根据Apple的文档
CGPDFDocument
,有一个名为documentAttributes
:
var documentAttributes: [AnyHashable : Any]? { get set }
我无法看到如何使用它在 Swift 中获取或设置 PDF 的文档属性。Xcode 不提供它作为一个点后的自动完成,例如myPDF.documentAttributes
.
你如何使用它?我正在尝试获取/设置文档元数据,例如作者、创建者、主题。
根据Apple的文档
CGPDFDocument
,有一个名为documentAttributes
:
var documentAttributes: [AnyHashable : Any]? { get set }
我无法看到如何使用它在 Swift 中获取或设置 PDF 的文档属性。Xcode 不提供它作为一个点后的自动完成,例如myPDF.documentAttributes
.
你如何使用它?我正在尝试获取/设置文档元数据,例如作者、创建者、主题。
再次查看您提供的链接。不是CGPDFDocument
但是Quartz.PDFDocument
。这是访问它的一种方法:
let pdfDoc = PDFDocument(url: URL(fileURLWithPath: "/path/to/file.pdf"))!
if let attributes = pdfDoc.documentAttributes {
let keys = attributes.keys // the set of keys differ from file to file
let firstKey = keys[keys.startIndex] // get the first key, whatever the turns out to be
// since Dictionaries are not ordered
print("\(firstKey): \(attributes[firstKey]!)")
print("Title: \(attributes["Title"])")
}
密钥列表因文件而异,因此您需要检查每个文件并nil
在密钥不可用时进行处理。
要更改属性:
pdfDoc.documentAttributes?["Title"] = "Cheese"
pdfDoc.write(to: URL(fileURLWithPath: "/path/to/file.pdf")) // save the PDF file