java中如何实现向已有的PDF文件插入附件?

 我来答
爱靠真00
2020-01-09
知道答主
回答量:56
采纳率:0%
帮助的人:2.9万
展开全部

可以用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;


}


}

效果:

草原上之狼
高粉答主

2020-01-04 · 醉心答题,欢迎关注
知道大有可为答主
回答量:2.9万
采纳率:93%
帮助的人:3802万
展开全部
java打开PDF需要借助其他的jar包的,如果我没记错的话,然后查看相应的API接口。应该是以流的形式进行读取,之前写过一点是往里面写数据的,生成html文然后写入PDF文件 工具有:
ItextPdf、FlyingAndItext、pd4ml 这些是将html文转换为PDF文件的,读取的话直接用bufferread读取试试(我没写过!)
本回答被网友采纳
已赞过 已踩过<
你对这个回答的评价是?
评论 收起
推荐律师服务: 若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询

为你推荐:

下载百度知道APP,抢鲜体验
使用百度知道APP,立即抢鲜体验。你的手机镜头里或许有别人想知道的答案。
扫描二维码下载
×

类别

我们会通过消息、邮箱等方式尽快将举报结果通知您。

说明

0/200

提交
取消

辅 助

模 式