Swift PDF 渲染任何 UIView 或 UIViewController PDFKit

标签 swift ios-pdfkit apple-pdfkit

我做了一些研究,我发现我可以使用 PDFKit 库绘制图像、字符串、形状。有什么简单的方法可以在 PDF 文档中绘制 UIViewUIViewController 的 View 吗?

我更喜欢 Swift 答案,但我也会接受 Objective-C。

最佳答案

UIView 以及包含在 UIViewController 中的 View ,可以用层渲染:

获取上下文:

let context = UIGraphicsGetCurrentContext()!

界面 View :

view.layoutIfNeeded()
view.layer.render(in: context)

UIViewController

controller.loadViewIfNeeded()
controller.view.layer.render(in: context)

完整的工作脚本:

let pdfMetadata =
[
    kCGPDFContextCreator: "MyAppName",
    kCGPDFContextAuthor: "TheAuthor"
]
UIGraphicsBeginPDFContextToFile(filePath, CGRect.zero, pdfMetadata)

let context = UIGraphicsGetCurrentContext()!

UIGraphicsBeginPDFPage()

controller.loadViewIfNeeded()
controller.view.layer.render(in: context)

UIGraphicsEndPDFContext()

关于Swift PDF 渲染任何 UIView 或 UIViewController PDFKit,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56741975/

相关文章:

ios - 测试 iOS 应用程序时,为什么不报告所有应用程序崩溃?

swift - 记录游戏得分的代码

ios - 当有长按手势识别器时,UIButton 不会改变文本颜色

swift - IOS PDFKit - 注释内容仅在选中时可见

ios - 检测到 PDFView 确实滚动了

ios - PDFKit/PDFView 禁用与表单注释的交互

arrays - 如何获取数组中元素的位置

ios - Swift PDFKit : Inconsistent behaviour with PDFView. currentDestination 和 PDFView.go(到目的地:PDFDestination)

ios - 应该如何定义 PDFView usePageViewController withViewOptions : 的选项字典