Add Attachments in PDF in Java

Andrew Wilson
3 min readMar 20, 2023

PDF attachments are external documents that users can access to find more relevant information. PDF attachments can be in different forms such as Word, Excel, PowerPoint, links or any other medium. This article will share how to programmatically add the following two types of attachments in a PDF document using a free library-Free Spire.PDF for Java.

  • Add a Document Level Attachment to PDF in Java
  • Add an Annotation Attachment to PDF in Java

Import Dependency (2 methods)

Method 1: Download the free library and unzip it. Then add the Spire.Pdf.jar file to your project as dependency.

Method 2: Directly add the jar dependency to maven project by adding the following configurations to the pom.xml.

<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.free</artifactId>
<version>5.1.0</version>
</dependency>
</dependencies>

Add a Document Level Attachment to PDF in Java

A document level attachment is a file attached to a PDF at the document level that won’t show on the page. The attached file can only be viewed in the “Attachments” panel of a PDF reader. Below is the complete sample code to achieve the task.

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

public class AttachFilesToPdf {

public static void main(String[] args) {

//Create a PdfDocument object
PdfDocument doc = new PdfDocument();

//Load a sample PDF file
doc.loadFromFile("C:\\Users\\Administrator\\Desktop\\Budget.pdf");

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

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

//Save to file
doc.saveToFile("Attachment.pdf");
}
}

Add an Annotation Attachment to PDF in Java

An annotation attachment is a file that will be added to a specific position of a page. Annotation attachments are shown as a paper clip icon on the page and reviewers can double-click the icon to open the file. Below is the complete sample code to achieve the task.

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;

public class AnnotationAttachment {

public static void main(String[] args) throws IOException {

//Create a PdfDocument object
PdfDocument doc = new PdfDocument();

//Load a sample PDF file
doc.loadFromFile("C:\\Users\\Administrator\\Desktop\\Budget.pdf");

//Get a specific page
PdfPageBase page = doc.getPages().get(0);

//Draw a label on PDF
String label = "A sample report:";
PdfTrueTypeFont font = new PdfTrueTypeFont(new Font("Arial", Font.PLAIN, 13));
double x = 80;
double y = doc.getPages().get(0).getActualSize().getHeight() - 190;
page.getCanvas().drawString(label, font, PdfBrushes.getRed(), x, y);

//Attach a file as an annotation
String filePath = "C:\\Users\\Administrator\\Desktop\\report.xlsx";
byte[] data = toByteArray(filePath);
Dimension2D size = font.measureString(label);
Rectangle2D bound = new Rectangle2D.Float((float) (x + size.getWidth() + 5), (float) y, 10, 15);
PdfAttachmentAnnotation annotation = new PdfAttachmentAnnotation(bound, filePath, data);
annotation.setColor(new PdfRGBColor(new Color(0, 128, 128)));
annotation.setFlags(PdfAnnotationFlags.Default);
annotation.setIcon(PdfAttachmentIcon.Graph);
annotation.setText("Click to open the file");
page.getAnnotationsWidget().add(annotation);

//Save to file
doc.saveToFile("PdfAttachment.pdf");
}
//Convert 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 = 0;
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;
}
}

--

--

Andrew Wilson

Explore C#, Java and Python solutions for processing Word/Excel/PowerPoint/PDF files.