首页 > 解决方案 > 如何快速分页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]
    
}

标签: swiftpdf

解决方案


经过一周的搜索,我终于找到了这个!

这是拆分 PDF 的最简单和最确定的方法!

https://pspdfkit.com/blog/2019/converting-attributed-string-to-pdf/


推荐阅读