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.)