Image on rotated page

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

31st May 2016
admin-marketing

Switch code for this example

ImageOnRotatedPage.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:
  10.  * http://stackoverflow.com/questions/33787785/itext-rotate-pdf-document-but-not-image
  11.  */
  12. package com.itextpdf.samples.sandbox.images;
  13.  
  14. import com.itextpdf.io.image.ImageDataFactory;
  15. import com.itextpdf.kernel.geom.PageSize;
  16. import com.itextpdf.kernel.pdf.PdfDocument;
  17. import com.itextpdf.kernel.pdf.PdfWriter;
  18. import com.itextpdf.layout.Document;
  19. import com.itextpdf.layout.element.Image;
  20. import com.itextpdf.samples.GenericTest;
  21. import com.itextpdf.test.annotations.type.SampleTest;
  22.  
  23. import org.junit.experimental.categories.Category;
  24.  
  25. import java.io.File;
  26.  
  27.  
  28. @Category(SampleTest.class)
  29. public class ImageOnRotatedPage extends GenericTest {
  30.     public static final String DEST = "./target/test/resources/sandbox/images/image_on_rotated_page.pdf";
  31.     public static final String IMAGE = "./src/test/resources/img/cardiogram.png";
  32.  
  33.     public static void main(String[] args) throws Exception {
  34.         File file = new File(DEST);
  35.         file.getParentFile().mkdirs();
  36.         new ImageOnRotatedPage().manipulatePdf(DEST);
  37.     }
  38.  
  39.     @Override
  40.     protected void manipulatePdf(String dest) throws Exception {
  41.         PdfDocument pdfDoc = new PdfDocument(new PdfWriter(dest));
  42.         // Note that it is not necessary to create new PageSize object,
  43.         // but for testing reasons (connected to parallelization) we call constructor here
  44.         Document doc = new Document(pdfDoc, new PageSize(PageSize.A4).rotate());
  45.         Image img = new Image(ImageDataFactory.create(IMAGE));
  46.         img.scaleToFit(770, 523);
  47.         float offsetX = (770 - img.getImageScaledWidth()) / 2;
  48.         float offsetY = (523 - img.getImageScaledHeight()) / 2;
  49.         img.setFixedPosition(36 + offsetX, 36 + offsetY);
  50.         doc.add(img);
  51.         doc.close();
  52.     }
  53. }
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