gpt4 book ai didi

swift - 在 macOS 上使用 Swift 在 PDF 上绘图

转载 作者:搜寻专家 更新时间:2023-11-01 05:52:29 26 4
gpt4 key购买 nike

我的目标是在 PDF 上书写文本,如注释。

我实现了将 PDFPage 转换为 NSImage,我在 NSImage 上绘制,然后保存由图像形成的 PDF。

let image = NSImage(size: pageImage.size)        
image.lockFocus()

let rect: NSRect = NSRect(x: 50, y: 50, width: 60, height: 20)
"Write it on the page!".draw(in: rect, withAttributes: someAttributes)

image.unlockFocus()

let out = PDFPage(image: image)

问题显然是 out(输出 PDF 的新页面)是图像的 PDFPage 而不是常规图像。因此输出的 PDF 非常大,您无法在其上复制和粘贴任何内容。这只是一系列图像。

我的问题是是否有一种方法可以在不使用 NSImage 的情况下以编程方式在 PDF 页面上添加简单文本。有什么想法吗?

注意在 iOS 编程中有这个类 UIGraphicsBeginPDFPageWithInfo 这对我的情况很有帮助。但是我找不到用于 macOS 开发的类似类。

最佳答案

您可以在 macOS 上创建一个 PDF 图形上下文并在其中绘制一个 PDFPage。然后,您可以使用 Core Graphics 或 AppKit 图形将更多对象绘制到上下文中。

这是我通过打印您的问题创建的测试 PDF: input PDF

下面是将该页面绘制到 PDF 上下文中,然后在其上绘制更多文本的结果:

output PDF

这是我编写的用于将第一个 PDF 转换为第二个 PDF 的代码:

import Cocoa
import Quartz

let inUrl: URL = URL(fileURLWithPath: "/Users/mayoff/Desktop/test.pdf")
let outUrl: CFURL = URL(fileURLWithPath: "/Users/mayoff/Desktop/testout.pdf") as CFURL

let doc: PDFDocument = PDFDocument(url: inUrl)!
let page: PDFPage = doc.page(at: 0)!
var mediaBox: CGRect = page.bounds(for: .mediaBox)

let gc = CGContext(outUrl, mediaBox: &mediaBox, nil)!
let nsgc = NSGraphicsContext(cgContext: gc, flipped: false)
NSGraphicsContext.current = nsgc
gc.beginPDFPage(nil); do {
page.draw(with: .mediaBox, to: gc)

let style = NSMutableParagraphStyle()
style.alignment = .center

let richText = NSAttributedString(string: "Hello, world!", attributes: [
NSFontAttributeName: NSFont.systemFont(ofSize: 64),
NSForegroundColorAttributeName: NSColor.red,
NSParagraphStyleAttributeName: style
])

let richTextBounds = richText.size()
let point = CGPoint(x: mediaBox.midX - richTextBounds.width / 2, y: mediaBox.midY - richTextBounds.height / 2)
gc.saveGState(); do {
gc.translateBy(x: point.x, y: point.y)
gc.rotate(by: .pi / 5)
richText.draw(at: .zero)
}; gc.restoreGState()

}; gc.endPDFPage()
NSGraphicsContext.current = nil
gc.closePDF()

关于swift - 在 macOS 上使用 Swift 在 PDF 上绘图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44640022/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com