附件是附加在pdf文档中用于展示关联信息的文件。pdf中的附件有两种存在方式,一种是普通的文件附件,一种是注释。本文将展示如何使用spire.pdf for java添加这两种附件到pdf文档。
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("c:\\users\\administrator\\desktop\\sample.pdf");
//添加附件到pdf
pdfattachment attachment = new pdfattachment("c:\\users\\administrator\\desktop\\使用说明书.docx");
doc.getattachments().add(attachment);
//绘制标签
string label = "财务报表.xlsx";
pdftruetypefont font = new pdftruetypefont(new font("arial unicode ms",font.plain,12),true);
double x = 35;
double y = doc.getpages().get(0).getactualsize().getheight() - 200;
doc.getpages().get(0).getcanvas().drawstring(label, font, pdfbrushes.getorange(), x, y);
//添加注释附件到pdf
string filepath = "c:\\users\\administrator\\desktop\\财务报表.xlsx";
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("点击打开财务报表.xlsx");
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;
}
}