Positioning different text snippets on a page

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

31st May 2016
iText PDF

Switch code for this example

CenterColumnVertically.java
  1. /*
  2.  
  3.     This file is part of the iText (R) project.
  4.     Copyright (c) 1998-2016 iText Group NV
  5.  
  6. */
  7.  
  8. package com.itextpdf.samples.sandbox.objects;
  9.  
  10. import com.itextpdf.kernel.color.Color;
  11. import com.itextpdf.kernel.geom.Rectangle;
  12. import com.itextpdf.kernel.pdf.PdfDocument;
  13. import com.itextpdf.kernel.pdf.PdfWriter;
  14. import com.itextpdf.kernel.pdf.canvas.PdfCanvas;
  15. import com.itextpdf.layout.Canvas;
  16. import com.itextpdf.layout.element.Paragraph;
  17. import com.itextpdf.samples.GenericTest;
  18. import com.itextpdf.test.annotations.type.SampleTest;
  19.  
  20. import org.junit.experimental.categories.Category;
  21.  
  22. import java.io.File;
  23. import java.io.IOException;
  24.  
  25. @Category(SampleTest.class)
  26. public class CenterColumnVertically extends GenericTest {
  27.     public static final String DEST = "./target/test/resources/sandbox/objects/center_column_vertically.pdf";
  28.  
  29.     public static void main(String[] args) throws Exception {
  30.         File file = new File(DEST);
  31.         file.getParentFile().mkdirs();
  32.         new CenterColumnVertically().manipulatePdf(DEST);
  33.     }
  34.  
  35.     public void manipulatePdf(String dest) throws IOException {
  36.         PdfDocument pdfDoc = new PdfDocument(new PdfWriter(dest));
  37.         float llx = 50;
  38.         float lly = 650;
  39.         float urx = 400;
  40.         float ury = 800;
  41.         Rectangle rect = new Rectangle(llx, lly, urx - llx, ury - lly);
  42.         PdfCanvas canvas = new PdfCanvas(pdfDoc.addNewPage());
  43.         canvas
  44.                 .setStrokeColor(Color.RED)
  45.                 .setLineWidth(0.5f)
  46.                 .rectangle(rect)
  47.                 .stroke();
  48.         Paragraph p = new Paragraph("This text is centered vertically. " +
  49.                 "It is rendered in the middle of the red rectangle.");
  50.         new Canvas(canvas, pdfDoc, rect)
  51.                 .add(p.setFixedPosition(llx, (ury + lly) / 2, urx - llx));
  52.         pdfDoc.close();
  53.     }
  54. }
