The following Swift script reproduces this problem.
// PDF Widget Annotations Disappear After Saving in PDFKit (Demo)
// Feedback report: FB24866826
import Foundation
import PDFKit
// PART 1: Creates a new "original" PDF that contains a page with a checkbox.
// The PDF syntax in the resulting file (output1.pdf) is properly formatted.
let fileURL = URL(fileURLWithPath: "output1.pdf")
// Create a new PDF document with a new, blank page in document
let pdfDocument = PDFDocument()
let pdfPage = PDFPage()
pdfDocument.insert(pdfPage, at: 0)
// Create new checkbox widget annotation
let checkbox = PDFAnnotation(
bounds: CGRect(x: 100, y: 500, width: 20, height: 20),
forType: .widget,
withProperties: nil)
checkbox.widgetFieldType = .button
checkbox.widgetControlType = .checkBoxControl
// Add checkbox to page
pdfPage.addAnnotation(checkbox)
// Write document to file
if pdfDocument.write(to: fileURL) {
print("1. PDF successfully saved to \(fileURL.path)")
} else {
print("1. Failed to save PDF.")
exit(1)
}
// PART 2: Opens file created in Part 1, updates checkbox state, and writes to new file.
// The PDF syntax in the resulting file (output2.pdf) is not properly formatted.
// Open document from PDF file created in Part 1
guard let openedDocument = PDFDocument(url: fileURL) else {
print("Failed to open \(fileURL.path).")
exit(1)
}
// Get the first page
guard let firstPage = openedDocument.page(at: 0) else {
print("No pages found in \(fileURL.path).")
exit(1)
}
// Get first annotation on page (this should be the checkbox)
guard let checkbox = firstPage.annotations.first else {
print("No annotations found in \(fileURL.path).")
exit(1)
}
// Update checkbox state to "on"
checkbox.buttonWidgetState = .onState
// Write document to second file
let newFileURL = URL(fileURLWithPath: "output2.pdf")
if openedDocument.write(to: newFileURL) {
print("2. PDF successfully re-opened, modified, and saved to \(newFileURL.path)")
} else {
print("2. Failed to save the modified PDF to a new file.")
}