简体   繁体   中英

c# high resolution images in PDF

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, becouse they're too large. Then they loose their quality. Is there any way to put big image to a4 page without loosing 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();

then I'm adding each picture

document.Add(iTextSharp.text.Image.GetInstance(toSaveImage, System.Drawing.Imaging.ImageFormat.Tiff));

and closing the document

document.Close();

First let me clear a couple of misunderstandings:

  • a PDF document doesn't have a resolution. The comment by spender was wrong. 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 Image object in iTextSharp, 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:

Image img =
    iTextSharp.text.Image.GetInstance(toSaveImage,
        System.Drawing.Imaging.ImageFormat.Tiff);
Rectangle pagesize = new Rectangle(img.ScaledWidth, img.ScaledHeight);
Document document = new Document(pagesize);
img.SetAbsolutePosition(0, 0);
document.Add(img);

I created the Document based on the scaled dimensions of the Image. Don't let the method names mislead you: ScaledWidth and ScaledHeight 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.

I've set the absolute position to the lower-left corner. That's safer than setting the page margins to 0.

EDIT: If you don't want to change the page size, then you have to use the ScaleToFit() method:

Image img =
    iTextSharp.text.Image.GetInstance(toSaveImage,
        System.Drawing.Imaging.ImageFormat.Tiff);
img.ScaleToFit(PageSize.A4);

Note that the method to scale to fit to a Rectangle object was introduced in one of the latest iTextSharp versions. An alternative would be to use the ScaleToFit() method that requires the width and the height of the rectangle.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM