Java insert attachment to PDF document

Inserting an attachment in a document can serve the purpose of matching with the source document and supplement the document in a more convenient way. The following describes how to insert attachments into PDF documents through Java programming. The document inserted here can be a common document type, such as Word, Excel, Ppt, Txt, or other file types. There are two ways to insert a document. One is to directly load the document content as an attachment and add it to the PDF document. The other is to add a comment to the PDF document and add the document to the comment. In the two methods, you can select the corresponding attachment adding method according to the document needs.

Use tools:

About jar file addition:

Step 1: create a new folder in the Java program to be named Lib. And copy the 2 jar files in the following path to the new folder.

Step 2: after copying the files, add them to the reference class library: select the two jar files, right-click and select "Build Path" – "Add to Build Path". Complete the reference.

 

Java code (for reference)

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 AttachFiles {

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

        //instantiation PdfDocument Class objects
        PdfDocument doc = new PdfDocument();

        //Load the PDF File
        doc.loadFromFile("test.pdf");

        //Load attachment document( Excel)And add to as an attachment PDF
        PdfAttachment attachment = new PdfAttachment("Sample.xlsx");
        doc.getAttachments().add(attachment);

        //stay PDF Draw the label at the specified position of the page
        String label = "TestReport.docx";
        PdfTrueTypeFont font = new PdfTrueTypeFont(new Font("Arial", Font.BOLD, 14));
        double x = 40;
        double y = doc.getPages().get(0).getActualSize().getHeight() -800;
        doc.getPages().get(0).getCanvas().drawString(label, font, PdfBrushes.getOrange(), x, y);

        //Add attachments as comments to PDF
        String filePath = "Test document.docx";
        byte[] data = toByteArray(filePath);
        Dimension2D size = font.measureString(label);
        Rectangle2D bound = new Rectangle2D.Float((float) (x + size.getWidth() + 3), (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 test report document.docx");
        doc.getPages().get(0).getAnnotationsWidget().add(annotation);

        //Save document
        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;
    }
}

Attachment adding effect (as shown below):

(end of this paper)

Keywords: Java Excel Programming

Added by Bladescope on Tue, 03 Dec 2019 04:30:11 +0200