具体实现方法如下:1、导入itext-2。1。5。jar跟itextasian-1。5。2。jar两个包到项目里,2、建立一个pdf文件。
一般情况下,iText使用在有以下一个要求的项目中:1。内容无法提前利用:取决于用户的输入或实时的数据库信息。2。由于内容,页面过多,PDF文档不能手动生成。3。文档需在无人参与,批处理模式下自动创建。4。内容被定制或个性化。
可以用Spire.Pdf for Java类库给PDF文档添加附件,下面的代码是插入Excel和Word附件给你参考:
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
}
}
效果:
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)