You can either write a document to file, memory or the output stream (e.g. stdout).
Document document = new Document();
// write to file
PdfWriter.getInstance(document, new FileOutputStream("Output.pdf");
//write to memory
ByteArrayOutputStream buffer = new ByteArrayOutputStream();
PdfWriter.getInstance(document, buffer);
//write to System.out
PdfWriter.getInstance(document, System.out);
Note that when using the file output or System.out the document is outputted directly but with the ByteArrayOutputStream it is buffered for use at a later date. To retrieve it, the reader needs to be passed the ByteArrayOutputStream cast as a ByteArray.
//read from memory
PdfReader reader = new PdfReader(buffer.toByteArray());
This is extremely useful when you need to do multiple passes on a pdf document. For example, you may want to read in multiple pdfs and write page numbers for the new combined document on each page. The pdfs can be read in, merged together and stored in memory then the whole new document can be manipulated and annotated. This saves writing an intermediary file to disk.
In-depth iText information can be found in Bruno Lowagie's excellent book iText In Action http://www.manning.com/lowagie2/
No comments:
Post a Comment