如何以编程方式创建 PDFOutline

How to create PDFOutline programmatically

我在尝试在 PDF 文件中创建 Table 个内容对象时遇到问题。我不确定我是否从 Apple 有限的文档中理解了这个过程。

我正在使用 python,但欢迎使用任何语言的令人信服的示例来解释它应该如何工作。该代码创建了一个新的 PDF 文档,但在预览中看不到大纲项。我试过只使用 myOutline 作为根对象,但这也不起作用。

pdfURL = NSURL.fileURLWithPath_(infile)
myPDF = Quartz.PDFDocument.alloc().initWithURL_(pdfURL)
if myPDF:
    # Create Destination
    myPage = myPDF.pageAtIndex_(1)
    pagePoint = Quartz.CGPointMake(0,0)
    myDestination = Quartz.PDFDestination.alloc().initWithPage_atPoint_(myPage, pagePoint)

    # Create Outline
    myOutline = Quartz.PDFOutline.alloc().init()
    myOutline.setLabel_("Interesting")
    myOutline.setDestination_(myDestination)

    # Create a root Outline and add the first outline as a child
    rootOutline = Quartz.PDFOutline.alloc().init()
    rootOutline.insertChild_atIndex_(myOutline, 0)

    # Add the root outline to the document and save
    myPDF.setOutlineRoot_(rootOutline)
    myPDF.writeToFile_(outfile)

编辑:实际上,大纲正在保存到新文件中:我可以通过编程方式阅读它,它在 Acrobat 中显示为书签;但是,它没有出现在预览的 Table 目录中(是的,我检查了 "Hide" 东西)。如果我在 Acrobat 中添加另一个书签,那么两者都会显示在预览中。

所以我想要么我仍然做错了一些事情,但 'finish' PDFOutline 数据并不完全正确,而且 Acrobat 很友善;或者 PDFKit 中存在一个巨大的错误,这意味着您无法正确编写 PDFOutlines。我在 FWIW 的 Mountain Lion 上也有同样的行为。

这确实是预览版中的错误。如果它只包含一个子条目,它将不会列出 Table 的目录。

如果我用上面的代码添加更多的大纲,那么所有大纲都会出现在预览中。如果使用其他软件删除 目录 Table 中除一个 条目外的所有条目,则预览将不会显示 any.