Skip to main content

How to Add and Remove Attachments in PDF Using Java

 In many professional and academic scenarios, PDF documents often need to carry additional files, such as Excel spreadsheets, PowerPoint slides, or supplementary data. Being able to manage attachments within a PDF can improve document organization, facilitate sharing, and make it easier for recipients to access related materials.

In this article, we will explore four practical ways to add and remove attachments in PDF files using Java, covering both direct attachments and annotation-based attachments:

  1. Adding a standard attachment to a PDF

  2. Attaching a file via annotation

  3. Removing standard attachments

  4. Removing annotation-based attachments




Installing the Required Library

To implement these examples, we use Spire.PDF for Java, a library that provides APIs for loading PDF documents, adding attachments, managing annotations, and saving changes. You can download the JAR package or include it via Maven:

<repositories>
    <repository>
        <id>com.e-iceblue</id>
        <name>e-iceblue</name>
        <url>https://repo.e-iceblue.com/nexus/content/groups/public/</url>
    </repository>
</repositories>
<dependencies>
    <dependency>
        <groupId>e-iceblue</groupId>
        <artifactId>spire.pdf</artifactId>
        <version>12.4.4</version>
    </dependency>
</dependencies>

Once added to your project, you can start manipulating attachments in PDFs programmatically.


1. Adding a Standard Attachment

The simplest way to attach a file to a PDF is by using a direct attachment. This approach embeds the file into the PDF and makes it available in the document’s attachment panel. For example, we can attach an Excel file to a report:

import com.spire.pdf.PdfDocument;
import com.spire.pdf.attachments.PdfAttachment;

public class AttachFilesToPdf {

    public static void main(String[] args) {
        // Create a new PDF document object
        PdfDocument doc = new PdfDocument();

        // Load an existing PDF file
        doc.loadFromFile("C:\\Users\\Administrator\\Desktop\\Sample.pdf");

        // Create a PdfAttachment object for an external file
        PdfAttachment attachment = new PdfAttachment("C:\\Users\\Administrator\\Desktop\\Data.xlsx");

        // Add the attachment to the PDF
        doc.getAttachments().add(attachment);

        // Save the updated PDF to a new file
        doc.saveToFile("Attachment.pdf");

        // Close the document
        doc.close();
    }
}

Details: Direct attachments are visible in the PDF’s attachment panel and can be opened by standard PDF viewers. This method is suitable for providing supplementary data or reference files without embedding them visibly on the page.


2. Attaching a File via Annotation

For more interactive scenarios, you can attach a file through a PDF annotation. This allows you to display a visual cue on the page and provide instructions or labels for users. For example, placing the text “Here is the report:” on a page and attaching a PowerPoint file next to it:

import com.spire.pdf.PdfPageBase;
import com.spire.pdf.annotations.*;
import com.spire.pdf.graphics.*;
import com.spire.pdf.PdfDocument;

import java.awt.*;
import java.awt.geom.Dimension2D;
import java.awt.geom.Rectangle2D;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.EnumSet;

public class AnnotationAttachment {

    public static void main(String[] args) throws IOException {
        PdfDocument doc = new PdfDocument();
        doc.loadFromFile("C:\\Users\\Administrator\\Desktop\\Sample.pdf");

        // Get the first page of the PDF
        PdfPageBase page = doc.getPages().get(0);

        // Draw a label on the page
        String label = "Here is the report:";
        PdfTrueTypeFont font = new PdfTrueTypeFont(new Font("Arial", Font.PLAIN, 13));
        double x = 35;
        double y = page.getActualSize().getHeight() - 220;
        page.getCanvas().drawString(label, font, PdfBrushes.getRed(), x, y);

        // Convert external file to byte array
        String filePath = "C:\\Users\\Administrator\\Desktop\\Report.pptx";
        byte[] data = toByteArray(filePath);

        // Determine the annotation bounds based on the label width
        Dimension2D size = font.measureString(label);
        Rectangle2D bound = new Rectangle2D.Float((float) (x + size.getWidth() + 5), (float) y, 10, 15);

        // Create the attachment annotation
        PdfAttachmentAnnotation annotation = new PdfAttachmentAnnotation(bound, filePath, data);
        annotation.setColor(new PdfRGBColor(new Color(0, 128, 128)));
        annotation.setFlags(EnumSet.of(PdfAnnotationFlags.Default));
        annotation.setIcon(PdfAttachmentIcon.Graph);
        annotation.setText("Click here to open the file");

        // Add the annotation to the page
        page.getAnnotationsWidget().add(annotation);

        // Save the updated PDF
        doc.saveToFile("Attachments.pdf");
        doc.close();
    }

    // Utility method to convert a file to byte array
    public static byte[] toByteArray(String filePath) throws IOException {
        File file = new File(filePath);
        long fileSize = file.length();
        if (fileSize > Integer.MAX_VALUE) {
            System.out.println("File too big...");
            return null;
        }
        FileInputStream fi = new FileInputStream(file);
        byte[] buffer = new byte[(int) fileSize];
        int offset = 0;
        int numRead;
        while (offset < buffer.length
                && (numRead = fi.read(buffer, offset, buffer.length - offset)) >= 0) {
            offset += numRead;
        }
        if (offset != buffer.length) {
            throw new IOException("Could not completely read file " + file.getName());
        }
        fi.close();
        return buffer;
    }
}

