首页 > 解决方案 > 如何设置 PDFPage 标签并重绘缩略图?

问题描述

我正在尝试在 macOS 上快速从 NSImages 创建一个多页 PDF 文件。如何设置 PDFPage 标签以及如何触发预览缩略图的生成。

PDFPage 有一个标签变量: https ://developer.apple.com/documentation/pdfkit/pdfpage/1504088-label

但我没有找到设置标签的方法 我试图将标签设置为 1 :page.setValue("1", forKey: "label")但这什么也没做

我没有找到触发缩略图生成的方法。

一页的代码示例:

//stroyboard pdfView
@IBOutlet weak var myPdfView: PDFView!

//Storyboad PDFThumbnailView
@IBOutlet weak var myPDFThumbnailView:PDFThumbnailView!

//create a new PDFDocument
var myPDFDocument = PDFDocument()

//image path
guard let pngPath = Bundle.main.url(forResource: "example", withExtension: "png") else { return }

//create NSImage
if let firstPageImage = NSImage(contentsOf: pngPath){

    //PDFPage
    if let page = PDFPage(image: firstPageImage) {

        //insert Page in PDFDocument
        myPDFDocument.insert(page, at: myPDFDocument.pageCount)

    }
}

//set PDFDocument
myPdfView.document = myPDFDocument

//set PDFView
myPDFThumbnailView.pdfView = myPdfView

预期结果:带有标签“1”的 PDF 页面缩略图出现在 PDFThumbnailView 中,并且 PDF 页面在 PDFView 中呈现。

实际结果:PDFThumbnailView 中出现带有“Label”标签的空白缩略图,并且 PDF 页面在 PDFView 中呈现。

编辑: 我解决问题的解决方法是将 PDFDocument 保存到磁盘并重新加载。它不漂亮,但它正在工作......欢迎任何建议!

myPDFDocument.write(toFile: "path/to/temp/folder/mytemp.pdf")
if let document = PDFDocument(url: URL(fileURLWithPath: "path/to/temp/folder/mytemp.pdf")) 
{
    myPDFDocument = document
}

标签: swiftapple-pdfkit

解决方案


There doesn't appear to be a method for setting the label of a PDFPage. The label property is Read-only.

This value is actually the displayed page number, so shouldn't normally need setting.


推荐阅读