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

Compressing images is an effective way for reducing the size of a scanned PDF or a normal PDF that contains multiple high quality images inside. Spire.PDF provides a straightforward method TryCompressImage() to compress the high resolution images in PDF.

Step 1: Create a PdfDocument instance and load a sample PDF file.

PdfDocument doc = new PdfDocument("Input.pdf");

Step 2: Disable increment update when updating the document. The TryCompressImage() method will make changes on the existing bytes in the file and overwrite the original.

doc.FileInfo.IncrementalUpdate = false;

Step 3: Traverse the Pages collection to get all images in the document. Invoke TryCompressImage() method to try to compress each of them.

foreach (PdfPageBase page in doc.Pages)
{
    if (page != null)
    {
        if (page.ImagesInfo != null)
        {
            foreach (PdfImageInfo info in page.ImagesInfo)
            {
                page.TryCompressImage(info.Index);
            }
        }
    }                              
}

Step 4: Save the file.

doc.SaveToFile("Output.pdf");

Result:

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

Full Code:

[C#]
PdfDocument doc = new PdfDocument("Input.pdf");
doc.FileInfo.IncrementalUpdate = false;
foreach (PdfPageBase page in doc.Pages)
{
    if (page != null)
    {
        if (page.ImagesInfo != null)
        {
            foreach (PdfImageInfo info in page.ImagesInfo)
            {
                page.TryCompressImage(info.Index);
            }
        }
    }                              
}                                
doc.SaveToFile("Output.pdf");
[VB.NET]
Dim doc As New PdfDocument("Input.pdf")
doc.FileInfo.IncrementalUpdate = False
For Each page As PdfPageBase In doc.Pages

    If page IsNot Nothing Then
        If page.ImagesInfo IsNot Nothing Then

            For Each info As PdfImageInfo In page.ImagesInfo
                page.TryCompressImage(info.Index)

            Next
        End If
    End If
Next
doc.SaveToFile("Output.pdf")