How to delete pages from a PDF document
You can delete pages of a PDF document using the PdfProcessor
in three steps:
- Load the
PdfDocument
you want to modify. - Create a
PdfProcessorTask
that removes the desired pages. - 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.") }}
@Overridepublic 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."));}
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.