Positioning different text snippets on a page

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

1st November 2015
admin-marketing

Switch code for this example

ColumnTextPhrase.java
  1. /*
  2.  * This example was written by Bruno Lowagie in answer to the following question:
  3.  * http://stackoverflow.com/questions/27989754/itext-failure-with-adding-elements-with-5-5-4
  4.  */
  5. package sandbox.objects;
  6.  
  7. import com.itextpdf.text.DocumentException;
  8. import com.itextpdf.text.Font;
  9. import com.itextpdf.text.Paragraph;
  10. import com.itextpdf.text.Phrase;
  11. import com.itextpdf.text.pdf.BaseFont;
  12. import com.itextpdf.text.pdf.ColumnText;
  13. import com.itextpdf.text.pdf.PdfContentByte;
  14. import com.itextpdf.text.pdf.PdfReader;
  15. import com.itextpdf.text.pdf.PdfStamper;
  16.  
  17. import java.io.File;
  18. import java.io.FileOutputStream;
  19. import java.io.IOException;
  20. import sandbox.WrapToTest;
  21.  
  22. @WrapToTest
  23. public class ColumnTextPhrase {
  24.  
  25.     public static final String SRC = "resources/pdfs/hello.pdf";
  26.     public static final String DEST = "results/objects/column_text_phrase.pdf";
  27.    
  28.     public static void main(String[] args) throws IOException, DocumentException {
  29.         File file = new File(DEST);
  30.         file.getParentFile().mkdirs();
  31.         new ColumnTextPhrase().manipulatePdf(SRC, DEST);
  32.     }
  33.  
  34.     public void manipulatePdf(String src, String dest) throws IOException, DocumentException {
  35.         PdfReader reader = new PdfReader(src);
  36.         PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(dest));
  37.         PdfContentByte cb = stamper.getOverContent(1);
  38.         ColumnText ct = new ColumnText(cb);
  39.         ct.setSimpleColumn(120f, 48f, 200f, 600f);
  40.         Font f = new Font();
  41.         Paragraph pz = new Paragraph(new Phrase(20, "Hello World!", f));
  42.         ct.addElement(pz);
  43.         ct.go();
  44.         BaseFont bf = BaseFont.createFont(BaseFont.HELVETICA_BOLD, "Cp1252", BaseFont.EMBEDDED);
  45.         f = new Font(bf, 13);
  46.         ct = new ColumnText(cb);
  47.         ct.setSimpleColumn(120f, 48f, 200f, 700f);
  48.         pz = new Paragraph ("Hello World!", f);
  49.         ct.addElement(pz);
  50.         ct.go();
  51.         stamper.close();
  52.         reader.close();
  53.     }
  54. }
FitTextInRectangle.java
  1. /**
  2.  * Example written by Bruno Lowagie in answer to:
  3.  * http://stackoverflow.com/questions/20909450/correct-text-position-center-in-rectangle-itext
  4.  *
  5.  * Doing some font math to vertically fit a piece of text inside a rectangle.
  6.  */
  7. package sandbox.objects;
  8.  
  9. import com.itextpdf.text.BaseColor;
  10. import com.itextpdf.text.Document;
  11. import com.itextpdf.text.DocumentException;
  12. import com.itextpdf.text.Element;
  13. import com.itextpdf.text.Font;
  14. import com.itextpdf.text.Phrase;
  15. import com.itextpdf.text.Rectangle;
  16. import com.itextpdf.text.pdf.BaseFont;
  17. import com.itextpdf.text.pdf.ColumnText;
  18. import com.itextpdf.text.pdf.PdfContentByte;
  19. import com.itextpdf.text.pdf.PdfWriter;
  20.  
  21. import java.io.File;
  22. import java.io.FileOutputStream;
  23. import java.io.IOException;
  24.  
  25. import sandbox.WrapToTest;
  26.  
  27. @WrapToTest
  28. public class FitTextInRectangle {
  29.  
  30.     public static final String DEST = "results/objects/chunk_in_rectangle.pdf";
  31.    
  32.     public static void main(String[] args) throws IOException, DocumentException {
  33.         File file = new File(DEST);
  34.         file.getParentFile().mkdirs();
  35.         new FitTextInRectangle().createPdf(DEST);
  36.     }
  37.    
  38.     public void createPdf(String dest) throws IOException, DocumentException {
  39.         Document document = new Document();
  40.         PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(dest));
  41.         document.open();
  42.        
  43.         // the direct content
  44.         PdfContentByte cb = writer.getDirectContent();
  45.         // the rectangle and the text we want to fit in the rectangle
  46.         Rectangle rect = new Rectangle(100, 150, 220, 200);
  47.         String text = "test";
  48.         // try to get max font size that fit in rectangle
  49.         BaseFont bf = BaseFont.createFont();
  50.         int textHeightInGlyphSpace = bf.getAscent(text) - bf.getDescent(text);
  51.         float fontSize = 1000f * rect.getHeight() / textHeightInGlyphSpace;
  52.         Phrase phrase = new Phrase("test", new Font(bf, fontSize));
  53.         ColumnText.showTextAligned(cb, Element.ALIGN_CENTER, phrase,
  54.                 // center horizontally
  55.                 (rect.getLeft() + rect.getRight()) / 2,
  56.                 // shift baseline based on descent
  57.                 rect.getBottom() - bf.getDescentPoint(text, fontSize),
  58.                 0);
  59.  
  60.         // draw the rect
  61.         cb.saveState();
  62.         cb.setColorStroke(BaseColor.BLUE);
  63.         cb.rectangle(rect.getLeft(), rect.getBottom(), rect.getWidth(), rect.getHeight());
  64.         cb.stroke();
  65.         cb.restoreState();
  66.        
  67.         document.close();
  68.     }
  69. }
