我正在开发一个小例程,该例程需要多个单页 PDF 并将它们合并到一个多页 PDF 中。我正在 Swift4/MacOS/Cocoa 中工作,但我一生都无法在 Swift 中找到任何类型的示例来创建大纲/仅遍历现有的大纲(我对此非常熟悉)。
使用对文档的最佳猜测,我想出了以下内容,我一直在摆弄它,但一点运气都没有。 PDF 输出得很好,但里面从来没有大纲/目录。这可能很简单,比如缺少作业或其他什么……任何线索将不胜感激。
顺便说一句,它处于两个循环而不是一个循环的原因是因为我想也许我需要先添加所有页面 - 但尝试这样做并没有什么区别。如果可能的话,最终只会有一个循环。
static func mergePagesIntoSinglePDF(streamId: String, numPages: Int)
{
let newPDF = PDFDocument()
var directoryURLStr = ""
for pageNum in 1...numPages {
let directoryUrl = getFileURL(streamId: streamId, recNum: pageNum)
directoryURLStr = directoryUrl!.absoluteString
if let pdfDocument = PDFDocument(url: directoryUrl!),
let pdfPage = pdfDocument.page(at: 0)
{
newPDF.insert(pdfPage, at: newPDF.pageCount)
}
}
for pageNum in 1...numPages {
let newDest:PDFDestination = PDFDestination.init(page: newPDF.page(at: pageNum-1)!, at:NSPoint(x:1,y:1))
let newTOCEntry:PDFOutline = PDFOutline.init()
newTOCEntry.destination = newDest
newTOCEntry.label = "This is page: \(pageNum)"
newPDF.outlineRoot?.insertChild(newTOCEntry, at: pageNum-1)
}
directoryURLStr = (getFileURL(streamId: streamId)?.absoluteString)!
let fileURL = URL(string: directoryURLStr)
newPDF.write(to: fileURL!)
}
最佳答案
看来我比我想象的要近得多。主要问题是我需要为 PDFOutline 创建一个根节点。我还添加了一些内容以使 NSPoint 更智能一些,因为您不能真正假设 PDF 中的“1,1” hack 是一个有效的坐标(通常是......但不能假设)。当然,现在可以删除双循环,但为了清楚起见,我将其保留在:
static func mergePagesIntoSinglePDF(streamId: String, numPages: Int)
{
let newPDF = PDFDocument()
newPDF.outlineRoot = PDFOutline(); // CREATE PDF OUTLINE ROOT NODE!
var directoryURLStr = ""
for pageNum in 1...numPages {
let directoryUrl = getFileURL(streamId: streamId, recNum: pageNum)
directoryURLStr = directoryUrl!.absoluteString
if let pdfDocument = PDFDocument(url: directoryUrl!),
let pdfPage = pdfDocument.page(at: 0)
{
newPDF.insert(pdfPage, at: newPDF.pageCount)
}
}
for pageNum in 1...numPages {
let pdfPage = newPDF.page(at: pageNum-1)!
// ADD A LITTLE CODE TO MAKE THE NSPoint IN THE DESTINATION MORE SOUND
let pdfPageRect = pdfPage.bounds(for: PDFDisplayBox.mediaBox)
let topLeft = NSMakePoint(pdfPageRect.minX, pdfPageRect.height + 20)
let destination = PDFDestination(page: pdfPage, at: topLeft)
let newDest = PDFDestination(page: pdfPage, at:topLeft)
let newTOCEntry = PDFOutline()
newTOCEntry.destination = newDest
newTOCEntry.label = "\(streamId) page \(pageNum)"
newPDF.outlineRoot!.insertChild(newTOCEntry, at: pageNum-1)
}
directoryURLStr = (getFileURL(streamId: streamId)?.absoluteString)!
let fileURL = URL(string: directoryURLStr)
newPDF.write(to: fileURL!)
}
关于swift - 使用 PDFOutline 将 TOC 添加到 Swift/Cocoa 中的 PDFDocument,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51689514/