简体   繁体   中英

How to write a text in the pdf file using itext at a given position using java

Im using PdfTemplate.createTemplate with following code,

 Document document = new Document();
 PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream("C:\\Report.pdf"));     
 document.open();
 document.add(new Paragraph("A Hello World PDF new TEXT document."));
 PdfContentByte contentByte = writer.getDirectContent();    
 PdfTemplate template = contentByte.createTemplate(50,50);
 template.beginText();
 BaseFont bf=BaseFont.createFont(BaseFont.HELVETICA,BaseFont.CP1252,BaseFont.NOT_EMBEDDED);
 template.setFontAndSize(bf,10);
 template.setTextMatrix(100,100);    
 template.showText("Text at the position 100,100 (relative to the template!)");
 template.endText();
 contentByte.addTemplate(template, 10, 100);
 document.close();

But the text is not visible in the pdf

When you do this:

PdfTemplate template = contentByte.createTemplate(50,50);

You create a canvas that measures 50 user units by 50 user units. All the content that you add to this canvas will be clipped to that size.

When you do this:

template.setTextMatrix(100,100);

You deliberately move outside the visible area of the small square with lower-left corner 0,0 and upper-right corner 50,50. Whatever you add in this area will be clipped.

You are correct when you say: the text is not visible in the pdf. If the text were visible, you would have found a bug.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM