Articles in this section
Category / Section

How to compress WinForms PDF using C# and VB.NET?

8 mins read

The Syncfusion Essential PDF is a feature-rich and high-performance .NET PDF library used to create, read, and edit PDF documents programmatically without Adobe dependencies. This library also offers functionality to merge, split, stamp, form, compress, and secure PDF files.

Using this library, you can optimize or reduce a PDF file size in C# and VB.NET using different techniques as follows:

  • Shrinking all images.
  • Optimizing fonts.
  • Removing metadata.
  • Optimizing incremental updates.
  • Removing or flattening form fields.
  • Removing or flattening annotations.

Steps to compress the PDF programmatically:

  1. Create a new C# Windows Forms application project.Create Windows Forms application in Visual Studio

 

  1. Install the Syncfusion.Pdf.WinForms NuGet package as a reference to your .NET standard applications from NuGet.org. Refer NuGet package to the project

 

  1. Include the following namespaces in the Form.cs file.

C#

using Syncfusion.Pdf;
using Syncfusion.Pdf.Parsing;

 

VB.NET

Imports Syncfusion.Pdf
Imports Syncfusion.Pdf.Parsing

 

  1. Use the following code snippet to compress the existing PDF document.

C#

// [C# Code]
// Loads an existing PDF document
PdfLoadedDocument loadedDocument = new PdfLoadedDocument(inputFile);
// Create new PDF compression options
PdfCompressionOptions options = new PdfCompressionOptions();
// Compress image
options.CompressImages = true;
options.ImageQuality = 50;
// Compress the font data
options.OptimizeFont = true;
// Compress the page contents
options.OptimizePageContents = true;
// Remove the metadata information
options.RemoveMetadata = true;
// Set the options to loaded PDF document
loadedDocument.CompressionOptions = options;
// Restructure the document
loadedDocument.FileStructure.IncrementalUpdate = false;
// Remove form fields and their data
RemoveFormFields(loadedDocument, false);
// Remove annotations and their data
RemoveAnnotations(loadedDocument, false);
// Save the document
loadedDocument.Save("Sample.pdf");
// Close the document
loadedDocument.Close(true);
// This will open the PDF file, so the result will be seen in the default PDF viewer
Process.Start("Sample.pdf");

// Remove form fields and their data
private void RemoveFormFields(PdfLoadedDocument loadedDocument, bool value)
{
    if (!value)
    {
        int totalFieldCount = loadedDocument.Form.Fields.Count;
        for (int i = totalFieldCount - 1; i >= 0; i--)
        {
            PdfField field = loadedDocument.Form.Fields[i] as PdfField;
            if (field != null)
            {
                loadedDocument.Form.Fields.Remove(field);
            }
        }
    }
}

// Remove annotations and their data
private void RemoveAnnotations(PdfLoadedDocument loadedDocument, bool value)
{
    if (!value)
    {
        PdfLoadedAnnotationCollection collection = null;
        for (int j = 0; j < loadedDocument.Pages.Count; j++)
        {
            collection = loadedDocument.Pages[j].Annotations;
            int totalAnnotationCount = collection.Count;
            for (int i = totalAnnotationCount - 1; i >= 0; i--)
            {
                collection.RemoveAt(i);
            }
        }
    }
}

 

VB.NET

' [VB Code]
' Loads an existing PDF document
Dim loadedDocument As New PdfLoadedDocument(inputFile)
' Create new PDF compression options
Dim options As New PdfCompressionOptions()
' Compress image
options.CompressImages = True
options.ImageQuality = 50
' Compress the font data
options.OptimizeFont = True
' Compress the page contents
options.OptimizePageContents = True
' Remove the metadata information
options.RemoveMetadata = True
' Set the options to loaded PDF document
loadedDocument.CompressionOptions = options
' Restructure the document
loadedDocument.FileStructure.IncrementalUpdate = False
' Remove form fields and their data
RemoveFormFields(loadedDocument, False)
' Remove annotations and their data
RemoveAnnotations(loadedDocument, False)
' Save the document
loadedDocument.Save("Sample.pdf")
' Close the document
loadedDocument.Close(True)
' This will open the PDF file, so the result will be seen in the default PDF viewer
Process.Start("Sample.pdf")

' Remove annotations and their data
Private Sub RemoveAnnotations(loadedDocument As PdfLoadedDocument, value As Boolean)
    If Not value Then
        Dim collection As PdfLoadedAnnotationCollection = Nothing

        For j As Integer = 0 To loadedDocument.Pages.Count - 1
            collection = loadedDocument.Pages(j).Annotations
            Dim totalAnnotationCount As Integer = collection.Count

            For i As Integer = totalAnnotationCount - 1 To 0 Step -1
  
                collection.RemoveAt(i)
            Next
        Next
    End If
End Sub

' Remove form fields and their data
Private Sub RemoveFormFields(loadedDocument As PdfLoadedDocument, value As Boolean)
    If Not value Then
        Dim totalFieldCount As Integer = loadedDocument.Form.Fields.Count
        For i As Integer = totalFieldCount - 1 To 0 Step -1
            Dim field As PdfField = TryCast(loadedDocument.Form.Fields(i), PdfField)
            If field IsNot Nothing Then
                loadedDocument.Form.Fields.Remove(field)
            End If
        Next
    End If
End Sub

A complete work sample can be downloaded from OptimizePDFSample.Zip.

By executing the program, the original PDF document size is reduced, and you will get the optimized PDF.

Take a moment to peruse the documentation, where you will find other options like compressing images with image quality, optimizing embedded fonts, optimizing page contents, and removing metadata information with code examples.

An online sample link to compress existing PDF Click here to explore the rich set of Syncfusion Essential PDF features.

Note:

Starting with v16.2.0.x, if you reference Syncfusion assemblies from trial setup or from the NuGet feed, include a license key in your projects. Refer to link to learn about generating and registering Syncfusion license key in your application to use the components without trail message.


Conclusion
I hope you enjoyed learning about how to compress WinForms PDF using C# and VB.NET.
You can refer to our WinForms PDF feature tour page to learn about its other groundbreaking feature representations and documentationand how to quickly get started with configuration specifications. For current customers, you can check out our components from the License and Downloads page. If you are new to Syncfusion, you can try our 30-day free trial to check out our other controls.
If you have any queries or require clarifications, please let us know in the comments section below. You can also contact us through our support forums or feedback portal. We are always happy to assist you!
Did you find this information helpful?
Yes
No
Help us improve this page
Please provide feedback or comments
Comments (0)
Please  to leave a comment
Access denied
Access denied