CenterVertically.java
  1. /*
  2.  
  3.     This file is part of the iText (R) project.
  4.     Copyright (c) 1998-2016 iText Group NV
  5.  
  6. */
  7.  
  8. /**
  9.  * This example was written by Bruno Lowagie in answer to the following question:
  10.  * http://stackoverflow.com/questions/27834540/generating-pdf-structure-on-dynamic-inputs
  11.  */
  12. package com.itextpdf.samples.sandbox.objects;
  13.  
  14. import com.itextpdf.kernel.geom.Rectangle;
  15. import com.itextpdf.kernel.pdf.PdfDocument;
  16. import com.itextpdf.kernel.pdf.PdfWriter;
  17. import com.itextpdf.layout.Document;
  18. import com.itextpdf.layout.element.AreaBreak;
  19. import com.itextpdf.layout.element.Cell;
  20. import com.itextpdf.layout.element.Table;
  21. import com.itextpdf.layout.layout.LayoutArea;
  22. import com.itextpdf.layout.layout.LayoutContext;
  23. import com.itextpdf.layout.layout.LayoutResult;
  24. import com.itextpdf.layout.renderer.IRenderer;
  25. import com.itextpdf.layout.renderer.TableRenderer;
  26. import com.itextpdf.samples.GenericTest;
  27. import com.itextpdf.test.annotations.type.SampleTest;
  28.  
  29. import org.junit.experimental.categories.Category;
  30.  
  31. import java.io.File;
  32. import java.io.IOException;
  33.  
  34. @Category(SampleTest.class)
  35. public class CenterVertically extends GenericTest {
  36.     public static final String DEST = "./target/test/resources/sandbox/objects/center_vertically.pdf";
  37.  
  38.     public static void main(String[] args) throws Exception {
  39.         File file = new File(DEST);
  40.         file.getParentFile().mkdirs();
  41.         new CenterVertically().manipulatePdf(DEST);
  42.     }
  43.  
  44.     public Rectangle addTable(Document doc, Table table) {
  45.         Rectangle pageDimension = new Rectangle(36, 36, 523, 770);
  46.         Rectangle rect;
  47.         IRenderer tableRenderer = table.createRendererSubTree().setParent(doc.getRenderer());
  48.         LayoutResult tableLayoutResult = tableRenderer.layout(new LayoutContext(new LayoutArea(0, pageDimension)));
  49.         if (LayoutResult.PARTIAL == tableLayoutResult.getStatus()) {
  50.             rect = pageDimension;
  51.         } else {
  52.             rect = new Rectangle(36, ((tableLayoutResult.getOccupiedArea().getBBox().getBottom() + 36) / 2),
  53.                     523, tableLayoutResult.getOccupiedArea().getBBox().getHeight());
  54.         }
  55.         return rect;
  56.     }
  57.  
  58.     @Override
  59.     protected void manipulatePdf(String dest) throws IOException {
  60.         PdfDocument pdfDoc = new PdfDocument(new PdfWriter(dest));
  61.         Document doc = new Document(pdfDoc);
  62.  
  63.         Table table;
  64.         Cell cell = new Cell();
  65.         for (int i = 1; i
ColumnTextPhrase.java
  1. /*
  2.  
  3.     This file is part of the iText (R) project.
  4.     Copyright (c) 1998-2016 iText Group NV
  5.  
  6. */
  7.  
  8. /**
  9.  * This example was written by Bruno Lowagie in answer to the following question:
  10.  * http://stackoverflow.com/questions/27989754/itext-failure-with-adding-elements-with-5-5-4
  11.  */
  12. package com.itextpdf.samples.sandbox.objects;
  13.  
  14. import com.itextpdf.io.font.FontConstants;
  15. import com.itextpdf.io.font.PdfEncodings;
  16. import com.itextpdf.kernel.font.PdfFont;
  17. import com.itextpdf.kernel.font.PdfFontFactory;
  18. import com.itextpdf.kernel.geom.Rectangle;
  19. import com.itextpdf.kernel.pdf.PdfDocument;
  20. import com.itextpdf.kernel.pdf.PdfReader;
  21. import com.itextpdf.kernel.pdf.PdfWriter;
  22. import com.itextpdf.kernel.pdf.canvas.PdfCanvas;
  23. import com.itextpdf.layout.Canvas;
  24. import com.itextpdf.layout.element.Paragraph;
  25. import com.itextpdf.samples.GenericTest;
  26. import com.itextpdf.test.annotations.type.SampleTest;
  27.  
  28. import org.junit.experimental.categories.Category;
  29.  
  30. import java.io.File;
  31. import java.io.IOException;
  32.  
  33. @Category(SampleTest.class)
  34. public class ColumnTextPhrase extends GenericTest {
  35.     public static final String DEST = "./target/test/resources/sandbox/objects/column_text_phrase.pdf";
  36.     public static final String SRC = "./src/test/resources/pdfs/hello.pdf";
  37.  
  38.     public static void main(String[] args) throws Exception {
  39.         File file = new File(DEST);
  40.         file.getParentFile().mkdirs();
  41.         new ColumnTextPhrase().manipulatePdf(DEST);
  42.     }
  43.  
  44.     public void manipulatePdf(String dest) throws IOException {
  45.         PdfDocument pdfDoc = new PdfDocument(new PdfReader(SRC), new PdfWriter(dest));
  46.  
  47.         PdfFont f = PdfFontFactory.createFont(FontConstants.HELVETICA);
  48.         Paragraph pz = new Paragraph("Hello World!").setFont(f).setFixedLeading(20);
  49.         new Canvas(new PdfCanvas(pdfDoc.getFirstPage()), pdfDoc, new Rectangle(120, 48, 80, 480))
  50.                 .add(pz);
  51.         f = PdfFontFactory.createFont(FontConstants.HELVETICA_BOLD, PdfEncodings.CP1252, true);
  52.         pz = new Paragraph("Hello World!").setFont(f).setFontSize(13);
  53.         new Canvas(new PdfCanvas(pdfDoc.getFirstPage()), pdfDoc, new Rectangle(120, 48, 80, 580))
  54.                 .add(pz);
  55.  
  56.         pdfDoc.close();
  57.     }
  58. }
DrawRectangleAroundText.java
  1. /*
  2.  
  3.     This file is part of the iText (R) project.
  4.     Copyright (c) 1998-2016 iText Group NV
  5.  
  6. */
  7.  
  8. /**
  9.  * This example was written by Bruno Lowagie in answer to the following question:
  10.  * http://stackoverflow.com/questions/29037981/how-to-draw-a-rectangle-around-multiline-text
  11.  */
  12. package com.itextpdf.samples.sandbox.objects;
  13.  
  14. import com.itextpdf.kernel.geom.Rectangle;
  15. import com.itextpdf.kernel.pdf.PdfDocument;
  16. import com.itextpdf.kernel.pdf.PdfReader;
  17. import com.itextpdf.kernel.pdf.PdfWriter;
  18. import com.itextpdf.kernel.pdf.canvas.PdfCanvas;
  19. import com.itextpdf.layout.Canvas;
  20. import com.itextpdf.layout.Document;
  21. import com.itextpdf.layout.element.Paragraph;
  22. import com.itextpdf.layout.layout.LayoutArea;
  23. import com.itextpdf.layout.layout.LayoutContext;
  24. import com.itextpdf.layout.renderer.ParagraphRenderer;
  25. import com.itextpdf.samples.GenericTest;
  26. import com.itextpdf.test.annotations.type.SampleTest;
  27.  
  28. import org.junit.experimental.categories.Category;
  29.  
  30. import java.io.File;
  31. import java.io.IOException;
  32.  
  33. @Category(SampleTest.class)
  34. public class DrawRectangleAroundText extends GenericTest {
  35.     public static final String DEST = "./target/test/resources/sandbox/objects/draw_rectangle_around_text.pdf";
  36.     public static final String SRC = "./src/test/resources/pdfs/hello.pdf";
  37.  
  38.     public static void main(String[] args) throws IOException {
  39.         File file = new File(DEST);
  40.         file.getParentFile().mkdirs();
  41.         new DrawRectangleAroundText().manipulatePdf(DEST);
  42.     }
  43.  
  44.     public void manipulatePdf(String dest) throws IOException {
  45.         PdfDocument pdfDoc = new PdfDocument(new PdfReader(SRC), new PdfWriter(DEST));
  46.         Document doc = new Document(pdfDoc);
  47.  
  48.         PdfCanvas canvas = new PdfCanvas(pdfDoc.getFirstPage());
  49.         Paragraph p = new Paragraph("This is a long paragraph that doesn't"
  50.                 + "fit the width we defined for the simple column of the"
  51.                 + "ColumnText object, so it will be distributed over several"
  52.                 + "lines (and we don't know in advance how many).");
  53.  
  54.         new Canvas(canvas, pdfDoc, new Rectangle(120, 500, 130, 280))
  55.                 .add(p);
  56.         canvas.rectangle(120, 500, 130, 280);
  57.         canvas.stroke();
  58.  
  59.         // In the lines below the comment we try to reproduce the itext5 method to achieve the result
  60.         // However it's much more simple to use the next line
  61.         // p.setBorder(new SolidBorder(1));
  62.         // Or you can implement your own ParagraphRenderer and change the behaviour of drawBorder(DrawContext)
  63.         // or draw(DrawContext)
  64.         ParagraphRenderer renderer = (ParagraphRenderer) p.createRendererSubTree().setParent(doc.getRenderer());
  65.         float height = renderer.layout(new LayoutContext(new LayoutArea(0, new Rectangle(300, 500, 130, 280)))).getOccupiedArea().getBBox().getHeight();
  66.  
  67.         new Canvas(canvas, pdfDoc, new Rectangle(300, 500, 130, 280))
  68.                 .add(p);
  69.         canvas.rectangle(300, 500 + 280 - height, 130, height);
  70.         canvas.stroke();
  71.  
  72.         doc.close();
  73.     }
  74. }
ThreeParts.java
  1. /*
  2.  
  3.     This file is part of the iText (R) project.
  4.     Copyright (c) 1998-2016 iText Group NV
  5.  
  6. */
  7.  
  8. /**
  9.  * Example written by Bruno Lowagie in answer to:
  10.  * http://stackoverflow.com/questions/28502315/divide-page-in-2-parts-so-we-can-fill-each-with-different-source
  11.  */
  12. package com.itextpdf.samples.sandbox.events;
  13.  
  14. import com.itextpdf.kernel.geom.Rectangle;
  15. import com.itextpdf.kernel.pdf.PdfDocument;
  16. import com.itextpdf.kernel.pdf.PdfWriter;
  17. import com.itextpdf.kernel.pdf.canvas.PdfCanvas;
  18. import com.itextpdf.layout.Document;
  19. import com.itextpdf.layout.element.Paragraph;
  20. import com.itextpdf.layout.layout.LayoutArea;
  21. import com.itextpdf.layout.layout.LayoutContext;
  22. import com.itextpdf.layout.layout.LayoutResult;
  23. import com.itextpdf.layout.renderer.DocumentRenderer;
  24. import com.itextpdf.layout.renderer.DrawContext;
  25. import com.itextpdf.layout.renderer.ParagraphRenderer;
  26. import com.itextpdf.samples.GenericTest;
  27. import com.itextpdf.test.annotations.type.SampleTest;
  28.  
  29. import org.junit.experimental.categories.Category;
  30.  
  31. import java.io.*;
  32.  
  33. @Category(SampleTest.class)
  34. public class ThreeParts extends GenericTest {
  35.     public static final String DEST = "./target/test/resources/sandbox/events/three_parts.pdf";
  36.  
  37.     public static void main(String[] args) throws Exception {
  38.         File file = new File(DEST);
  39.         file.getParentFile().mkdirs();
  40.         new ThreeParts().manipulatePdf(DEST);
  41.     }
  42.  
  43.     public Paragraph createParagraph(String path) throws IOException {
  44.         Paragraph p = new Paragraph();
  45.         BufferedReader in = new BufferedReader(
  46.                 new InputStreamReader(new FileInputStream(path), "UTF-8"));
  47.         StringBuffer buffer = new StringBuffer();
  48.         String line = in.readLine();
  49.         while (null != line) {
  50.             buffer.append(line);
  51.             line = in.readLine();
  52.         }
  53.         in.close();
  54.         p.add(buffer.toString());
  55.         return p;
  56.     }
  57.  
  58.     public void addSection(PdfDocument pdfDoc, Paragraph paragraph, int pageNumber, int sectionNumber) throws IOException {
  59.         LayoutResult layoutResult;
  60.         ParagraphRenderer renderer = (ParagraphRenderer) paragraph.createRendererSubTree();
  61.         renderer.setParent(new DocumentRenderer(new Document(pdfDoc)));
  62.         while (((layoutResult = renderer.layout(new LayoutContext(new LayoutArea(pageNumber, new Rectangle(36, 36 + ((842 - 72) / 3) * sectionNumber, 523, (842 - 72) / 3)))))).getStatus() != LayoutResult.FULL) {
  63.             if (pdfDoc.getNumberOfPages() < pageNumber) {
  64.                 pdfDoc.addNewPage();
  65.             }
  66.             layoutResult.getSplitRenderer().draw(new DrawContext(pdfDoc, new PdfCanvas(pdfDoc.getPage(pageNumber++)), false));
  67.             renderer = (ParagraphRenderer) layoutResult.getOverflowRenderer();
  68.         }
  69.         if (pdfDoc.getNumberOfPages() < pageNumber) {
  70.             pdfDoc.addNewPage();
  71.         }
  72.         renderer.draw(new DrawContext(pdfDoc, new PdfCanvas(pdfDoc.getPage(pageNumber)), false));
  73.     }
  74.  
  75.  
  76.     @Override
  77.     protected void manipulatePdf(String dest) throws Exception {
  78.         PdfDocument pdfDoc = new PdfDocument(new PdfWriter(dest));
  79.         int firstPageNumber = 1;
  80.  
  81.         for (int section = 0; section < 3; section++) {
  82.             // latin
  83.             addSection(pdfDoc, createParagraph(String.format("./src/test/resources/txt/liber1_%s_la.txt", section + 1)), firstPageNumber, 2);
  84.             // english
  85.             addSection(pdfDoc, createParagraph(String.format("./src/test/resources/txt/liber1_%s_en.txt", section + 1)), firstPageNumber, 1);
  86.             // french
  87.             addSection(pdfDoc, createParagraph(String.format("./src/test/resources/txt/liber1_%s_fr.txt", section + 1)), firstPageNumber, 0);
  88.  
  89.             firstPageNumber = pdfDoc.getNumberOfPages() + 1;
  90.         }
  91.  
  92.         pdfDoc.close();
  93.     }
  94. }
AddRotatedTemplate.java
  1. /*
  2.  
  3.     This file is part of the iText (R) project.
  4.     Copyright (c) 1998-2016 iText Group NV
  5.  
  6. */
  7.  
  8. /**
  9.  * Example written by Bruno Lowagie in answer to the following question:
  10.  * http://stackoverflow.com/questions/25808367/rotate-multiline-text-with-columntext-itextsharp
  11.  */
  12. package com.itextpdf.samples.sandbox.stamper;
  13.  
  14. import com.itextpdf.kernel.geom.Rectangle;
  15. import com.itextpdf.kernel.pdf.PdfDocument;
  16. import com.itextpdf.kernel.pdf.PdfReader;
  17. import com.itextpdf.kernel.pdf.PdfWriter;
  18. import com.itextpdf.kernel.pdf.canvas.PdfCanvas;
  19. import com.itextpdf.kernel.pdf.xobject.PdfFormXObject;
  20. import com.itextpdf.layout.Canvas;
  21. import com.itextpdf.layout.element.Paragraph;
  22. import com.itextpdf.samples.GenericTest;
  23. import com.itextpdf.test.annotations.type.SampleTest;
  24.  
  25. import java.io.File;
  26.  
  27. import org.junit.experimental.categories.Category;
  28.  
  29. @Category(SampleTest.class)
  30. public class AddRotatedTemplate extends GenericTest {
  31.     public static final String SRC = "./src/test/resources/pdfs/hello.pdf";
  32.     public static final String DEST = "./target/test/resources/sandbox/stamper/add_rotated_template.pdf";
  33.  
  34.     public static void main(String[] args) throws Exception {
  35.         File file = new File(DEST);
  36.         file.getParentFile().mkdirs();
  37.         new AddRotatedTemplate().manipulatePdf(DEST);
  38.     }
  39.  
  40.     @Override
  41.     protected void manipulatePdf(String dest) throws Exception {
  42.         PdfDocument pdfDoc = new PdfDocument(new PdfReader(SRC), new PdfWriter(DEST));
  43.  
  44.         PdfFormXObject formXObject = new PdfFormXObject(new Rectangle(80, 120));
  45.         new Canvas(formXObject, pdfDoc).add(new Paragraph("Some long text that needs to be distributed over several lines."));
  46.  
  47.         PdfCanvas canvas = new PdfCanvas(pdfDoc.getFirstPage());
  48.         canvas.addXObject(formXObject, 36, 600);
  49.         double angle = Math.PI / 4;
  50.         canvas.addXObject(formXObject,
  51.                 (float) Math.cos(angle), -(float) Math.sin(angle),
  52.                 (float) Math.cos(angle), (float) Math.sin(angle),
  53.                 150, 600);
  54.  
  55.         pdfDoc.close();
  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