Write on previous page

This is a code example of iText PDF, discover more.

25th November 2015
admin-marketing

Switch code for this example

WriteOnFirstPage.java
  1. /*
  2.  * This example was written by Bruno Lowagie in answer to the following question:
  3.  * http://stackoverflow.com/questions/33873180/itext-pdf-add-text-in-absolute-position-on-top-of-the-1st-page
  4.  */
  5. package sandbox.columntext;
  6.  
  7. import com.itextpdf.text.Document;
  8. import com.itextpdf.text.DocumentException;
  9. import com.itextpdf.text.Image;
  10. import com.itextpdf.text.Paragraph;
  11. import com.itextpdf.text.Rectangle;
  12. import com.itextpdf.text.pdf.ColumnText;
  13. import com.itextpdf.text.pdf.PdfContentByte;
  14. import com.itextpdf.text.pdf.PdfTemplate;
  15. import com.itextpdf.text.pdf.PdfWriter;
  16. import java.io.File;
  17. import java.io.FileOutputStream;
  18. import java.io.IOException;
  19.  
  20. /**
  21.  * @author iText
  22.  */
  23. public class WriteOnFirstPage {
  24.     public static final String DEST = "results/columntext/write_on_first_page.pdf";
  25.    
  26.    
  27.     public static void main(String[] args) throws IOException, DocumentException {
  28.         File file = new File(DEST);
  29.         file.getParentFile().mkdirs();
  30.         new WriteOnFirstPage().createPdf(DEST);
  31.     }
  32.     public void createPdf(String dest) throws IOException, DocumentException {
  33.         // step 1
  34.         Document document = new Document();
  35.         // step 2
  36.         PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(dest));
  37.         // step 3
  38.         document.open();
  39.         // step 4
  40.         PdfContentByte cb = writer.getDirectContent();
  41.         PdfTemplate message = cb.createTemplate(523, 50);
  42.         Image header = Image.getInstance(message);
  43.         document.add(header);
  44.         for (int i = 0; i < 100; i++) {
  45.             document.add(new Paragraph("test"));
  46.         }
  47.         ColumnText ct = new ColumnText(message);
  48.         ct.setSimpleColumn(new Rectangle(0, 0, 523, 50));
  49.         ct.addElement(
  50.                 new Paragraph(
  51.                         String.format("There are %s pages in this document", writer.getPageNumber())));
  52.         ct.go();
  53.         // step 5
  54.         document.close();
  55.     }
  56.    
  57. }
Contact

Still have questions? 

We're happy to answer your questions. Reach out to us and we'll get back to you shortly.

Contact us
Stay updated

Join 11,000+ subscribers and become an iText PDF expert by staying up to date with our new products, updates, tips, technical solutions and happenings.

Subscribe Now