Convert Instant JSON to XFDF on Android

To achieve interoperability between XFDF (XML Forms Data Format) and JSON files that conform to PSPDFKit’s annotation schema, PSPDFKit has APIs for importing JSON data into a PDF and exporting it as XFDF.

Unlike PSPDFKit’s JSON schema, XFDF doesn’t have a concept of differentials for describing changes to a PDF (e.g. deleted annotations, new bookmarks, edited forms). XFDF is instead a representation of all annotation and form data inside a PDF document at a point in time. Since these concepts don’t directly translate to each other, there are some limitations that wouldn’t be represented in the final XFDF.

The resulting XFDF file will include all the annotations and form data you specify. The XFDF file will conform to the ISO Specification, and can be imported by conforming third-party viewers, such as Adobe Acrobat.

You can import conforming JSON files and export to XFDF using the following code:

fun export(inputJsonFile: File, document: PdfDocument, outputXfdfFile: File) {
    // Import the data from the JSON file into the PDF document.
    val jsonProvider = ContentResolverDataProvider(Uri.fromFile(inputJsonFile))
    DocumentJsonFormatter.importDocumentJson(document, jsonProvider)

    // Writing XFDF requires specifying the annotations to be exported. Here, all
    // annotations of the document to be exported are fetched.
    val allAnnotations = (0 until document.pageCount)
        .flatMap { pageIndex -> document.annotationProvider.getAnnotations(pageIndex) }

    // Finally, write the data. The method will automatically close the output stream upon completion.
    XfdfFormatter.writeXfdf(document, allAnnotations, emptyList(), outputXfdfFile.outputStream())
}
void export(@NonNull final File inputJsonFile,
            @NonNull final PdfDocument document,
            @NonNull final File outputXfdfFile) throws IOException {
    // Import the data from the JSON file into the PDF document.
    final DataProvider jsonProvider = new ContentResolverDataProvider(Uri.fromFile(inputJsonFile));
    DocumentJsonFormatter.importDocumentJson(document, jsonProvider);

    // Writing XFDF requires specifying the annotations to be exported. Here, all
    // annotations of the document to be exported are fetched.
    final List<Annotation> allAnnotations = new ArrayList<>();
    for(int pageIndex = 0; pageIndex < document.getPageCount(); pageIndex++) {
        allAnnotations.addAll(document.getAnnotationProvider().getAnnotations(pageIndex));
    }

    // Finally, write the data. The method will automatically close the output stream upon completion.
    XfdfFormatter.writeXfdf(document, allAnnotations, emptyList(), new FileOutputStream(outputXfdfFile));
}