Java iText объединяет штампованные файлы - PullRequest
2 голосов
/ 31 августа 2011

Я работаю с библиотекой iText, чтобы выполнить некоторые манипуляции с PDF в Java, но я пытаюсь сделать что-то, в чем API iText начинает меня поражать.Мне действительно просто нужен быстрый учебник или какой-то псевдокод, но вот что я пытаюсь сделать:

  1. Пользователь выбирает серию флажков, указывающих, какие PDF-файлы он хочет напечатать.
  2. Исходя из введенных пользователем данных, возьмите 1 - x файлов шаблонов PDF.На каждой странице есть ряд полей AcroFields, которые необходимо заполнить.
  3. Одна такая страница требует рисования некоторой пользовательской графики в PDF, то есть доступа к объекту PdfContentByte и манипулирования им для вставки изображений и прямоугольников.
  4. Если это возможно, я бы хотел избежать записи временных PDF-файлов на диск.Предыдущий программист делал это, и с этим было грязно иметь дело.Я бы предпочел захватить файл шаблона, манипулировать им в памяти и подать его прямо в браузер.

Кажется, у меня есть все части, но я не могу собрать все это вместе,Точка № 4 - это то, что действительно сбило меня с толку.

TIA.

1 Ответ

2 голосов
/ 31 августа 2011

Итак, вот ответ, который я, наконец, смог придумать:

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

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...