天天看点

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;

}

}