DrawRectangleAroundText.java
  1. /*
  2.  * This example was written by Bruno Lowagie in answer to the following question:
  3.  * http://stackoverflow.com/questions/29037981/how-to-draw-a-rectangle-around-multiline-text
  4.  */
  5. package sandbox.objects;
  6.  
  7. import com.itextpdf.text.DocumentException;
  8. import com.itextpdf.text.Paragraph;
  9. import com.itextpdf.text.pdf.ColumnText;
  10. import com.itextpdf.text.pdf.PdfContentByte;
  11. import com.itextpdf.text.pdf.PdfReader;
  12. import com.itextpdf.text.pdf.PdfStamper;
  13.  
  14. import java.io.File;
  15. import java.io.FileOutputStream;
  16. import java.io.IOException;
  17. import sandbox.WrapToTest;
  18.  
  19. @WrapToTest
  20. public class DrawRectangleAroundText {
  21.  
  22.     public static final String SRC = "resources/pdfs/hello.pdf";
  23.     public static final String DEST = "results/objects/column_text_rectangle.pdf";
  24.    
  25.     public static void main(String[] args) throws IOException, DocumentException {
  26.         File file = new File(DEST);
  27.         file.getParentFile().mkdirs();
  28.         new DrawRectangleAroundText().manipulatePdf(SRC, DEST);
  29.     }
  30.  
  31.     public void manipulatePdf(String src, String dest) throws IOException, DocumentException {
  32.         PdfReader reader = new PdfReader(src);
  33.         PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(dest));
  34.         PdfContentByte cb = stamper.getOverContent(1);
  35.         // full column
  36.         ColumnText ct = new ColumnText(cb);
  37.         ct.setSimpleColumn(120f, 500f, 250f, 780f);
  38.         Paragraph p = new Paragraph("This is a long paragraph that doesn't"
  39.                 + "fit the width we defined for the simple column of the"
  40.                 + "ColumnText object, so it will be distributed over several"
  41.                 + "lines (and we don't know in advance how many).");
  42.         ct.addElement(p);
  43.         ct.go();
  44.         cb.rectangle(120, 500, 130, 280);
  45.         cb.stroke();
  46.         // used column
  47.         ct = new ColumnText(cb);
  48.         ct.setSimpleColumn(300f, 500f, 430f, 780f);
  49.         ct.addElement(p);
  50.         ct.go();
  51.         float endPos = ct.getYLine() - 5;
  52.         cb.rectangle(300, endPos, 130, 780 - endPos);
  53.         cb.stroke();
  54.         stamper.close();
  55.         reader.close();
  56.     }
  57. }
