【发布时间】:2019-04-18 11:52:55
【问题描述】:
我正在我的应用中开发一个功能,让用户可以将他们的数据导出到设计精美的 PDF 中。
我为此使用了UIGraphicsPDFRenderer,并通过了Apple's documentation。
我在添加诸如“第 x 页,共 y 页”之类的页脚时遇到问题。虽然“x”很容易 - 我在确定“y”时遇到了麻烦,因为我只知道在完全呈现 PDF 后我的文档有多少页。由于布局相当复杂,我无法提前确定页数。
现在我也知道新页面是用beginPage() 创建的。有没有办法转到上一页? - 因为那时我可以简单地浏览文档并添加缺少的页脚。
这是我在 Swift 4 中使用的代码(非常简化,但应该足以理解):
let pdf = renderer.pdfData { (context) in
let attributes = [ NSFontAttributeName : UIFont.boldSystemFont(ofSize: 15) ]
// page 1
context.beginPage()
NSAttributedString(string: "Page 1", attributes: attributes).draw(in: CGRect(x: 0, y: 0, width: 500, height: 200))
// page 2
context.beginPage()
NSAttributedString(string: "Page 2", attributes: attributes).draw(in: CGRect(x: 0, y: 0, width: 500, height: 200))
// page 3
context.beginPage()
NSAttributedString(string: "Page 3", attributes: attributes).draw(in: CGRect(x: 0, y: 0, width: 500, height: 200))
// Now that I know that the PDF will have 3 pages, add the footer on all 3 pages - but how?
}
}
【问题讨论】:
-
请提供您目前尝试过的代码。
-
您不能创建一个没有页脚的 pdf、获取 pageCount、丢弃该 pdf 并创建另一个或简单地编辑页脚页数吗?
-
@fewlinesofcode 我添加了一个示例代码来了解我想要做什么。
-
@LeoDabus 谢谢,这是个好主意——肯定会奏效。唯一我不太喜欢的是,我或多或少地创建了两次相同的文档。我将不得不用大量数据对其进行测试,看看它会如何工作:)
-
@LeoDabus 感谢您的提示 - 添加了 Swift 版本(第 4 版)并更新了代码以使用 NSAttributedString。
标签: ios swift pdf apple-pdfkit