Shalugin
Shalugin

Reputation: 1204

How to change link colour in PDFKit in Swift?

I am using PDFKit to create a PDF from a view. My view has some UITextViews with links and I would like those links to be clickable in PDF. That I managed to achieve by using text.draw(at: textViewOrigin, withAttributes: attributes) method. However all links in PDF are always of standard tint iOS colour and I am struggling to change it to black. Any idea how I can do it?

Slightly simplified code looks like this:

    guard let documentsPath = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first else {
        fatalError("Cannot find document directory")
    }
    let url = documentsPath.appendingPathComponent("\(pdfTitle).pdf")

    let pdfRenderer = UIGraphicsPDFRenderer(bounds: view.bounds)
    hideTextView()

    do {
        try pdfRenderer.writePDF(to: url, withActions: { context in
            context.beginPage()
            view.layer.render(in: context.cgContext)
            
            let attributes = [
               NSAttributedString.Key.font: UIFont.systemFont(ofSize: 14),
               NSAttributedString.Key.link: "mailto:\(text)",
               NSAttributedString.Key.underlineStyle: NSUnderlineStyle.single.rawValue,
               NSAttributedString.Key.foregroundColor: UIColor.black, // NOT working - it changes colour of text, but colour of link won't change
            ] as [NSAttributedString.Key : Any]

            text.draw(at: textViewOrigin, withAttributes: attributes)
        })
    } catch {
        print("Could not create PDF file: \(error)")
    }

Upvotes: 1

Views: 50

Answers (1)

Shalugin
Shalugin

Reputation: 1204

I think I found a workaround:

  1. Draw text without a link attribute:

     let text = "https://www.stackoverflow.com"
    
     let attributes = [
          NSAttributedString.Key.font: UIFont.systemFont(ofSize: 14),
          NSAttributedString.Key.underlineStyle: NSUnderlineStyle.single.rawValue,
          NSAttributedString.Key.foregroundColor: UIColor.black, // Set colour here
     ] as [NSAttributedString.Key : Any]
    
     text.draw(at: textViewOrigin, withAttributes: attributes)
    
  2. Create PDFDocument from the url where PDF is rendered and allow PDFKit add hyperlink automatically:

     let pdfDocument = PDFDocument(url: url)
     let pdfData = pdfDocument?.dataRepresentation()
    

Text attributes will be those set in Step 1 and thanks to some magic that happens in PDFDocument(url: url) link will be clickable. Then we can share PDF or whatever else was the goal.

Upvotes: 0

Related Questions