[英]Create PDF in Swift with clickable link in PDF
I want to generate PDF from data with clickable link inside.我想从内部带有可点击链接的数据生成 PDF。 I have created PDF using SimplePDF ( https://github.com/nRewik/SimplePDF ) library but couldn't find the way to how make link clickable.
我使用 SimplePDF ( https://github.com/nRewik/SimplePDF ) 库创建了 PDF,但找不到如何使链接可点击的方法。
Help will be appreciated.帮助将不胜感激。
Try this as text on your pdf试试这个作为 pdf 上的文本
let attributedString = NSMutableAttributedString(string: "Life Saver!")
attributedString.addAttribute(.link, value: "https://www.stackoverflow.com", range: NSRange(location: 19, length: 55))
textView.attributedText = attributedString
My problem was, that I created the PDF from a IB-constructed view.我的问题是,我从 IB 构建的视图创建了 PDF。 I used
writePDF
and rendered the entire view with view.layer.render(in: context.cgContext)
, and the attributed texts within the labels or text views weren't clickable (although they appeared well).我使用
writePDF
并使用view.layer.render(in: context.cgContext)
渲染整个视图,并且标签或文本视图中的属性文本不可点击(尽管它们看起来不错)。 So I had to add it as an extra text:所以我不得不将它添加为额外的文本:
mutableString.draw(in: CGRect(x: 0, y: 0, width: 500, height: 200))
This is the core of my solution:这是我的解决方案的核心:
let pdfRenderer = UIGraphicsPDFRenderer(bounds: pdfView.bounds)
do {
try pdfRenderer.writePDF(to: outputFileURL, withActions: { context in
context.beginPage()
pdfView.layer.render(in: context.cgContext)
mutableString.draw(in: CGRect(x: 0, y: 0, width: 500, height: 200))
})
} catch {
print("Could not create PDF file: \(error)")
}
This seems to be working from iOS 15 however.然而,这似乎适用于 iOS 15。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.