There are two ways in Spire.PDF to attach files to a PDF document – add attachments to background and add attachments as annotations. This article demonstrates the same.
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 AttachFiles { 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\\Sample.pdf"); //add an attachment to pdf PdfAttachment attachment = new PdfAttachment("C:\\Users\\Administrator\\Desktop\\ReadMe.txt"); 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(0).getActualSize().getHeight() - 100; doc.getPages().get(0).getCanvas().drawString(label, font, PdfBrushes.getOrange(), x, y); //add an attachment annotation to pdf String filePath = "C:\\Users\\Administrator\\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(0, 128, 128))); annotation.setFlags(PdfAnnotationFlags.Default); annotation.setIcon(PdfAttachmentIcon.Graph); annotation.setText("Click to open Report.docx"); doc.getPages().get(0).getAnnotationsWidget().add(annotation); //save to file doc.saveToFile("Attachments.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: