Compress PDF Files in C#

Knowing how to reduce PDF file size can save you from a number of different frustrating hold-ups—like trying to send a large file via email, only to get the annoying popup telling us the file is too large to send. This post provides two solutions in C# to make PDFs smaller.

Before start, you should download .NET PDF component and add the dll file as reference to your Visual Studio.

Reducing PDF file size by compressing content

Content compression involves removing all extra space characters, inserting a single repeat character to indicate a string of repeated characters and substituting smaller bit strings for frequently occurring characters.

//Creates a new PDF document
PdfDocument doc = new PdfDocument();
//Load file
doc.LoadFromFile(@"C:\Users\Administrator\Desktop\example.pdf");
//Disables the incremental update
doc.FileInfo.IncrementalUpdate = false;
//Sets the compression level to best
doc.CompressionLevel = PdfCompressionLevel.Best;
//Save file
doc.SaveToFile("Compressed.pdf");
doc.Close();

Reducing PDF file size by shrinking all images

For PDF files that contain many images, compressing/changing the quality of them all can make a noticeable difference in making your PDF smaller.

//Creates a new PDF document
PdfDocument pdf = new PdfDocument();
//Load file
pdf.LoadFromFile(@"C:\Users\Administrator\Desktop\Image_PDF.pdf");
pdf.FileInfo.IncrementalUpdate = false;

foreach (PdfPageBase page in pdf.Pages)
{
    Image[] images = page.ExtractImages();
    if (images != null && images.Length > 0)
    {
        for (int j = 0; j < images.Length; j++)
        {
            Image image = images[j];
            PdfBitmap bp = new PdfBitmap(image);
            bp.Quality = 20; //Reduces the quality of the image
            page.ReplaceImage(j, bp);
        }
    }
}
//Save file
pdf.SaveToFile("image_compressed.pdf");
Advertisements

Author: janewdaisy

.NET Program Beginner. Share methods about how to use C#/VB.NET to export data, operate Word, Excel, PDF and other useful skills.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s