swiftmacoscgpdfdocument

How to use documentAttributes of CGPDFDocument


According to Apple's documentation CGPDFDocument has a var called documentAttributes:

var documentAttributes: [AnyHashable : Any]? { get set }

I'm having trouble seeing how to use this to either get, or set document attributes of a PDF in Swift. Xcode doesn't offer it as an auto-completion following a dot, e.g. myPDF.documentAttributes.

How do you use it? I'm trying to get/set the document metadata such as Author, Creator, Subject.


Solution

  • Had a second look at the link you provided. It's not CGPDFDocument but Quartz.PDFDocument. Heres one way to access it:

    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"])")
    }
    

    The list of keys differ from file to file so you need to check each one and deal with nil when the key is not available.


    To change the attributes:

    pdfDoc.documentAttributes?["Title"] = "Cheese"
    pdfDoc.write(to: URL(fileURLWithPath: "/path/to/file.pdf")) // save the PDF file