Details: Annotation attachments allow you to provide visual cues and instructions. Users can click the annotation to open the attached file, which is particularly useful for presentations or supplementary documents.


3. Removing Standard Attachments

Sometimes you may need to remove attachments that are no longer relevant. You can do this by accessing the PDF’s attachment collection:

import com.spire.pdf.PdfDocument;
import com.spire.pdf.attachments.PdfAttachmentCollection;

public class RemoveAttachments {

    public static void main(String[] args) {
        PdfDocument doc = new PdfDocument();
        doc.loadFromFile("C:\\Users\\Administrator\\Desktop\\Attachments.pdf");

        // Get the collection of standard attachments (excluding annotation attachments)
        PdfAttachmentCollection attachments = doc.getAttachments();

        // Remove all attachments
        attachments.clear();

        // Or remove a specific attachment by index
        // attachments.removeAt(0);

        // Save the updated PDF
        doc.saveToFile("output/DeleteAttachments.pdf");
        doc.close();
    }
}

Details: Standard attachment removal affects only the directly embedded files, leaving any annotation-based attachments intact.


4. Removing Annotation-Based Attachments

If attachments were added as annotation attachments, you need to remove them by iterating through the page annotations:

import com.spire.pdf.PdfDocument;
import com.spire.pdf.annotations.PdfAnnotation;
import com.spire.pdf.annotations.PdfAnnotationCollection;
import com.spire.pdf.annotations.PdfAttachmentAnnotationWidget;

public class RemoveAnnotationAttachments {

    public static void main(String[] args) {
        PdfDocument doc = new PdfDocument();
        doc.loadFromFile("C:\\Users\\Administrator\\Desktop\\Attachments.pdf");

        // Loop through each page
        for (int i = 0; i < doc.getPages().getCount(); i++) {
            PdfAnnotationCollection annotationCollection = doc.getPages().get(i).getAnnotationsWidget();

            // Iterate through the annotations and remove attachment annotations
            for (Object annotation : annotationCollection) {
                if (annotation instanceof PdfAttachmentAnnotationWidget) {
                    annotationCollection.remove((PdfAnnotation) annotation);
                }
            }
        }

        // Save the updated PDF
        doc.saveToFile("output/DeleteAnnotationAttachments.pdf");
        doc.close();
    }
}

Details: This method ensures that all annotation-based attachments are removed while leaving standard attachments intact.


Conclusion

Managing attachments in PDF files can be done in multiple ways:

  1. Standard attachments – Embed files directly into the PDF.

  2. Annotation attachments – Provide interactive cues on the page with clickable attachments.

  3. Removing standard attachments – Clear outdated or unnecessary files.

  4. Removing annotation attachments – Remove interactive file annotations while keeping the PDF content intact.

These approaches provide flexibility depending on whether you want the attachment to be directly visible in the attachment panel or embedded as part of the page annotations.

Comments

Popular posts from this blog

3 Ways to Generate Word Documents from Templates in Java

A template is a document with pre-applied formatting like styles, tabs, line spacing and so on. You can quickly generate a batch of documents with the same structure based on the template. In this article, I am going to show you the different ways to generate Word documents from templates programmatically in Java using Free Spire.Doc for Java library. Prerequisite First of all, you need to add needed dependencies for including Free Spire.Doc for Java into your Java project. There are two ways to do that. If you use maven, you need to add the following code to your project’s pom.xml file. <repositories>               <repository>                   <id>com.e-iceblue</id>                   <name>e-iceblue</name>...

Insert and Extract OLE objects in Word in Java

You can use OLE (Object Linking and Embedding) to include content from other programs, such as another Word document, an Excel or PowerPoint document to an existing Word document. This article demonstrates how to insert and extract embedded OLE objects in a Word document in Java by using Free Spire.Doc for Java API.   Add dependencies First of all, you need to add needed dependencies for including Free Spire.Doc for Java into your Java project. There are two ways to do that. If you use maven, you need to add the following code to your project’s pom.xml file.     <repositories>               <repository>                   <id>com.e-iceblue</id>                   <name>e-iceblue</name>    ...

Simple Java Code to Convert Excel to PDF in Java

This article demonstrates a simple solution to convert an Excel file to PDF in Java by using free Excel API – Free Spire.XLS for Java . The following examples illustrate two possibilities to convert Excel to PDF:      Convert the whole Excel file to PDF     Convert a particular Excel Worksheet to PDF Before start with coding, you need to Download Free Spire.XLS for Java package , unzip it and import Spire.Xls.jar file from the lib folder in your project as a denpendency. 1. Convert the whole Excel file to PDF Spire.XLS for Java provides saveToFile method in Workbook class that enables us to easily save a whole Excel file to PDF. import com.spire.xls.FileFormat; import com.spire.xls.Workbook; public class ExcelToPDF {     public static void main(String[] args){         //Create a Workbook         Workbook workbook = new Workbook();   ...