使用PDFKIT在PDF的所有页面上绘制文本
我正在使用以下代码在PDF文档上绘制文本。这似乎仅在单个页面上绘制文本。 。如何在所有页面上绘制字符串?
var pdffile=PDFDocument(url: input)
let data = NSMutableData()
let consumer = CGDataConsumer(data: data as CFMutableData)!
for y in stride(from: 0, to: pdffile!.pageCount, by: 1)
{
let page: PDFPage = pdffile!.page(at: y)!
let outputBounds = page.bounds(for: PDFDisplayBox.mediaBox)
var mediaBox = CGRect(x: 0, y: 0, width: outputBounds.size.width, height: outputBounds.size.height)
let context = CGContext(consumer: consumer, mediaBox: &mediaBox, nil)!
NSGraphicsContext.current = NSGraphicsContext(cgContext: context, flipped: false)
context.beginPDFPage(nil)
page.draw(with: .mediaBox, to: context)
text.draw(in:drawrect,withAttributes:textFontAttributes);
context.endPDFPage()
context.closePDF()
}
let anotherDocument = PDFDocument(data:data as Data)
pdfview.document=anotherDocument
I'm using the following code to draw text on a PDF Document.This seems to draw the text only on a single page.I'm trying to iterate through each page,draw string on it and finally display the PDF document from the MutableData. How do I draw the string on all pages?
var pdffile=PDFDocument(url: input)
let data = NSMutableData()
let consumer = CGDataConsumer(data: data as CFMutableData)!
for y in stride(from: 0, to: pdffile!.pageCount, by: 1)
{
let page: PDFPage = pdffile!.page(at: y)!
let outputBounds = page.bounds(for: PDFDisplayBox.mediaBox)
var mediaBox = CGRect(x: 0, y: 0, width: outputBounds.size.width, height: outputBounds.size.height)
let context = CGContext(consumer: consumer, mediaBox: &mediaBox, nil)!
NSGraphicsContext.current = NSGraphicsContext(cgContext: context, flipped: false)
context.beginPDFPage(nil)
page.draw(with: .mediaBox, to: context)
text.draw(in:drawrect,withAttributes:textFontAttributes);
context.endPDFPage()
context.closePDF()
}
let anotherDocument = PDFDocument(data:data as Data)
pdfview.document=anotherDocument
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这里的主要问题是重新创建的上下文,对于我们应该写入相同上下文的多个页面(它通过beginpdfpage/endpdfpage对管理页面)。
这是固定的代码。用Xcode 13.4 / MacOS测试12.4
The main issue here is that context recreated, for multiple pages we should write into the same context (it manages pages by beginPDFPage/endPDFPage pair).
Here is fixed code. Tested with Xcode 13.4 / macOS 12.4