iText PDF 系列文章之一:continued, page 4
iText is able to write PDF syntax to any OutputStream, so instead of buffering the complete PDF file in a ByteArrayOutputStream we could have done something like this:
PdfWriter.getInstance(document,
response.getOutputStream());
This will work with most browsers, but unfortunately some specific browsers don't digest dynamically generated PDFs very well. You get a blank page or no PDF at all. You can only work around this problem by telling the browser the content length of the file before sending the PDF.
Manipulating Existing PDF files
Up till now we have been using iText to create documents from scratch. It is also possible to use iText to manipulate existing PDF document. In the next example, we are going to add a watermarks and page numbers to an existing three page document:
PdfReader reader = new PdfReader("Hello.pdf");
PdfStamper stamper = new PdfStamper(reader,
new FileOutputStream("HelloStamped.pdf"));
Image img = Image.getInstance("images/watermark.jpg");
img.setAbsolutePosition(200, 400);
BaseFont bf = BaseFont.createFont(BaseFont.HELVETICA,
BaseFont.WINANSI, BaseFont.NOT_EMBEDDED);
PdfContentByte under, over;
int total = reader.getNumberOfPages() + 1;
for (int i = 1; i < total; i++) {
under = stamper.getUnderContent(i);
under.addImage(img);
over = stamper.getOverContent(i);
over.beginText();
over.setFontAndSize(bf, 18);
over.setTextMatrix(30, 30);
over.showText("page " + i);
over.endText();
over.setRGBColorStroke(0xFF, 0x00, 0x00);
over.setLineWidth(5f);
over.ellipse(250, 450, 350, 550);
over.stroke();
}
stamper.close();
The existing PDF file is loaded into the object PdfReader and passed to the object PdfStamper. An instance of an image (the watermark) is created as well as a font for the page numbers. In a loop that goes over all the pages the canvas under the existing content is grabbed with the method getUnderContent(). A watermark is added to this canvas. Then getOverContent() is used to get the canvas that will cover the existing content. We add some text with the page number at the bottom of the page and we draw a red circle in the middle of the page.
Figure 4. An existing file with bookmarks was stamped
原文地址:http://www.pdfdev.com/page/articles_1_4/

浙公网安备 33010602011771号