Tiling images

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

1st November 2015
admin-marketing

Switch code for this example

TiledImage.java
  1. /**
  2.  * This code sample was written by Bruno Lowagie in answer to this question:
  3.  * http://stackoverflow.com/questions/26859473/how-to-show-an-image-with-large-dimensions-across-multiple-pages-in-itextpdf
  4.  */
  5. package sandbox.images;
  6.  
  7. import com.itextpdf.text.Document;
  8. import com.itextpdf.text.DocumentException;
  9. import com.itextpdf.text.Image;
  10. import com.itextpdf.text.Rectangle;
  11. import com.itextpdf.text.pdf.PdfContentByte;
  12. import com.itextpdf.text.pdf.PdfWriter;
  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 TiledImage {
  21.     public static final String IMAGE = "resources/images/bruno_ingeborg.jpg";
  22.     public static final String DEST = "results/images/tiled_image.pdf";
  23.    
  24.     public static void main(String[] args) throws IOException, DocumentException {
  25.         File file = new File(DEST);
  26.         file.getParentFile().mkdirs();
  27.         new TiledImage().createPdf(DEST);
  28.     }
  29.     public void createPdf(String dest) throws IOException, DocumentException {
  30.         Image image = Image.getInstance(IMAGE);
  31.         float width = image.getScaledWidth();
  32.         float height = image.getScaledHeight();
  33.         Rectangle page = new Rectangle(width / 2, height / 2);
  34.         Document document = new Document(page);
  35.         PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(dest));
  36.         document.open();
  37.         PdfContentByte canvas = writer.getDirectContentUnder();
  38.         canvas.addImage(image, width, 0, 0, height, 0, -height / 2);
  39.         document.newPage();
  40.         canvas.addImage(image, width, 0, 0, height, 0, 0);
  41.         document.newPage();
  42.         canvas.addImage(image, width, 0, 0, height, -width / 2, - height / 2);
  43.         document.newPage();
  44.         canvas.addImage(image, width, 0, 0, height, -width / 2, 0);
  45.         document.close();
  46.     }
  47. }
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