Writing metadata to a pdf using pyobjc

后端 未结 2 1384
终归单人心
终归单人心 2021-02-09 17:18

I\'m trying to write metadata to a pdf file using the following python code:

from Foundation import *
from Quartz import *

url = NSURL.fileURLWithPath_(\"test.p         


        
2条回答
  •  闹比i
    闹比i (楼主)
    2021-02-09 17:28

    Mark is on the right track, but there are a few peculiarities that should be accounted for.

    First, he is correct that pdfdoc.documentAttributes is an NSDictionary that contains the document metadata. You would like to modify that, but note that documentAttributes gives you an NSDictionary, which is immutable. You have to convert it to an NSMutableDictionary as follows:

    attrs = NSMutableDictionary.alloc().initWithDictionary_(pdfDoc.documentAttributes())
    

    Now you can modify attrs as you did. There is no need to write PDFDocument.PDFDocumentTitleAttribute as Mark suggested, that one won't work, PDFDocumentTitleAttribute is declared as a module-level constant, so just do as you did in your own code.

    Here is the full code that works for me:

    from Foundation import *
    from Quartz import *
    
    url = NSURL.fileURLWithPath_("test.pdf")
    pdfdoc = PDFDocument.alloc().initWithURL_(url)
    
    attrs = NSMutableDictionary.alloc().initWithDictionary_(pdfdoc.documentAttributes())
    attrs[PDFDocumentTitleAttribute] = "THIS IS THE TITLE"
    attrs[PDFDocumentAuthorAttribute] = "A. Author and B. Author"
    
    pdfdoc.setDocumentAttributes_(attrs)
    pdfdoc.writeToFile_("mynewfile.pdf")
    

提交回复
热议问题