Open PDFs from In-Memory Data in Java

This guide explains how to open a PDF document from an in-memory data provider.

PdfDocument expects a DataProvider to read from. To open a file from application memory, you must extend the InputStreamDataProvider, which has an openInputStream method returning an object of type InputStream to provide the data.

This example creates a ResourceDataProvider that extends the InputStreamDataProvider to provide an InputStream from a local asset with a string name:

private static class ResourceDataProvider extends InputStreamDataProvider {
    @NotNull
    private String assetFilename;

    // Constructs a resource data provider.
    // @param assetFilename The name of the asset file.
    ResourceDataProvider(@NotNull final String assetFilename) {
        this.assetFilename = assetFilename;
    }

    // `openInputStream` must be overridden to provide the data stream.
    // Here we also check the resource exists and throw if not.
    @NotNull
    @Override
    protected InputStream openInputStream() throws Exception {
        InputStream resource = getClass().getClassLoader().getResourceAsStream(assetFilename);
        if (resource == null) throw new FileNotFoundException("Unable to find resource " + assetFilename);
        return resource;
    }

    @Override
    public long getSize() {
        try {
            return openInputStream().available();
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        }
    }

    @Override
    public @Nullable String getTitle() {
        return assetFilename;
    }
}

You can use ResourceDataProvider to open a PDF document in your project asset folder:

PdfDocument document = PdfDocument.open(new ResourceDataProvider("documentInAssets.pdf"));