在现有pdf的itext中附加数据 [英] Appending a data in itext in existing pdf
问题描述
我正在使用 itext pdf 库。我想在现有pdf的末尾添加一个内容。
I am working with itext pdf library. I want to add a content at the end of the existing pdf.
比如说现有的pdf(比如Original.pdf)说4页,所以我想要添加另一页,即第5页,内容 Hello World我添加内容并将其保存在相同的pdf中,即 Original.pdf
Say for example the existing pdf(say Original.pdf) is having say 4 pages, so I want to add another page i.e. page no 5 with content Hello World I am added content and save it in the same pdf i.e. Original.pdf
关闭后,我的Original.pdf将包含 5 页面,即 4页(已有默认内容)+ 1页,内容 Hello World我添加了内容
So after closing my Original.pdf will contain 5 pages i.e 4 pages(with default content they already have) + 1 page with content Hello World I am added content
我正在使用此代码但显示异常
I am using this code but showing an exception
String in="Original.pdf";
String out="Original.pdf";
PdfReader reader = new PdfReader(in);
PdfStamper stamper = new PdfStamper(reader,new FileOutputStream(out));
int totalPages=reader.getNumberOfPages();
stamper.insertPage(totalPages+1, PageSize.A4);
stamper.addAnnotation(
PdfAnnotation.createText(
stamper.getWriter(),
new Rectangle(30f, 750f, 80f, 800f),
"inserted page", "This page is the title page.",
true,
null)
,
reader.getNumberOfPages()
);
stamper.close();
java.io.EOFException
提前致谢。
推荐答案
我认为问题来自于您使用 FileOutputStream
和同一文件上的 FileInputStream
。
I think the problem comes from the fact that you are using a FileOutputStream
and a FileInputStream
on the same file.
我会建议在ByteArrayOutputStream上保存pdf,关闭压模,然后在文件中保存 ByteArrayOutputStream
。
I would recommand to save on ByteArrayOutputStream the pdf, close the stamper, and then save the ByteArrayOutputStream
in your file.
I使用了 IOUtils.write(byte []数据,OutputStream输出)方法在 FileOutputStream
中保存 ByteArrayOutputStream
。
I've used IOUtils.write(byte[] data, OutputStream output) method to save the ByteArrayOutputStream
in the FileOutputStream
.
我已经测试了这个并且它有效:
I've tested this and it works:
String in = "Original.pdf";
String out = "Original.pdf";
PdfReader reader = new PdfReader(in);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
PdfStamper stamper = new PdfStamper(reader, baos );
int totalPages = reader.getNumberOfPages();
stamper.insertPage(totalPages + 1, PageSize.A4);
stamper.addAnnotation(PdfAnnotation.createText(stamper.getWriter(), new Rectangle(30f, 750f, 80f, 800f), "inserted page", "This page is the title page.", true, null),
reader.getNumberOfPages());
stamper.close();
FileOutputStream fileOutputStream = new FileOutputStream(out);
IOUtils.write(baos.toByteArray(), fileOutputStream);
这篇关于在现有pdf的itext中附加数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!