I'm trying to put high quality images into PDF (one per page). But if I set page size to A4, I have to resize my pictures, because they're too large. Then they lose their quality. Is there any way to add a big image to an A4 page without losing quality?
I'm using iTextSharp library, firstly I'm creating the document
document = new Document(PageSize.A4, 0, 0, 0, 0); FileStream output = new FileStream(pdfPath + "document.pdf", FileMode.Create); PdfWriter writer = PdfWriter.GetInstance(document, output); document.Open();
First let me clear a couple of misunderstandings:
- a PDF document as such doesn't have a resolution. There is no such thing as DPI in PDF. The resolution only comes into play when a PDF is rendered (to the screen, to paper,...) and that's why there may be a DPI in a PDF viewer (but that's something completely different).
- when you scale an
Imageobject, you don't lose any information: the number of pixels remains the same. Whereas PDF doesn't have a resolution, the images inside a PDF do. When you the image scale down (that is: you put the same number of pixels on a smaller canvas), the resolution increases; when you scale up, the resolution decreases.
Now for your question: you're not obliged to create A4 pages:
PdfDocument pdfDoc = new PdfDocument(new PdfWriter(dest)); Image img = new Image(ImageDataFactory.create(imgSrc)); Rectangle rect = new Rectangle(img.getImageScaledWidth(), img.getImageScaledHeight()); PageSize pageSize = new PageSize(rect); Document doc = new Document(pdfDoc, pageSize); img.setFixedPosition(0, 0); doc.add(img); pdfDoc.close();
My code snippet is in Java, but you can easily port it to C#. I created the
Document based on the scaled dimensions of the Image. Don't let the method names mislead you:
getImageScaledHeight() are the safest methods to use when getting the dimensions of an Image. Not only do they include any scaling operations, you may have done on the image, the also take into account the space needed for the image after rotating it.
Observe that I've set the absolute position to the lower-left corner. That's safer than setting the page margins to 0.
If you don't want to change the page size, then you have to use the
Image img = new Image(ImageDataFactory.create(imgSrc)); img.scaleToFit(PageSize.A4.getWidth(), PageSize.A4.getHeight());
Scale to fit will keep the aspect ratio of the image. If the aspect ratio of the image is different from the aspect ratio of the page, the page will have a margin.
Click How to preserve high resolution images in PDF? if you want to see how to answer this question in iText 5.