C# – iTextsharp – PDF file size after inserting image

citextsharppdf-generation

I'm currently converting some legacy code to create PDF files using iTextSharp. We're creating a largish PDF file that contains a number of images, which I'm inserting like so:

Document doc = new Document(PageSize.A4, 50, 50, 25, 25);
PdfWriter writer = PdfWriter.GetInstance(doc, myStream);

writer.SetFullCompression();

doc.Open();

Image frontCover = iTextSharp.text.Image.GetInstance(@"C:\MyImage.png");

//Scale down from a 96 dpi image to standard itextsharp 72 dpi
frontCover.ScalePercent(75f);

frontCover.SetAbsolutePosition(0, 0);

doc.Add(frontCover);

doc.Close();

Inserting an image (20.8 KB png file) seems to increase the PDF file size by nearly 100 KB.

Is there a way of compressing the image before entry (bearing in mind that this needs to be of reasonable print quality), or of further compressing the entire PDF? Am I even performing any compression in the above example?

Best Answer

The answer appears to have been that you need to set an appropriate version of the PDF spec to target and then set the compression as follows:

PdfWriter writer = PdfWriter.GetInstance(doc, ms);
PdfContentByte contentPlacer;

writer.SetPdfVersion(PdfWriter.PDF_VERSION_1_5);

writer.CompressionLevel = PdfStream.BEST_COMPRESSION;

This has brought my file size down considerably. I also found that PNG's were giving me the best results as regards to final size of document.

Related Topic