swift - 如何快速分页PDF
问题描述
我不知道如何为我正在创建的 PDF 创建分页符,我尝试了几种不同的创建 PDF 的方法,结果都一样。我正在尝试为长的多行标签创建 PDF。
当我尝试通过 UIActivityView 仅打印一个字符串时,它可以完美地处理分页符,正如您所期望的那样。但是,当我尝试保存或打印 PDF 时,它在打印预览中或保存 PDF 时仅显示一页。
如何在 PDF 中包含所有文本?
这是我现在只为 UIActivityView 调用 PDF 的共享函数
// Share function for share button
@objc func shareTapped() {
// Create printable string
let printableString = "Line measurement: \(sizeTransfer.text ?? "No data")\nCalculated size: \(heightSizeTransfer.text ?? "No data")\nHeight: \(heightTransfer.text ?? "No data")\n \nCoursing results:\n \n \(calcOutput.text ?? "No data")"
// String print formatting
let attrs = [NSAttributedString.Key.font: UIFont.systemFont(ofSize: 12), NSAttributedString.Key.foregroundColor: UIColor.black]
let str = NSAttributedString(string: printableString, attributes: attrs)
let print = (UISimpleTextPrintFormatter(attributedText: str))
// Saving string file
let tempDir = FileManager.default.temporaryDirectory
let stringFileName = "Coursing Printout"
let tempStringDir = tempDir.appendingPathComponent(stringFileName)
try? printableString.write(to: tempDir, atomically: true, encoding: String.Encoding.utf8)
// Create PDF
let pageRect = CGRect(x: 0, y: 0, width: 612, height: 792)
let renderer = UIGraphicsPDFRenderer(bounds: pageRect)
let text = printableString
let textAttributes = [NSAttributedString.Key.font: UIFont.systemFont(ofSize: 12)]
let formattedText = NSAttributedString(string: text, attributes: textAttributes)
let data = renderer.pdfData { ctx in
ctx.beginPage()
formattedText.draw(in: pageRect.insetBy(dx: 50, dy: 50))
}
// Give sharing functionality
let vc = UIActivityViewController(activityItems: [data], applicationActivities: [])
present(vc, animated: true)
vc.excludedActivityTypes = [.assignToContact, .addToReadingList]
}
解决方案
经过一周的搜索,我终于找到了这个!
这是拆分 PDF 的最简单和最确定的方法!
https://pspdfkit.com/blog/2019/converting-attributed-string-to-pdf/
推荐阅读
- javascript - 如何在js中进行去抖动
- debugging - PhpStorm 可以调试已重定向到使用 Nginx 的 X-Accel-Redirect 的文件吗?
- compiler-construction - 这个编译器图不准确吗?
- python - 如何快速有效地检查图像是否主要是背景?
- reactjs - 如何在上述字段中显示 2 个输入的值?
- ansible - 在继续操作手册的其余部分之前,如何汇总存储有关远程主机的自定义事实?
- c - 链表的结构相对于存储中的公共结构有什么特别之处吗?
- firebase - 如何在 React Native(iOS)中处理 FCM 仅数据消息
- python - 是否有 Microsoft SQL Server 地理/几何类型的示例 SQLAlchemy UserDefinedType?
- mysql - 如何修复日期函数的 SQL 查询?