星期四, 九月 25, 2008

iText

keywords:

Document is the object to which you’ll add content: the document data and meta-data.
Upon creating the Document object, you can define the page size, the page color, and the margins of the first page of your PDF document.

By default, a user unit corresponds with the typographic unit of measurement known as the point.
1 in = 2.54 cm = 72 points

When a document object is opened,  a lot of initializations take place in iText.
If you use the parameterless Document constructor and you want to change page size and margins with the corresponding setter methods, it’s important to do this before opening the document. Otherwise the default page size and margins will be used for the first page, and your page settings will only be taken into account starting from the second page.
That’s why you should always set the PDF version and add the metadata before opening the document.

When document.open() is invoked, the iText DocWriter starts writing its first bytes to the OutputStream. In the case of PdfWriter, a PDF header is written, and by default it looks like this:

%PDF-1.4
%âãÏÓ


adding content to the PDF document . There are three ways to do this:
    a:The easy way—Using iText’s basic building blocks
                        document.add(new Paragraph("Hello World"));

    b:As a PDF expert—Using iText methods that correspond with PDF operators and operands
                        PdfContentByte cb = writer.getDirectContent();
                        BaseFont bf = BaseFont.createFont(BaseFont.HELVETICA,
                        BaseFont.CP1252, BaseFont.NOT_EMBEDDED);
                        cb.saveState(); // q
                        cb.beginText(); // BT
                        cb.moveText(36, 806); // 36 806 Td
                        cb.moveText(0, -18); // 0 -18 Td
                        cb.setFontAndSize(bf, 12); // /F1 12 Tf
                        cb.showText("Hello World"); // (Hello World)Tj
                        cb.endText(); // ET
                        cb.restoreState(); // Q
    c:As a Java expert—Using Graphics2D methods and the paint method in Swing components
                        PdfContentByte cb = writer.getDirectContent();
                  Graphics2D graphics2D = cb.createGraphics(PageSize.A4.getWidth(),
                                                             PageSize.A4.getHeight());
                  graphics2D.drawString("Hello World", 36, 54);
                  graphics2D.dispose();
      (attention:On UNIX systems, may encounter X11 problems that prompt this error message: Can’t connect to X11 window server using xyz as the value of the DISPLAY variable. You can work around this issue by running the AWT in headless mode by starting the Java Virtual Machine (JVM) with the parameter java.awt.headless=true. Another solution is to run an X server. If you don’t need to display anything, a virtual X11 server will do.)