Flatten PDF form fields on Android
Use PdfProcessor to flatten PDF form fields.
Initialize Nutrient before using the processor API. Otherwise, processing fails. For details, refer to the initializing Nutrient guide.
Form elements use the AnnotationType.WIDGET annotation type. For flattening concepts and printing behavior, refer to the flattening annotations guide.
The following example flattens all form elements:
// Flatten only forms, and copy everything else.val task = PdfProcessorTask.fromDocument(document) .changeAllAnnotations(PdfProcessorTask.AnnotationProcessingMode.KEEP) .changeAnnotationsOfType(AnnotationType.WIDGET, PdfProcessorTask.AnnotationProcessingMode.FLATTEN)// Write to a new file. The output can't be the file the document was opened from.val outputFile = File(context.filesDir, "flattened.pdf")
// `processDocument()` blocks until processing finishes, so run it in the background.lifecycleScope.launch(Dispatchers.IO) { PdfProcessor.processDocument(task, outputFile)}// Flatten only forms, and copy everything else.PdfProcessorTask task = PdfProcessorTask.fromDocument(document) .changeAllAnnotations(PdfProcessorTask.AnnotationProcessingMode.KEEP) .changeAnnotationsOfType(AnnotationType.WIDGET, PdfProcessorTask.AnnotationProcessingMode.FLATTEN);// Write to a new file. The output can't be the file the document was opened from.File outputFile = new File(context.getFilesDir(), "flattened.pdf");
// `processDocument()` blocks until processing finishes, so run it on a background thread.new Thread(() -> PdfProcessor.processDocument(task, outputFile)).start();To flatten a specific FormType, use PdfProcessorTask#changeFormsOfType.
Flattening a signature field preserves only the signature’s appearance, not the digital signature itself. The following example excludes signature fields from flattening:
// Flatten all forms except for signature types.val task = PdfProcessorTask.fromDocument(document) .changeAnnotationsOfType(AnnotationType.WIDGET, PdfProcessorTask.AnnotationProcessingMode.FLATTEN) .changeFormsOfType(FormType.SIGNATURE, PdfProcessorTask.AnnotationProcessingMode.KEEP)val outputFile = File(context.filesDir, "flattened.pdf")
lifecycleScope.launch(Dispatchers.IO) { PdfProcessor.processDocument(task, outputFile)}// Flatten all forms except for signature types.PdfProcessorTask task = PdfProcessorTask.fromDocument(document) .changeAnnotationsOfType(AnnotationType.WIDGET, PdfProcessorTask.AnnotationProcessingMode.FLATTEN) .changeFormsOfType(FormType.SIGNATURE, PdfProcessorTask.AnnotationProcessingMode.KEEP);File outputFile = new File(context.getFilesDir(), "flattened.pdf");
new Thread(() -> PdfProcessor.processDocument(task, outputFile)).start();