This article will introduce how to add, extract and remove attachments in a PDF document using Java codes programmatically. Before beginning, we should create a test environment using a free third-party library called FreeSpire.PDF for Java. You can either download the API’s JAR or install it within your maven-based applications using the following configurations.
<repositories>
<repository>
<id>com.e-iceblue</id>
<name>e-iceblue</name>
<url>http://repo.e-iceblue.com/nexus/content/groups/public/</url>
</repository>
</repositories>
<dependencies>
<dependency>
<groupId> e-iceblue </groupId>
<artifactId>spire.pdf.free</artifactId>
<version>3.9.0</version>
</dependency>
</dependencies>
Add Attachments to PDF in Java
Free Spire.PDF for Java supports adding a file attachment or annotation attachment to PDF. In the
process of adding an annotation attachment, it supports drawing a label on PDF, and set the label’s font
size or location. Besides, Flag, icon or text can be also set.
The following code sample shows how to add a file attachment and an annotation attachment.
import com.spire.pdf.PdfDocument;
import com.spire.pdf.annotations.*;
import com.spire.pdf.attachments.PdfAttachment;
import com.spire.pdf.graphics.*;
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 AddAttachment {
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\\Test1\\Desktop\\Sample.pdf");
//add an attachment to pdf
PdfAttachment attachment = new PdfAttachment("C:\\Users\\Test1\\Desktop\\Country list.xlsx");
doc.getAttachments().add(attachment);
//draw a label on pdf
String label = "Report.docx";
PdfTrueTypeFont font = new PdfTrueTypeFont(new Font("Arial", Font.BOLD, 14));
double x = 30;
double y = doc.getPages().get(2).getActualSize().getHeight() - 80;
doc.getPages().get(2).getCanvas().drawString(label, font, PdfBrushes.getOrange(), x, y);
//add an attachment annotation to pdf
String filePath = "C:\\Users\\Test1\\Desktop\\Report.docx";
byte[] data = toByteArray(filePath);
Dimension2D size = font.measureString(label);
Rectangle2D bound = new Rectangle2D.Float((float) (x + size.getWidth() + 2), (float) y, 10, 15);
PdfAttachmentAnnotation annotation = new PdfAttachmentAnnotation(bound, filePath, data);
annotation.setColor(new PdfRGBColor(new Color(128, 13, 119)));
annotation.setFlags(PdfAnnotationFlags.Default);
annotation.setIcon(PdfAttachmentIcon.Graph);
annotation.setText("Click to open Report.docx");
doc.getPages().get(2).getAnnotationsWidget().add(annotation);
//save to file
doc.saveToFile("output/AddAttachments.pdf");
}
//read 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;
}
}Output
Extract Attachments from PDF
We just need to load the sample file, get and loop through the attachment collection to extract each
attachment in PDF.
import com.spire.pdf.PdfDocument;
import com.spire.pdf.attachments.PdfAttachmentCollection;
import java.io.*;
public class ExtractAttachment {
public static void main(String[] args) throws IOException {
//Load the PDF document
PdfDocument pdf = new PdfDocument();
pdf.loadFromFile("C:\\Users\\Test1\\Desktop\\AddAttachments.pdf");
//Get the attachment collection of the PDF document
PdfAttachmentCollection attachments = pdf.getAttachments();
//Loop through the collection and extract each attachment in the PDF document
for (int i = 0; i < attachments.getCount(); i++) {
File file = new File("output/ExtractAttachments/"+attachments.get(i).getFileName());
OutputStream output = new FileOutputStream(file);
BufferedOutputStream bufferedOutput = new BufferedOutputStream(output);
bufferedOutput.write(attachments.get(i).getData());
bufferedOutput.close();
}
}
}Delete Attachments in PDFWe can separately delete a file attachment or an annotation attachment from the following two code
samples.
l Delete a file attachment
Free Spire.PDF for Java supports delete all attachments or a specific attachment in PDF.
import com.spire.pdf.PdfDocument;
import com.spire.pdf.attachments.PdfAttachmentCollection;
public class DeleteAttachment {
public static void main(String[] args) {
//load a PDF document
PdfDocument doc = new PdfDocument();
doc.loadFromFile("C:\\Users\\Test1\\Desktop\\AddAttachments.pdf");
//get the attachments collection, not containing annotation attachments
PdfAttachmentCollection attachments = doc.getAttachments();
//remove all attachments
attachments.clear();
//remove a specific attachment
//attachments.removeAt(0);
//save to file
doc.saveToFile("output/DeleteAttachments.pdf");
doc.close();
}
}l Delete an annotation attachment
We can delete the annotation attachment by determining if it is an instance of PdfAttachmentAnnotationWidget in the following code sample.
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 DeleteAnnotationAttachment {
public static void main(String[] args) {
//load a PDF document
PdfDocument doc = new PdfDocument();
doc.loadFromFile("C:\\Users\\Test1\\Desktop\\AddAttachments.pdf");
//loop through the pages
for (int i = 0; i < doc.getPages().getCount(); i++) {
//get the annotations collection
PdfAnnotationCollection annotationCollection = doc.getPages().get(i).getAnnotationsWidget();
//loop through the annotations
for (Object annotation: annotationCollection) {
//determine if an annotation is an instance of PdfAttachmentAnnotationWidget
if (annotation instanceof PdfAttachmentAnnotationWidget){
//remove the attachment annotation
annotationCollection.remove((PdfAnnotation) annotation);
}
}
}
//save to file
doc.saveToFile("output/DeleteAnnotationAttachments.pdf");
doc.close();
}
}
No comments:
Post a Comment