天天看點

java 添加附件_Java 插入附件到PDF文檔

importcom.spire.pdf.PdfDocument;import com.spire.pdf.annotations.*;importcom.spire.pdf.attachments.PdfAttachment;import com.spire.pdf.graphics.*;import java.awt.*;importjava.awt.geom.Dimension2D;importjava.awt.geom.Rectangle2D;importjava.io.File;importjava.io.FileInputStream;importjava.io.IOException;public classAttachFiles {public static void main(String[] args) throwsIOException {//執行個體化PdfDocument類的對象

PdfDocument doc = newPdfDocument();//加載需要添加附件的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= newPdfAttachmentAnnotation(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) throwsIOException {

File file= newFile(filePath);long fileSize =file.length();if (fileSize >Integer.MAX_VALUE) {

System.out.println("file too big...");return null;

}

FileInputStream fi= newFileInputStream(file);byte[] buffer = new byte[(int) fileSize];int offset = 0;int numRead = 0;while (offset = 0) {

offset+=numRead;

}if (offset !=buffer.length) {throw new IOException("Could not completely read file "

+file.getName());

}

fi.close();returnbuffer;

}

}