Custom PDFPage drawing will not save to file despite appearing correctly in PDFView – works on iOS but not macOS

I am attempting to add custom page drawing in a PDFDocument on macOS. I adapted the Custom Graphics iOS sample code (https://developer.apple.com/documentation/pdfkit/custom_graphics), which appears possible on macOS based on this evidently successful 2018 example: https://stackoverflow.com/questions/53415176/how-can-i-save-a-watermark-on-pdf-file-and-export-to-desktop-macos-mojave. To adapt the sample, I cut out UIGraphicsPushContext(context), UIGraphicsPopContext(), and the code required to flip the context, as its orientation was already correct. (I tried flipping it, but it did not solve my problem below.)

What still works:

After the PDFDocumentDelegate is set, the PDFView correctly displays the pages with custom drawing. Further, if I insert the PDFDocument’s pages into a new PDFDocument using insert(_:at:), the PDFView will display the second document with the custom drawing.

The problem:

The problem is that using either of the methods below will result in a document that contains all the expected elements, including PDFAnnotations, with this exception regarding the PDFPage subclass’s draw(with:to:): The original page can be drawn/removed by adding/removing super.draw(with:to:), but any other drawing in this method is not preserved, despite appearing correctly in the PDFView.

These methods produce the problem:

  1. Using PDFDocument’s write(to:) to save to a file. The file is successfully saved with all elements except the custom drawing.
  2. Using PDFDocument’s dataRepresentation() to convert the document to Data and then using init(data:) to turn it back into a PDFDocument. The PDFDocument appears as before, except without the custom drawing.

By contrast, on iOS/Mac Catalyst, both of these methods reproduce the custom drawing. What am I doing wrong here? Is it perhaps a bug, or is this drawing just not possible on macOS? I can paste the full code below if needed. I am using Xcode 13.0 and Big Sur 11.6 on a 2015 MBP.

Update: The problem persists in Xcode 13.1 with Big Sur 11.6, Big Sur 11.6.1, and Monterey 12.0.1.

Custom PDFPage drawing will not save to file despite appearing correctly in PDFView – works on iOS but not macOS
 
 
Q