0

I am using iText 5.0 to add static text to few existing PDFs. Following code works for PDF in portrait orientation, but it isn't working for PDF in landscape. I have been struggling to get this working, will appreciate any hint on what i might be missing here.

sample PDF in landscape: http://mirrors.ibiblio.org/CTAN/macros/latex/contrib/mwe/example-image-a4-landscape.pdf

Code block:

private static void  addTextToPDF(int pageNr, PdfReader reader, PdfStamper pdfStamper) {

    for (int i = 1; i <= reader.getNumberOfPages(); i++)
    {
        Rectangle pageSize = reader.getPageSizeWithRotation(i);

        PdfContentByte pdfPageContents = pdfStamper.getUnderContent(i);
        pdfPageContents.beginText();

        BaseFont baseFont = null;
        try {
            baseFont = BaseFont.createFont(BaseFont.HELVETICA_BOLD, BaseFont.CP1252, false);
        } catch (DocumentException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        pdfPageContents.setFontAndSize(baseFont, 40); 
        pdfPageContents.setRGBColorFill(255, 0, 0); 


        pdfPageContents.showTextAligned(PdfContentByte.ALIGN_CENTER, "Put this text on the page!!",
                pageSize.getWidth()/2,
                pageSize.getHeight()/2,
                0.0f);

        pdfPageContents.endText();

        System.out.println("Wriiten at:" + pageSize.getWidth()/2 + " " + pageSize.getHeight()/2);
    }
    pdfStamper.setFormFlattening(true);

}
Joris Schellekens
  • 8,483
  • 2
  • 23
  • 54
user859106
  • 11
  • 1
  • Would you please read the [Watermark tutorial](https://developers.itextpdf.com/question/how-watermark-pdfs-using-text-or-images) on the official web site? I see at least two errors in your code. You don't take into account a possible offset. You don't tell iTexr to take the rotation into account. And why are you adding text the hard way? – Bruno Lowagie Jun 23 '18 at 20:06
  • Thank you Bruno, that link really helped. – user859106 Jun 24 '18 at 05:11

0 Answers0