PDF Compression
IronPDF provides support for compressing PDFs, primarily by reducing the size of embedded images within the document using the CompressImages method.
When resizing JPEGs, the quality setting determines the balance between file size and image clarity. A quality of 100% results in almost no noticeable loss, while 1% produces a very low-quality image. Generally, 90% and above is considered high quality, 80%-90% is medium quality, and 70%-80% is low quality. Reducing the quality below 70% can significantly lower the file size but may result in visibly lower image quality.
It's recommended to experiment with different quality values to find the ideal balance between file size and image clarity for your specific needs. Keep in mind that the degree of visible quality reduction depends on the original image; some images may degrade more noticeably than others.
5 Steps to Compress PDF Files in C#
- var pdf = new PdfDocument("document.pdf");
- pdf.CompressImages(60);
- pdf.SaveAs("document_compressed.pdf");
- pdf.CompressImages(90, ShrinkImage: true);
- pdf.SaveAs("document_scaled_compressed.pdf");
First, we will need to load the PDF document that needs to be compressed. This can be done with the PdfDocument
class, which can be used to load an existing PDF file from the given file path.
Now, we will demonstrate compressing images within the PDF with a specified quality. To do this, we will use the CompressImages
method, and pass to it the quality of which we want it to use during compression. This method will compress all of the images within our PDF document to 60% of their original quality. The quality parameter is an integer from 1 (lowest quality, highest compression) to 100 (highest quality, least compression). This reduces the file size, but you will need to be aware that it can result in some loss of image clarity. We can then save this newly compressed PDF document using the SaveAs
method.
Next, let's demonstrate another approach to image compression within a PDF document, compressing images with scaling. To do this, we will again use the CompressImages
method. This time, along with the compression quality, we will also be passing the ShrinkImage
boolean to the method and setting it to true. This boolean, when set to true, scales down the image resolution based on its visible size within the PDF. This means that if an image is larger than what is visibly displayed, it will be resized to match its displayed dimensions. However, this can lead to image distortion.
Finally, we will again use the SaveAs
method to save the compressed PDF to the specified location. This approach is useful when optimizing PDFs for smaller file sizes, such as for web or email use, while balancing quality and compression.
Click here to view the How-to Guide, including examples, sample code, and files >