XFDF Support


XFDF is an XML-like standard from Adobe XFDF for encoding annotations and forms (see XFDF Overview). It is compatible with Adobe Acrobat and several other 3rd-party frameworks.

Note: XFDF has various limitations. In most cases, using PSPDFKit Instant will result in a smaller file and better synchronization.

PSPDFKit for iOS supports both reading and writing XFDF and also offers an annotation provider subclass - PSPDFXFDFAnnotationProvider - that will save/load annotations to/from XFDF automatically.

Parsing XFDF

To read from XFDF file:

Copy
1
2
3
4
5
6
7
8
9
// Load from an example XFDF file.
let fileXML = URL(fileURLWithPath: "path/to/XFDF.xfdf")

// Create document and set up the XFDF provider.
let document = PSPDFDocument()
document.didCreateDocumentProviderBlock = {(_ documentProvider: PSPDFDocumentProvider) -> Void in
    let XFDFProvider = PSPDFXFDFAnnotationProvider(documentProvider: documentProvider, fileURL: fileXML)
    documentProvider.annotationManager.annotationProviders = [XFDFProvider]
}
Copy
1
2
3
4
5
6
7
8
9
// Load from an example XFDF file.
NSURL *fileXML = [NSURL fileURLWithPath:[docsFolder stringByAppendingPathComponent:@"XFDFTest.xfdf"]];

// Create document and set up the XFDF provider.
PSPDFDocument *document = [PSPDFDocument documentWithURL:documentURL];
document.didCreateDocumentProviderBlock = ^(PSPDFDocumentProvider *documentProvider) {
    PSPDFXFDFAnnotationProvider *XFDFProvider = [[PSPDFXFDFAnnotationProvider alloc] initWithDocumentProvider:documentProvider fileURL:fileXML];
    documentProvider.annotationManager.annotationProviders = @[XFDFProvider];
};

Exporting to XFDF

To export annotations and form fields from the document to XFDF file:

Copy
1
2
3
4
5
6
7
8
9
10
11
// Collect all existing annotations from the document
let annotations = document.allAnnotations(of: .all).values.flatMap { $0 }

// Write the file
let outputStream = OutputStream.init(url: fileXML, append: false)
do {
    try PSPDFXFDFWriter().write(annotations, to: outputStream!, documentProvider: document.documentProviders[0])
} catch {
    print("Failed to write XFDF file: \(error.localizedDescription))")
}
outputStream?.close()
Copy
1
2
3
4
5
6
7
8
9
10
11
12
13
// Collect all existing annotations from the document
NSMutableArray<PSPDFAnnotation *> *annotations = [NSMutableArray<PSPDFAnnotation *> array];
for (NSArray<PSPDFAnnotation *> *pageAnnotations in [document allAnnotationsOfType:PSPDFAnnotationTypeAll].allValues) {
    [annotations addObjectsFromArray:pageAnnotations];
}

// Write the file
NSError *error;
NSOutputStream *outputStream = [NSOutputStream outputStreamWithURL:fileXML append:NO];
if (![[PSPDFXFDFWriter new] writeAnnotations:annotations toOutputStream:outputStream documentProvider:document.documentProviders[0] error:&error]) {
    NSLog(@"Failed to write XFDF file: %@", error.localizedDescription);
}
[outputStream close];
Was this page helpful? We're happy to answer any questions.