简体   繁体   English

使用 Java 中的 itext 将 pdf 保存到字节数组

[英]Save pdf to bytearray using itext in Java

I am using itext to read a large pdf file and save selected pages.我正在使用 itext 读取大型 pdf 文件并保存选定的页面。

PdfReader reader = null;
reader = new PdfReader("customPath/largePdf.pdf");
int pages = reader.getNumberOfPages();
List<Integer> pagesList = new ArrayList<Integer>();
pagesList.add(1);
pagesList.add(2);
reader.selectPages(pagesList);
String path;
PdfStamper stamper = null;
path = String.format("customerPath/split.pdf");
stamper = new PdfStamper(reader, new FileOutputStream(path));

All good until now, i can open the split.pdf.到目前为止一切顺利,我可以打开 split.pdf。

Now, Instead of saving to a file, i want to save it to a bytearray (so that i can save it as a blob later)现在,我不想将其保存到文件中,而是将其保存到字节数组中(以便以后可以将其保存为 blob)

Tried this:试过这个:

PdfReader reader = null;
reader = new PdfReader("customPath/largePdf.pdf");
int pages = reader.getNumberOfPages();
List<Integer> pagesList = new ArrayList<Integer>();
pagesList.add(1);
pagesList.add(2);
reader.selectPages(pagesList);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
PdfStamper stamper2 = new PdfStamper(reader, baos);
byte[] byteARy = baos.toByteArray();

Just to make sure it works, i tried writing this bytearray to a file:只是为了确保它有效,我尝试将此字节数组写入文件:

OutputStream out = new FileOutputStream("customPath/fromByteArray.pdf");
out.write(byteARy);
out.close();

fromByteArray.pdf does not open and the size is zero, any idea what might be wrong? fromByteArray.pdf 未打开且大小为零,知道可能出了什么问题吗?

You retrieve the byte array (using baos.toByteArray() ) immediately after creating the PdfStamper .创建PdfStamper后立即检索字节数组(使用baos.toByteArray() )。

PdfStamper stamper2 = new PdfStamper(reader, baos);
byte[] byteARy = baos.toByteArray();

At that time there is (next to) nothing in the output.那时 output 中(旁边)什么都没有。 You must instead wait until after closing your PdfStamper to retrieve the output.您必须等到关闭PdfStamper后才能检索 output。

PdfStamper stamper2 = new PdfStamper(reader, baos);
...
stamper2.close();
byte[] byteARy = baos.toByteArray();

Now the byte array should contain the complete, stamped PDF.现在字节数组应该包含完整的标记 PDF。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM