使用 UIGraphicsPDFRenderer 创建 PDF 时添加像 "page x of y" 这样的页脚

Add a footer like "page x of y" when creating a PDF using UIGraphicsPDFRenderer

我正在开发我的应用程序中的一项功能,让用户可以将他们的数据导出到设计精美的 PDF 中。

我为此使用了 UIGraphicsPDFRenderer,我经历了 Apple's documentation

我在添加 "page x of 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?
  }
}

UIGraphicsPDFRenderer 是一个仅向前的 pdf 生成器。
您有 2 个选择:

  1. (推荐) 在将数据写入 pdf 之前分析数据以确定它适合多少页。由于您的代码执行了分页符,因此您应该能够计算出您的数据需要多少页。
  2. 创建没有“第 x 页,共第 y 页”的文档并保存。创建一个新文档,打开以前保存的文档并将其页面绘制在新文档的页面上,然后添加“page x of y”。

2 更麻烦且效率低下,所以我会选择 1。因为保存、编辑和删除需要更多 CPU 和内存。