Import and Export Annotations from Instant JSON in Java

Annotations can be imported and exported with the PSPDFKit Instant JSON format.

Instant JSON is a serializable representation of the current changes to a document, i.e. a diff between the document’s saved and unsaved changes. This can be used to transfer a set of changes across devices without having to send the entire PDF, which could potentially be large.

In PSPDFKit for Java, we use the terms Instant JSON and Document JSON interchangeably.

Please see the Instant JSON guide for details on how the format works.

Exporting to Instant JSON

To generate Instant Document JSON, use PdfDocument.exportDocumentJson, which will take an WritableDataProvider to write the JSON to.

Exporting to a File

This is an example using a FileDataProvider:

File file = new File("instant.json");
document.exportDocumentJson(new FileDataProvider(filename));

Exporting to an In-Memory Data Provider

By extending WritableDataProvider to hold an array of data bytes (see the Save to a Custom Data Provider guide for details on implementing this), you can export the document Instant JSON to in-memory data:

CustomDataProvider customDataProvider = new CustomDataProvider();
document.exportDocumentJson(customDataProvider);
byte[] data = customDataProvider.read(customDataProvider.getSize(), 0);
// ... Do something with `data`.

Other reasons for implementing a custom WritableDataProvider could be for encrypting the exported JSON, for writing into a database, or for streaming the export to a remote server.

Importing from Instant JSON

The generated JSON in the previous example can be applied to a document using the PdfDocument.importDocumentJson method, which takes a DataProvider. This is an example using a FileDataProvider:

File file = new File("Assets/instant.json");
document.importDocumentJson(new FileDataProvider(file));

If the imported data is malformed or has no data, an exception will be thrown.

The DataProvider can be inherited from in order to implement custom readers — for example, for decrypting the imported JSON, for reading from a database, or for streaming from a remote server.

Modifying and Generating Instant JSON

You can use the Instant JSON format to generate or alter the JSON prior to importing it with the PdfDocument.importDocumentJson method described above.