In this article I will show you how you can attach PDF files in Java using our JPedal PDF SDK toolkit, using a few lines of Java code.
JPedal offers other PDF manipulation features, to aid Java developers working with the PDF format.
Introduction
PDF is a powerful format, and one such feature is the ability to embed/attach files within a PDF document. This is useful if you want to bundle resources with a document but do not want to distribute them as a ZIP or RAR file, and is great for PDF/A compliance.
Adding attachments to PDF
If you want to be able to programmatically attach files to a PDF document using Java, you may use our PDF toolkit JPedal.
- First, download the trial JAR
- Second, add JPedal to your project
- Finally, add the following Java code to your app:
final PdfManipulator pdf = new PdfManipulator();
pdf.loadDocument(new File("inputFile.pdf"));
pdf.embedFile(new File("embed.png"), "embedded-image");
pdf.apply();
pdf.writeDocument(new File("outputFile.pdf"));
pdf.closeDocument();
If you want to include a FileAttachment annotation on a page to reference the attached file, you can specify a color and a bounding box like so:
pdf.attachFile(1, new File("embed.png"), "embedded-image",
new float[] {10.0f, 10.0f, 100.0f, 100.0f}, new float[] {0.7f, 0.3f, 0.4f});
Learn more about the PdfManipulator class.
Viewing attachments
If you want to view the files attachments that you have embedded in your PDF document, you may use a PDF viewer such as the JPedal Viewer.
java -jar jpedal.jar –view „inputFile.pdf“
Learn more about the JPedal Viewer.
We’ve been working with PDF files for over two decades and can help you understand the PDF format…