Graphics2D examples

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

7th November 2015
admin-marketing

Switch code for this example

LargeTemplate.java
  1. /**
  2.  * Example written by Bruno Lowagie in answer to:
  3.  * http://stackoverflow.com/questions/24807638/writing-a-large-graphics-2d-document-to-multiple-pdf
  4.  */
  5. package sandbox.graphics2d;
  6.  
  7. import com.itextpdf.awt.PdfGraphics2D;
  8. import com.itextpdf.text.Document;
  9. import com.itextpdf.text.DocumentException;
  10. import com.itextpdf.text.Rectangle;
  11. import com.itextpdf.text.pdf.PdfContentByte;
  12. import com.itextpdf.text.pdf.PdfTemplate;
  13. import com.itextpdf.text.pdf.PdfWriter;
  14.  
  15. import java.awt.Graphics2D;
  16. import java.io.File;
  17. import java.io.FileOutputStream;
  18. import java.io.IOException;
  19.  
  20. /**
  21.  *
  22.  * @author iText
  23.  */
  24. public class LargeTemplate {
  25.    
  26.     public static final String DEST = "results/graphics2d/large_template.pdf";    
  27.    
  28.     public static void main(String[] args) throws IOException, DocumentException {
  29.         File file = new File(DEST);
  30.         file.getParentFile().mkdirs();
  31.         new LargeTemplate().createPdf(DEST);
  32.     }
  33.     public void createPdf(String dest) throws IOException, DocumentException {
  34.         float width = 602;
  35.         float height = 15872;
  36.         float maxHeight = 5000;
  37.         Document document = new Document(new Rectangle(width, maxHeight));
  38.         PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(DEST));
  39.         document.open();
  40.         PdfContentByte canvas = writer.getDirectContent();
  41.         PdfTemplate template = canvas.createTemplate(width, height);
  42.         Graphics2D g2d = new PdfGraphics2D(template, width, height);
  43.         for (int x = 10; x < width; x += 100) {
  44.             for (int y = 10; y < height; y += 100) {
  45.                 g2d.drawString(String.format("(%s,%s)", x, y), x, y);
  46.             }
  47.         }
  48.         g2d.dispose();
  49.         int pages = ((int)height / (int)maxHeight) + 1;
  50.         for (int p = 0; p < pages; ) {
  51.             p++;
  52.             canvas.addTemplate(template, 0, (p * maxHeight) - height);
  53.             document.newPage();
  54.         }
  55.         document.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