Image on rotated page

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

20th November 2015
admin-marketing

Switch code for this example

Example that shows how to position an image on a rotated page.



ImageOnRotatedPage.java
  1. /*
  2.  * Example written in answer to:
  3.  * http://stackoverflow.com/questions/33787785/itext-rotate-pdf-document-but-not-image
  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.PageSize;
  11. import com.itextpdf.text.pdf.PdfWriter;
  12. import java.io.File;
  13. import java.io.FileOutputStream;
  14. import java.io.IOException;
  15. import sandbox.WrapToTest;
  16.  
  17. /**
  18.  * @author Bruno Lowagie (iText Software)
  19.  */
  20. @WrapToTest
  21. public class ImageOnRotatedPage {
  22.     public static final String IMAGE = "resources/images/cardiogram.png";
  23.     public static final String DEST = "results/images/cardiogram.pdf";
  24.    
  25.     public static void main(String[] args) throws IOException, DocumentException {
  26.         File file = new File(DEST);
  27.         file.getParentFile().mkdirs();
  28.         new ImageOnRotatedPage().createPdf(DEST);
  29.     }
  30.    
  31.     public void createPdf(String dest) throws IOException, DocumentException {
  32.         Document document = new Document(PageSize.A4.rotate());
  33.         PdfWriter.getInstance(document, new FileOutputStream(dest));
  34.         document.open();
  35.         Image img = Image.getInstance(IMAGE);
  36.         img.scaleToFit(770, 523);
  37.         float offsetX = (770 - img.getScaledWidth()) / 2;
  38.         float offsetY = (523 - img.getScaledHeight()) / 2;
  39.         img.setAbsolutePosition(36 + offsetX, 36 + offsetY);
  40.         document.add(img);
  41.         document.close();
  42.     }
  43.    
  44. }
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