【问题标题】:Draw text on all pages of PDF using PDFKit使用 PDFKit 在 PDF 的所有页面上绘制文本
【发布时间】:2022-08-23 20:54:43
【问题描述】:

我正在使用以下代码在 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

标签: swift macos pdfkit


【解决方案1】:

这里的主要问题是重新创建了上下文,对于多个页面,我们应该写入同一个上下文(它通过 beginPDFPage/endPDFPage 对管理页面)。

这是固定代码。使用 Xcode 13.4 / macOS 12.4 测试

let pdffile = PDFDocument(url: input)
let data = NSMutableData()
let consumer = CGDataConsumer(data: data as CFMutableData)!

// create common context with no mediaBox, we will add it later
// per-page (because, actually they might be different)
let context = CGContext(consumer: consumer, mediaBox: nil, nil)!

for y in stride(from: 0, to: pdffile!.pageCount, by: 1)
{
    let page: PDFPage = pdffile!.page(at: y)!

    // re-use media box of original document as-is w/o changes !!
    var mediaBox = page.bounds(for: PDFDisplayBox.mediaBox)
    NSGraphicsContext.current = NSGraphicsContext(cgContext: context, flipped: false)

    // prepare mediaBox data for page setup
    let rectData = NSData(bytes: &mediaBox, length: MemoryLayout.size(ofValue: mediaBox))

    context.beginPDFPage([kCGPDFContextMediaBox as String: rectData] as CFDictionary)   // << here !!

    page.draw(with: .mediaBox, to: context) // << original !!
    text.draw(in:drawrect,withAttributes:textFontAttributes) // << over !!

    context.endPDFPage()
}
context.closePDF()  // close entire document

let anotherDocument = PDFDocument(data:data as Data)
// ... as used before

【讨论】:

    猜你喜欢
    • 2018-11-22
    • 2012-08-22
    • 1970-01-01
    • 2012-04-30
    • 2016-11-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-07-27
    相关资源
    最近更新 更多