How to Delete Pages from a PDF Document

You can delete pages of a PDF document using the PdfProcessor in three steps:

  1. Load the PdfDocument you want to modify.

  2. Create a PdfProcessorTask that removes the desired pages.

  3. Process the document, saving it to a new location.

Here’s how to do this in your PdfActivity:

override fun onDocumentLoaded(document: PdfDocument) {
    // Remove the pages with index 0 and 4.
    val task = PdfProcessorTask.fromDocument(document)
        .removePages(setOf(0, 4))

    // The output file must be different than the original document file.
    val outputFile = filesDir.resolve("${document.uid}-processed.pdf")

    // Process the document on a background thread. The newly created
    // document will have the pages removed.
    PdfProcessor.processDocumentAsync(task, outputFile)
        .ignoreElements()
        .subscribeOn(Schedulers.io())
        .observeOn(AndroidSchedulers.mainThread())
        .subscribe { Log.i(TAG, "Document successfully saved.") }
}
@Override
public void onDocumentLoaded(@NonNull PdfDocument document) {
    // Remove the pages with index 0 and 4.
    final PdfProcessorTask task = PdfProcessorTask.fromDocument(document)
        .removePages(new HashSet<>(Arrays.asList(0, 4)));

    // The output file must be different than the original document file.
    final File outputFile =
        new File(getFilesDir(), document.getUid() + "-processed.pdf");

    // Process the document on a background thread. The newly created
    // document will have the pages removed.
    PdfProcessor.processDocumentAsync(task, outputFile)
        .ignoreElements()
        .subscribeOn(Schedulers.io())
        .observeOn(AndroidSchedulers.mainThread())
        .subscribe(() -> Log.i("TAG", "Document successfully saved."));
}
Warning

When saving the processed document to an outputFile, the output file must be different than the input file. Writing back directly to the original document isn’t supported.