Java 插入附件到PDF文檔


在文檔中插入附件,可以起到與源文檔配套使用的目的,以一種更簡便的方式對文檔起到補充說明的作用。下面將介紹通過Java編程插入附件到PDF文檔中的方法。這里插入的文檔可以是常見的文檔類型,如Word、Excel、Ppt、Txt或者其他文件類型。插入方法,分兩種情況,一種是直接加載文檔內容作為附件添加到PDF文檔,另一種是通過給PDF文檔添加注釋並添加文檔到注釋的形式。兩種方式中可根據文檔需要,選擇相應的附件添加方法。

使用工具:

關於jar文件添加:

步驟1在Java程序中新建一個文件夾可命名為Lib。並將以下路徑中的2個jar文件復制到新建的文件夾下。

步驟2復制文件后,添加到引用類庫:選中這兩個jar文件,點擊鼠標右鍵,選擇“Build Path” – “Add to Build Path”。完成引用。

 

Java代碼(供參考)

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 {

        //實例化PdfDocument類的對象
        PdfDocument doc = new PdfDocument();

        //加載需要添加附件的PDF文檔
        doc.loadFromFile("test.pdf");

        //加載附件文檔(Excel)並作為附件添加到PDF
        PdfAttachment attachment = new PdfAttachment("Sample.xlsx");
        doc.getAttachments().add(attachment);

        //在PDF頁面指定位置繪制標簽
        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);

        //以注釋的形式添加附件到PDF
        String filePath = "測試文檔.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("點擊打開測試報告文檔.docx");
        doc.getPages().get(0).getAnnotationsWidget().add(annotation);

        //保存文檔
        doc.saveToFile("Attachments.pdf");
    }

    //讀取文件到byte數組
    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;
    }
}

附件添加效果(如下圖):

 (本文完)


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM