gpt4 book ai didi

Java iText 合并冲压文件

转载 作者:行者123 更新时间:2023-11-30 09:46:13 25 4
gpt4 key购买 nike

我正在使用 iText 库在 Java 中做一些 PDF 操作,但我正在尝试做一些 iText API 开始让我不知所措的事情。我真的只需要一个快速教程或一些伪代码,但这是我想要完成的:

  1. 用户选择一系列复选框,指示他或她希望打印哪些 PDF。
  2. 根据用户输入,获取 1 - x PDF 模板文件。每个页面都有一系列需要填写的 AcroFields。
  3. 其中一个页面需要在 PDF 上绘制一些自定义图形,即访问 PdfContentByte 对象并对其进行操作以插入图像和矩形。
  4. 如果可能,我想避免将临时 PDF 写入磁盘。以前的程序员就是这么干的,处理那个一直很乱。我更愿意获取模板文件,在内存中对其进行操作,然后直接将其提供给浏览器。

我似乎拥有所有的部分,但我不能完全把它们放在一起。第 4 点是真正让我感到困惑的地方。

TIA。

最佳答案

所以,这是我最终能够想出的答案:

//Open an input stream to the PDF template
InputStream is = getInputStreamToEachFile();


//Declare a document object, as well as a PdfCopy for
//copying in each PdfFile we open in memory and edit.
Document doc = new Document();
PdfCopy copy = new PdfCopy(doc, outputStreamToBrowser);


//Be sure to open the document or it will throw an exception!
doc.open();


//Since the PdfStamper class wants to output everything to an
//output stream you can declare a ByteArrayOutputStream object
//and direct it there, since we need to tack on more PDFs and
//can't just output to the response's output stream directly.
ByteArrayOutputStream byteStream = new ByteArrayOutputStream();
PdfStamper stamper = new PdfStamper(new PdfReader(is), byteStream);


//Pseduocode - set form fields - just check out
//the documentation for AcroFields in the API
//this part is easy.
...


//if form has custom graphics declare a PdfContentByte array
//the 1 argument in the getUnderContent refers to the page number

PdfContentByte cb = stamper.getUnderContent(1);

//pseduocode - do custom graphics. This can be a lot of different things,
//so check the documentation
...


//Wrap things up - set the dyanamic form fields to read only
//and call the stamper's close function to close the streams
stamper.setFormFlatterning(true);
stamper.close()


//Finally, declare a new PdfReader, reading the stamper's byte array stream
//which was declared in memory.
PdfReader outReader = new PdfReader(byteStream.toByteArray());

//Use this function call to add each page that you need. Repeat this process
//for as many PDFs as are being stitched together.
copy.addPage(copy.getImportedPage(outReader,1));

//Finally, tell the browser you are done generating the file, and output it.
//If there are a lot of pages being generated this way, I guess you could use the flush
//function instead, and then call close when they are all done.
copy.close();

感谢我最终自己找到的这个教程:

http://itextpdf.com/examples/iia.php?id=127

关于Java iText 合并冲压文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7249086/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com