CenterVertically.java
  1. /*
  2.  * This example was written by Bruno Lowagie in answer to the following question:
  3.  * http://stackoverflow.com/questions/26752663/adding-maps-at-itext-java
  4.  */
  5. package sandbox.objects;
  6.  
  7. import com.itextpdf.text.Document;
  8. import com.itextpdf.text.DocumentException;
  9. import com.itextpdf.text.Paragraph;
  10. import com.itextpdf.text.Rectangle;
  11. import com.itextpdf.text.pdf.ColumnText;
  12. import com.itextpdf.text.pdf.PdfContentByte;
  13. import com.itextpdf.text.pdf.PdfPCell;
  14. import com.itextpdf.text.pdf.PdfPTable;
  15. import com.itextpdf.text.pdf.PdfWriter;
  16.  
  17. import java.io.File;
  18. import java.io.FileOutputStream;
  19. import java.io.IOException;
  20. import sandbox.WrapToTest;
  21.  
  22. @WrapToTest
  23. public class CenterVertically {
  24.  
  25.     public static final String DEST = "results/objects/center_vertically.pdf";
  26.    
  27.     private int status = ColumnText.START_COLUMN;
  28.     private float y_position = 0;
  29.    
  30.     public static void main(String[] args) throws IOException, DocumentException {
  31.         File file = new File(DEST);
  32.         file.getParentFile().mkdirs();
  33.         new CenterVertically().createPdf(DEST);
  34.     }
  35.  
  36.     public void createPdf(String dest) throws IOException, DocumentException {
  37.         // step 1
  38.         Document document = new Document();
  39.         // step 2
  40.         PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(dest));
  41.         // step 3
  42.         document.open();
  43.         // step 4
  44.         PdfContentByte pagecanvas = writer.getDirectContent();
  45.         PdfPTable table;
  46.         PdfPCell cell = new PdfPCell();
  47.         for (int i = 1; i
CenterColumnVertically.java
  1. package sandbox.objects;
  2.  
  3. import com.itextpdf.text.BaseColor;
  4. import com.itextpdf.text.Document;
  5. import com.itextpdf.text.DocumentException;
  6. import com.itextpdf.text.Paragraph;
  7. import com.itextpdf.text.Rectangle;
  8. import com.itextpdf.text.pdf.ColumnText;
  9. import com.itextpdf.text.pdf.PdfContentByte;
  10. import com.itextpdf.text.pdf.PdfWriter;
  11.  
  12. import java.io.File;
  13. import java.io.FileOutputStream;
  14. import java.io.IOException;
  15.  
  16. import sandbox.WrapToTest;
  17.  
  18. @WrapToTest
  19. public class CenterColumnVertically {
  20.  
  21.     public static final String DEST = "results/objects/center_column_vertically.pdf";
  22.    
  23.     public static void main(String[] args) throws IOException, DocumentException {
  24.         File file = new File(DEST);
  25.         file.getParentFile().mkdirs();
  26.         new CenterColumnVertically().createPdf(DEST);
  27.     }
  28.  
  29.     public void createPdf(String dest) throws IOException, DocumentException {
  30.         // step 1
  31.         Document document = new Document();
  32.         // step 2
  33.         PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(dest));
  34.         // step 3
  35.         document.open();
  36.         // step 4
  37.         // show the area for the column as a rectangle with red borders
  38.         float llx = 50;  float lly = 650;
  39.         float urx = 400; float ury = 800;
  40.         Rectangle rect = new Rectangle(llx, lly, urx, ury);
  41.         rect.setBorder(Rectangle.BOX);
  42.         rect.setBorderWidth(0.5f);
  43.         rect.setBorderColor(BaseColor.RED);
  44.         PdfContentByte cb = writer.getDirectContent();
  45.         cb.rectangle(rect);
  46.         // this is the paragraph we want to center vertically:
  47.         Paragraph p = new Paragraph("This text is centered vertically. It is rendered in the middle of the red rectangle.");
  48.         p.setLeading(12f);
  49.         // We add the column in simulation mode:
  50.         float y = drawColumnText(cb, rect, p, true);
  51.         // We calculate a new rectangle and add the column for real
  52.         rect = new Rectangle(llx, lly, urx, ury - ((y - lly) / 2));
  53.         drawColumnText(cb, rect, p, false);
  54.         // step 5
  55.         document.close();
  56.     }
  57.  
  58.     /**
  59.      * Draws a Paragraph inside a given column and returns the Y value at the end of the text.
  60.      * @param  canvas    the canvas to which we'll add the Paragraph
  61.      * @param  rect      the dimensions of the column
  62.      * @param  p         the Paragraph we want to add
  63.      * @param  simulate  do we add the paragraph for real?
  64.      * @return the Y coordinate of the end of the text
  65.      * @throws com.itextpdf.text.DocumentException
  66.      */
  67.     public float drawColumnText(PdfContentByte canvas, Rectangle rect, Paragraph p, boolean simulate) throws DocumentException {
  68.         ColumnText ct = new ColumnText(canvas);
  69.         ct.setSimpleColumn(rect);
  70.         ct.addElement(p);
  71.         ct.go(simulate);
  72.         return ct.getYLine();
  73.     }
  74. }
ThreeParts.java
  1. /**
  2.  * Example written by Bruno Lowagie in answer to:
  3.  * http://stackoverflow.com/questions/28502315/divide-page-in-2-parts-so-we-can-fill-each-with-different-source
  4.  */
  5. package sandbox.events;
  6.  
  7. import com.itextpdf.text.BaseColor;
  8. import com.itextpdf.text.Document;
  9. import com.itextpdf.text.DocumentException;
  10. import com.itextpdf.text.Phrase;
  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.PdfPageEventHelper;
  15. import com.itextpdf.text.pdf.PdfWriter;
  16.  
  17. import java.io.BufferedReader;
  18. import java.io.File;
  19. import java.io.FileInputStream;
  20. import java.io.FileOutputStream;
  21. import java.io.IOException;
  22. import java.io.InputStreamReader;
  23.  
  24. import sandbox.WrapToTest;
  25.  
  26. @WrapToTest
  27. public class ThreeParts {
  28.     public static final String DEST = "results/events/three_parts.pdf";
  29.    
  30.     public static final String[] LANGUAGES = { "la", "en", "fr" };
  31.     public static final Rectangle[] RECTANGLES = {
  32.         new Rectangle(36, 581, 559, 806),
  33.         new Rectangle(36, 308.5f, 559, 533.5f),
  34.         new Rectangle(36, 36, 559, 261) };
  35.    
  36.     public static void main(String[] args) throws IOException, DocumentException {
  37.         File file = new File(DEST);
  38.         file.getParentFile().mkdirs();
  39.         new ThreeParts().createPdf(DEST);
  40.     }
  41.    
  42.     public class RedBorder extends PdfPageEventHelper {
  43.         protected Rectangle[] rectangles;
  44.        
  45.         public RedBorder() {
  46.             rectangles = new Rectangle[3];
  47.             for (int i = 0; i < 3; i++) {
  48.                 rectangles[i] = new Rectangle(RECTANGLES[i]);
  49.                 rectangles[i].setBorder(Rectangle.BOX);
  50.                 rectangles[i].setBorderWidth(1);
  51.                 rectangles[i].setBorderColor(BaseColor.RED);
  52.             }
  53.         }
  54.        
  55.         @Override
  56.         public void onEndPage(PdfWriter writer, Document document) {
  57.             PdfContentByte canvas = writer.getDirectContent();
  58.             for (Rectangle rectangle : rectangles) {
  59.                 canvas.rectangle(rectangle);
  60.             }
  61.         }
  62.     }
  63.    
  64.     public void createPdf(String filename) throws IOException, DocumentException {
  65.         // step 1
  66.         Document document = new Document();
  67.         // step 2
  68.         PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(filename));
  69.         RedBorder event = new RedBorder();
  70.         writer.setPageEvent(event);
  71.         // step 3
  72.         document.open();
  73.         // step 4
  74.         PdfContentByte cb = writer.getDirectContent();
  75.         ColumnText[] columns = new ColumnText[3];
  76.         for (int section = 1; section
AddRotatedTemplate.java
  1. /**
  2.  * Example written by Bruno Lowagie in answer to the following question:
  3.  * http://stackoverflow.com/questions/25808367/rotate-multiline-text-with-columntext-itextsharp
  4.  */
  5. package sandbox.stamper;
  6.  
  7. import com.itextpdf.text.DocumentException;
  8. import com.itextpdf.text.Paragraph;
  9. import com.itextpdf.text.Rectangle;
  10. import com.itextpdf.text.pdf.ColumnText;
  11. import com.itextpdf.text.pdf.PdfContentByte;
  12. import com.itextpdf.text.pdf.PdfReader;
  13. import com.itextpdf.text.pdf.PdfStamper;
  14. import com.itextpdf.text.pdf.PdfTemplate;
  15.  
  16. import java.io.File;
  17. import java.io.FileOutputStream;
  18. import java.io.IOException;
  19. import sandbox.WrapToTest;
  20.  
  21. @WrapToTest
  22. public class AddRotatedTemplate {
  23.  
  24.     public static final String SRC = "resources/pdfs/hello.pdf";
  25.     public static final String DEST = "results/stamper/hello_template.pdf";
  26.     public static void main(String[] args) throws IOException, DocumentException {
  27.         File file = new File(DEST);
  28.         file.getParentFile().mkdirs();
  29.         new AddRotatedTemplate().manipulatePdf(SRC, DEST);
  30.     }
  31.  
  32.     public void manipulatePdf(String src, String dest) throws IOException, DocumentException {
  33.         PdfReader reader = new PdfReader(src);
  34.         PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(dest));
  35.         PdfContentByte cb = stamper.getOverContent(1);
  36.         PdfTemplate xobject = cb.createTemplate(80, 120);
  37.         ColumnText column = new ColumnText(xobject);
  38.         column.setSimpleColumn(new Rectangle(80, 120));
  39.         column.addElement(new Paragraph("Some long text that needs to be distributed over several lines."));
  40.         column.go();
  41.         cb.addTemplate(xobject, 36, 600);
  42.         double angle = Math.PI / 4;
  43.         cb.addTemplate(xobject,
  44.                 (float)Math.cos(angle), -(float)Math.sin(angle),
  45.                 (float)Math.cos(angle), (float)Math.sin(angle),
  46.                 150, 600);
  47.         stamper.close();
  48.         reader.close();
  49.     }
  50.  
  51. }
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