Java iText结合标记文件

时间:2011-08-30 20:01:19

标签: java pdf itext

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

  1. 用户选中一系列复选框,指示他或她希望打印哪些PDF。
  2. 根据用户输入,抓取1-x PDF模板文件。每个页面都有一系列需要填写的AcroField。
  3. 一个这样的页面需要在PDF上绘制一些自定义图形,即访问PdfContentByte对象并操纵它以插入图像和矩形。
  4. 如果可能的话,我想避免将临时PDF写入磁盘。以前的程序员做到了这一点,处理这个问题一直很麻烦。我更喜欢抓住模板文件,在内存中操作它并直接将它提供给浏览器。
  5. 我似乎拥有所有的碎片,但我不能完全把它们放在一起。第4点是我真正绊倒的原因。

    TIA。

1 个答案:

答案 0 :(得分:2)

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

//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