1

I'm trying to create a multipage PDF file from NSImages in swift on macOS. How do i set the PDFPage label and how do i trigger the generation of the preview thumbnails.

PDFPage has a variable for the label: https://developer.apple.com/documentation/pdfkit/pdfpage/1504088-label

but i didn't find a way to set the label i tried to set the label to 1 with: page.setValue("1", forKey: "label") but this did nothing

I didn't find a way to trigger the generation of thumbnails.

code example for one page:

//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

Expected result: a thumbnail of the PDF page with the label "1" appears in PDFThumbnailView and the PDF pages are rendered in PDFView.

Actual result: a blank thumbnail with the label "Label" appears in PDFThumbnailView and the PDF pages are rendered in PDFView.

EDIT: My workaround to solve my problems is to save the PDFDocument to disk and reload it. It's not pretty but it's working... any advice is welcome!

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

1 Answers1

0

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.

benwiggy
  • 1,440
  • 17
  • 35
  • The Documentation (https://developer.apple.com/documentation/pdfkit/pdfpage/1504088-label) says: _Typically, the label is “1” for the first page, “2” for the second page, and so on, but nonnumerical labels are also possible (such as “xxi”, “4-1” and so on)._ so I assumed that there is a way to set this Label, to set it for example to "xxi". – Julian Hi Feb 27 '19 at 11:09
  • @JulianHi Yes, it is "possible" for a PDF that is being read to contain other types of value in the label, but there is no mechanism in PDFKit to set such values. (As far as I can tell from Apple's documentation of the API.) – benwiggy Feb 27 '19 at 11:26