How to Add or Remove Attachments in PDF via Java Code?
We can add attachments to PDF files or PowerPoint presentations to make them more comprehensive and detailed. Attaching related documents to PDF can facilitate centralized management and transmission of documents. So how to add or remove attachments in PDF? Don't worry, we can easily do this programmatically. For your reference, I have attached the Java code for the specific steps I have organized.
Document Level Attachment: A file attached to a PDF at the document level won't appear on a page, but can only be viewed in the "Attachments" panel of a PDF reader.
Annotation Attachment: A file will be added to a specific position of a page. Annotation attachments are shown as a paper clip icon on the page; reviewers can double-click the icon to open the file.
- Add an Attachment to PDF in Java
- Add an Annotation Attachment to PDF in Java
- Remove Attachments from PDF in Java
- Remove Annotation Attachments from PDF in Java
Programming Environment
Method 1:
Introduced manually. Download Free Spire.PDF
for Java locally, unzip it, and find the Spire.PDF.jar file in the lib
folder. Open the following interface in IDEA, and import the jar file in the
local path into the Java program:
If you use Maven, you can easily import the JAR
file in your application by adding the following code to your project’s pom.xml file.
<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 an Attachment to PDF in Java
- Create a PdfDocument object.
- Load a PDF document using PdfDocument.loadFromFile() method.
- Create a PdfAttachment object based on an external file.
- Add the attachment to PDF using PdfDocument.getAttachments().add() method.
- Save the document to another PDF file using PdfDocument.saveToFile() method.
Full Code
Java
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("UK.pdf");
//Create a PdfAttachment object based on an external file
PdfAttachment attachment = new PdfAttachment("Data.xlsx");
//Add the attachment to PDF
doc.getAttachments().add(attachment);
//Save to file
doc.saveToFile("Attachment.pdf");
}
}
Effective Shot
Add an Annotation Attachment to PDF in Java
- Create a PdfDocument object.
- Load a PDF document using PdfDocument.loadFromFile() method.
- Get a specific page to add annotation using PdfDocument.getPages().get() method.
- Create a PdfAttachmentAnnotation object based on an external file.
- Add the annotation attachment to the page using PdfPageBase.getAnnotationsWidget().add() method.
- Save the document to another PDF file using PdfDocument.saveToFile() method.
Full Code
Java
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("UK.pdf");
//Get a specific page PdfPageBase page = doc.getPages().get(0);
//Draw a label on PDF String label = "Here is the development history of UK:"; PdfTrueTypeFont font = new PdfTrueTypeFont(new Font("Arial", Font.PLAIN, 13)); double x = 35; double y = doc.getPages().get(0).getActualSize().getHeight() - 300; page.getCanvas().drawString(label, font, PdfBrushes.getRed(), x, y); //Attach a file as an annotation String filePath = "Development History.pptx"; 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 here to open the file"); page.getAnnotationsWidget().add(annotation);
//Save to file doc.saveToFile("Attachments.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; }
Effective Shot
Remove Attachments from PDF in Java
- Create a PdfDocument object.
- Load a PDF document using PdfDocument.loadFromFile() method.
- Get the attachment collection from the document using PdfDocument.getAttachments() method.
- Remove a specific attachment using PdfAttachmentCollection.removeAt() method. To remove all attachments at once, use PdfAttachmentCollection.clear() method.
- Save the document to another PDF file using PdfDocument.saveToFile() method.
Full Code
Java
import com.spire.pdf.PdfDocument;
import com.spire.pdf.attachments.PdfAttachmentCollection;
public class RemoveAttachments {
public static void main(String[] args) {
//Create a PdfDocument object
PdfDocument doc = new PdfDocument();
//Load a PDF file
doc.loadFromFile("C:\\Users\\Administrator\\Desktop\\Attachments.pdf");
//Get attachment 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();
}
}
Remove Annotation Attachments from PDF in Java
- Create a PdfDocument object.
- Load a PDF document using PdfDocument.loadFromFile() method.
- Loop through the pages in the document, and get the annotation collection from a specific page using PdfPageBase.getAnnotationsWidget() method.
- Determine if an annotation is an instance of PdfAttachmentAnnotationWidget. If yes, remove the annotation attachment using PdfAnnotationCollection.remove() method.
- Save the document to another PDF file using PdfDocument.saveToFile() method.
Full Code
Java
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) {
//Create a PdfDocument object
PdfDocument doc = new PdfDocument();
//Load a PDF file
doc.loadFromFile("C:\\Users\\Administrator\\Desktop\\Attachments.pdf");
//Loop through the pages
for (int i = 0; i < doc.getPages().getCount(); i++) {
//Get the annotation 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();
}
}
Conclusion:
In this article, you have learned how to add
or remove attachments in PDF in Java. Not only that, we also have other
functions, such as, Extract
Attachments from PDF in Java, Java:
Convert PDF to Word and so
on. Apart from that, if you'd like to learn more, you can visit this
link to explore more about for Spire.PDF for Java.
Comments
Post a Comment