How to delete pages from a PDF document?

Q: How to delete pages from a PDF document?

Deletion of pages of a PDF document can be done 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:

Copy
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
override fun onDocumentLoaded(document: PdfDocument) {
    // Remove pages with index 0 and 4.
    val task = PdfProcessorTask.fromDocument(document)
        .removePages(setOf(0, 4))

    // The output file must be different to 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.") }
}
Copy
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
@Override
public void onDocumentLoaded(@NonNull PdfDocument document) {
    // Remove 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 to 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."));
}

⚠️ Important: When saving the processed document to an outputFile, the output file must be different than the input file. Writing directly back to the original document is not supported.