Embed hyperlink in PDF using Core Graphics on iOS

后端 未结 2 2163
攒了一身酷
攒了一身酷 2021-01-05 16:03

I\'m trying to do a quite simple thing: write an URL inside a PDF file that can be actually clicked by the user.

I know for sure that using libharu it can be done. W

2条回答
  •  暗喜
    暗喜 (楼主)
    2021-01-05 16:30

    Here is converted code for Swift 5

    let context = UIGraphicsGetCurrentContext()
    let ctm = context?.ctm
    
    // Translate the origin to the bottom left.
    // Notice that 842 is the size of the PDF page. 
    ctm?.translatedBy(x: 0.0, y: 842)
    
    // Flip the handedness of the coordinate system back to right handed.
    ctm?.scaledBy(x: 1.0, y: -1.0)
    
    var xformRect: CGRect? = nil
    if let ctm = ctm {
        xformRect = frameRect.applying(ctm)
    }
    
    let url = URL(string: text)
    if let url = url {
        UIGraphicsSetPDFContextURLForRect(url, xformRect ?? CGRect.zero)
    }
    
    context?.saveGState()
    
    let attributesDict =[
            .foregroundColor: UIColor.blue,
            .underlineStyle: NSUnderlineStyle.single.rawValue
        ]
    let attString = NSMutableAttributedString(string: url?.absoluteString ?? "", attributes: attributesDict as? [NSAttributedString.Key : Any])
    
    attString?.draw(in: frameRect)
    
    context?.restoreGState()
    

提交回复
热议问题