DEV Community

Gia
Gia

Posted on

How to Compress PDF Documents Programmatically

Compressing PDF files can reduce their size, making them faster to upload, send, and store, while also saving disk space. In situations where large numbers of PDF documents need to be frequently processed, such as in file archiving, email transmission, and network sharing, using the compress PDF function can significantly improve work efficiency and usability. Furthermore, the compression process does not result in any loss or impact on the content of the PDF files, so users can confidently use this function to optimize their PDF files. Free Spire.PDF for .NET can achieve this easily. Here are the details and sample code.

Programming Environment

  • Visual Studio 2022
  • Free Spire.PDF for .NET

Import the Spire.xls.dll file into the program.

  • Download and install Free Spire.PDF for .NET.
  • After installation, open “Visual Studio” to create a new project.
  • Right-click "References" in the "Solution Explorer", and then select "Add Reference" > "Browse".
  • Find the dll file in the BIN folder under the installation path, click "OK".

Sample Code:

C#:

using Spire.Pdf;
using Spire.Pdf.Graphics;
using System.Drawing;
using Spire.Pdf.Utilities;

namespace CompressPdf
{
    class Program
    {
        static void Main(string[] args)
        {
            //Create a PdfDocument object
            PdfDocument doc = new PdfDocument();

            //Load a PDF file
            doc.LoadFromFile(@"sample.pdf");

            //Disable incremental update
            doc.FileInfo.IncrementalUpdate = false;

            //Set the compression level to best
            doc.CompressionLevel = PdfCompressionLevel.Best;

            //Loop through the pages in the document
            foreach (PdfPageBase page in doc.Pages)
            {
                //Create a PdfImageHelper object
                PdfImageHelper helper = new PdfImageHelper();

                //Get image information collection of a certain page
                PdfImageInfo[] imagesInfo = helper.GetImagesInfo(page);

                //Loop through the image information collection
                foreach (PdfImageInfo imageInfo in imagesInfo)
                {
                    //Replace a certain image with the compressed image
                    helper.ReplaceImage(imageInfo, CompressImage(imageInfo.Image));
                }

            }

            //Save the document to a PDF file
            doc.SaveToFile("output.pdf");
            doc.Close();
        }

        //Compress an image by reducing the quality
        private static PdfBitmap CompressImage(Image img)
        {
            PdfBitmap newImage = new PdfBitmap(img);
            newImage.Quality = 10;
            return newImage;
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

VB.NET

Imports Spire.Pdf
Imports Spire.Pdf.Graphics
Imports System.Drawing
Imports Spire.Pdf.Utilities

Namespace CompressPdf
    Class Program
        Shared  Sub Main(ByVal args() As String)
            'Create a PdfDocument object
            Dim doc As PdfDocument =  New PdfDocument() 

            'Load a PDF file
            doc.LoadFromFile("sample.pdf")

            'Disable incremental update
            doc.FileInfo.IncrementalUpdate = False

            'Set the compression level to best
            doc.CompressionLevel = PdfCompressionLevel.Best

            'Loop through the pages in the document
            Dim page As PdfPageBase
            For Each page In doc.Pages
                'Create a PdfImageHelper object
                Dim helper As PdfImageHelper =  New PdfImageHelper() 

                'Get image information collection of a certain page
                Dim imagesInfo() As PdfImageInfo =  helper.GetImagesInfo(page) 

                'Loop through the image information collection
                Dim imageInfo As PdfImageInfo
                For Each imageInfo In imagesInfo
                    'Replace a certain image with the compressed image
                    helper.ReplaceImage(imageInfo, CompressImage(imageInfo.Image))
                Next

            Next

            'Save the document to a PDF file
            doc.SaveToFile("output.pdf")
            doc.Close()
            System.Diagnostics.Process.Start("output.pdf")

        End Sub

        'Compress an image by reducing the quality
        Private Shared Function CompressImage(ByVal img As Image) As PdfBitmap
            Dim NewImage As PdfBitmap =  New PdfBitmap(img) 
            NewImage.Quality = 10
            Return NewImage
        End Function
    End Class
End Namespace
Enter fullscreen mode Exit fullscreen mode

Above code loads a sample PDF document and compresses its contents using Spire.PDF library. The document's incremental update is disabled, and the compression level is set to "best". A loop is used to traverse through all pages, and the image information collection of each page is retrieved using PdfImageHelper.GetImagesInfo() method. Then, each image is compressed using PdfImageHelper.ReplaceImage() method. Finally, the compressed document is saved to another PDF file using PdfDocument.SaveToFile() method.

Top comments (0)