Remove Attachments from PDF via Java

Delete Attachments from PDF programmatically with Java

How to remove Attachments Using Java Library

Remove Attachments from PDF using the Aspose.PDF for Java. Files with attachments, such as images or other PDF, can increase the size of a document. Removing attachments may help reduce the file size, making it easier to share and store. Also, attachments can contain confidential information that you don’t want to share with others. So, delete attachments from PDF. Removing attachments helps protect your data. Malicious attachments may pose security risks. Removing unknown or untrusted attachments from PDF will help prevent potential security threats. Removing attachments makes the PDF easier to print and view your document. We can conclude, that removing attachments from PDF can make the document more user-friendly, efficient, and compatible. In order to remove Attachments, we’ll use Aspose.PDF for Java API which is a feature-rich, powerful and easy to use conversion API for Java platform. You can download its latest version directly from Maven and install it within your Maven-based project by adding the following configurations to the pom.xml.

Repository

<repository>
    <id>AsposeJavaAPI</id>
    <name>Aspose Java AP</name>
    <url>https://releases.aspose.com/java/repo/</url>
</repository>

Dependency

<dependency>
<groupId>com.aspose</groupId>
<artifactId>aspose-pdf</artifactId>
<version>version of aspose-pdf API</version>
</dependency>

Remove Attachments from PDF


You need Aspose.PDF for Java to try the code in your environment.

  1. Open existing PDF.
  2. Delete all attachments.
  3. Save the result.

This code snippet programmatically removes all attachments from a PDF document and saves the modified PDF as a separate file. It initializes a ‘pdfDocument’ object, which is associated with the PDF file located at the ‘dataDir + DeleteAllAttachments.pdf’ path. After opening the PDF document, the code instructs the software to delete all attachments contained within this PDF file. Attachments in a PDF can include embedded files, such as images or other documents. The code modifies the ‘dataDir’ variable to store the path where the updated PDF file, without any attachments, will be saved. The updated PDF will be saved with the filename ‘DeleteAllAttachments_out.pdf.’

Delete Attachment from PDF document

This sample code shows how to Remove attachment from PDF - Java

// Open a document
Document pdfDocument = new Document(_dataDir+"input.pdf");
// Delete all attachments
pdfDocument.getEmbeddedFiles().delete();
// Save the updated file
pdfDocument.save("output.pdf");