How to Compress PDF Document in C#, VB.NET

Spire.PDF allows us to compress PDF document in the following two ways:

  • Compressing content
  • Compressing image

Compressing content

In Spire.PDF, we can control the compression level of the document by using the PdfCompressionLevel enum. The compression level can be set to best, normal, above normal, none etc.

[C#]
//Loads the PDF document
PdfDocument doc = new PdfDocument("Test.pdf");
//Disables the incremental update
doc.FileInfo.IncrementalUpdate = false;
//Sets the compression level to best
doc.CompressionLevel = PdfCompressionLevel.Best;
//Saves and closes the resultant document
doc.SaveToFile("Compressed.pdf");
doc.Close();
[VB.NET]
'Loads the PDF document
Dim doc As New PdfDocument("Test.pdf")
'Disables the incremental update
doc.FileInfo.IncrementalUpdate = False
'Sets the compression level to best
doc.CompressionLevel = PdfCompressionLevel.Best
'Saves and closes the resultant document
doc.SaveToFile("Compressed.pdf")
doc.Close()

Screenshot:

How to Compress PDF Document in C#, VB.NET


Compressing image

We can compress/change the quality of the images in the PDF document by using the following code example.

[C#]
//Loads the PDF document
PdfDocument doc = new PdfDocument("Image.pdf");
//Disables the incremental update
doc.FileInfo.IncrementalUpdate = false;

//Traverses all pages
foreach (PdfPageBase page in doc.Pages)
{
    //Extracts images from page
    Image[] images = page.ExtractImages();
    if (images != null && images.Length > 0)
    {
        //Traverses all images
        for (int j = 0; j < images.Length; j++)
        {
            Image image = images[j];
            PdfBitmap bp = new PdfBitmap(image);
            //Reduces the quality of the image
            bp.Quality = 20;
            //Replaces the old image in the document with the compressed image
            page.ReplaceImage(j, bp);
        }
    }                
}
//Saves and closes the resultant document
doc.SaveToFile("Output.pdf");
doc.Close();
[VB.NET]
'Loads the PDF document
Dim doc As New PdfDocument("Image.pdf")
'Disables the incremental update
doc.FileInfo.IncrementalUpdate = False

'Traverses all pages
For Each page As PdfPageBase In doc.Pages
	'Extracts images from page
	Dim images As Image() = page.ExtractImages()
	If images IsNot Nothing AndAlso images.Length > 0 Then
		'Traverses all images
		For j As Integer = 0 To images.Length - 1
			Dim image As Image = images(j)
			Dim bp As New PdfBitmap(image)
			'Reduces the quality of the image
			bp.Quality = 20
			'Replaces the old image in the document with the compressed image
			page.ReplaceImage(j, bp)
		Next
	End If
Next
'Saves and closes the resultant document
doc.SaveToFile("Output.pdf")
doc.Close()

Screenshot:

How to Compress PDF Document in C#, VB.NET