Compress PDF using C#

Compress and reduce a PDF file size by up to 90%

Try for FREE

Compress PDF features

The Compress PDF C# library by ConvertAPI is a tool that allows for the compression and reduction of PDF file sizes by up to 90%. This C# library optimizes PDF quality by compressing text, graphics, images, subsetting fonts, and optimizing document structure. It offers various parameters for customization, including compression presets, color and grayscale image compression, and options to remove elements like bookmarks, annotations, forms, and embedded files from the PDF. The C# library also provides options for optimizing the PDF for web viewing and preserving the PDF/A standard.

C# library install

ConvertAPI provides an ASP.NET C# library that allows you to perform a Compress PDF conversion with just a few lines of code. Compress PDF documents using C# programming language with no effort at all!

NuGet Terminal >
Install-Package ConvertApi

Authenticate ConvertAPI C# library

You can obtain your secret key by signing up for a free account. Once you sign up, you'll receive 250 free conversions instantly! Grab your authentication secret from the account dashboard, and authenticate the ConvertAPI C# library like this:

// get your secret key here: https://www.convertapi.com/a/auth
ConvertApi convertApi = new ConvertApi("secret_or_token");

Compress PDF using C# in no time!

Once you have your authentication in place, simply copy-paste this pdf to compress conversion code snippet into your C# project:

// Code snippet is using the ConvertAPI JavaScript Client: https://github.com/ConvertAPI/convertapi-js

// Code snippet is using the ConvertAPI Node.js Client: https://github.com/ConvertAPI/convertapi-nodejs

// Code snippet is using the ConvertAPI PHP Client: https://github.com/ConvertAPI/convertapi-php

// Code snippet is using the ConvertAPI Java Client: https://github.com/ConvertAPI/convertapi-java

// Code snippet is using the ConvertAPI C# Client: https://github.com/ConvertAPI/convertapi-dotnet

# Code snippet is using the ConvertAPI Ruby Client: https://github.com/ConvertAPI/convertapi-ruby

# Code snippet is using the ConvertAPI Python Client: https://github.com/ConvertAPI/convertapi-python

// Code snippet is using the ConvertAPI Go Client: https://github.com/ConvertAPI/convertapi-go

REM Code snippet is using the command line utility program: https://github.com/ConvertAPI/convertapi-cli

<!-- For conversions with the multiple file result please refer to this example: https://repl.it/@ConvertAPI/HTML-Form-with-multiple-file-result -->

Try the conversion online - no coding required!

You can try out advanced conversion parameters and test the conversion result online using our interactive demo tool. This tool will produce the same conversion output as if you were using the library from your solution, and it will auto-generate the code snippet for you!

Try for FREE!

A detailed guide to PDF compression using C#

ConvertAPI provides a GDPR-compliant and ISO/IEC 27001-certified document processing and conversion REST API service. One of our popular conversions is Compress PDF API. It is incredibly efficient - it can reduce the PDF size up to 99% of the original size. The compressed PDF document will be ready to download in a blink of an eye.

PDF compression allows you to optimize PDF documents and reduce their size as much as possible without losing the quality. Compressing PDF files is extremely important for file sharing and long-term storage online, as it can help you save space and bandwidth. It works by re-encoding fonts, images and removing repetitive patterns without compromising the overall PDF quality.

You can test our PDF compressor online for free. Sign up for a free account and use our interactive demo tool to try the conversion using your own documents. Whether you want to share your documents via email or keep them for long-term storage, PDF Compression increases performance significantly!

ConvertAPI PDF compressor

This tutorial will go through the C# PDF compression implementation, all from the file upload to the compressed document result download. Even though ConvertAPI is a REST API service, we created a ConvertAPI DotNet wrapper library for your convenience, so you don't need to make any HTTP calls explicitly. Simply install the ConvertApi package from NuGet into your ASP.NET C# project and you are good to go.

To gain complete control over the compression, you can set up a custom compression level with a bunch of useful parameters. These parameters include image compression and resampling, an option to keep or remove multiple document assets like fonts, bookmarks, annotations, embedded files, etc. In addition, it allows you to optimize page content streams in the PDF file, linearize compressed documents and optimize for fast Web View. You can also compress password-protected files and preserve the PDF/A file format while performing the compression.

How to Compress a PDF using C# and .NET?

  1. Install the ConvertApi NuGet package
  2. Sign up for free and get your API secret
  3. Set up conversion parameters using our interactive demo tool
  4. Copy-paste the auto-generated code snippet into your project

1. ConvertAPI NuGet package installation

Our ConvertAPI C# library works with both .NET Standard and .NET Core. You can install the ConvertApi NuGet package by searching for ConvertApi in the NuGet package manager or by running this command:

PM> Install-Package ConvertApi

2. Get your secret key

Get your secret key and start using our service for free. Simply sign up for a free account and find your API Secret Key in your account dashboard. You can read more about different authentication methods in our docs.

Secret key

3. Set the compression parameters

Once you have our library installed into the ASP.NET project and got your ConvertAPI secret, you can set up the conversion parameters using our interactive demo tool. These parameters include image compression, image resampling, and the ability to remove particular PDF objects like bookmarks, annotations, embedded files, etc. You will find an auto-generated code snippet at the bottom of the page.

4. Compress the PDF files using C# programming language

As soon as you are happy with the conversion result on our website, copy-paste the code snippet into your project. Here is an example code snippet using some custom compression parameters:

var convertApi = new ConvertApi("your-api-secret");
var convert = await convertApi.ConvertAsync("pdf", "compress",
    new ConvertApiFileParam("File", @"C:\path\to\my_file.pdf"),
    new ConvertApiParam("ColorImageCompression", "zip"),
    new ConvertApiParam("ColorImageQuality", "70"),
    new ConvertApiParam("ColorImageDownsample", "true"),
    new ConvertApiParam("ColorImageThresholdDpi", "150"),
    new ConvertApiParam("ColorImageResampleDpi", "100"),
    new ConvertApiParam("RemoveBookmarks", "true"),
    new ConvertApiParam("RemoveAnnotations", "true"),
    new ConvertApiParam("RemoveEmbeddedFiles", "false"),
    new ConvertApiParam("UnembedBaseFonts", "true"),
    new ConvertApiParam("SubsetEmbeddedFonts", "true")
);
await convert.SaveFilesAsync(@"C:\converted-files\");

That's all it takes to implement PDF compression into the ASP.NET project. You can find a complete list of parameters on our interactive demo tool page.

Advanced techniques

Using our library, you can compress either a local file or a remote file accessible by a public URL. You can even compress your PDF using the file stream. Let's see some examples below.

Convert a local file

Converting a local file is the most straightforward and reliable approach. Set the source file path and the destination folder, and you will have your document converted in seconds!

var convertApi = new ConvertApi("your-api-secret");
var convert = await convertApi.ConvertAsync("pdf", "compress",
    new ConvertApiFileParam("File", @"C:\path\to\my_file.pdf"),
);
await convert.SaveFilesAsync(@"C:\converted-files\");

Convert a remote file

Compressing a remote is relatively simple too. Just make sure that the file is publicly accessible by a URL and that it has the application/pdf content type set.

var convertApi = new ConvertApi("your-api-secret");
var sourceFile = new Uri("https://cdn.convertapi.com/cara/testfiles/document-large.pdf");
var compressionResult = await convertApi.ConvertAsync("pdf", "compress", new ConvertApiFileParam(sourceFile));
var outputFileName = compressionResult.Files[0];
var fileInfo = await outputFileName.SaveFileAsync(Path.Combine(Path.GetTempPath(), outputFileName.FileName));

Convert file stream

You can also compress the PDF file stream. In this example, we will compress the file stream and receive the compressed document's file stream for further processing. Please note that you have to provide a file name explicitly in the new ConvertApiFileParam(stream, "sample.pdf") parameter:

var convertApi = new ConvertApi("your-api-secret");
using (FileStream stream = File.Open(@"c:\sample.pdf", FileMode.Open))
{
    var convertToPdf = await convertApi.ConvertAsync("pdf", "compress",
        new ConvertApiFileParam(stream, "sample.pdf")
    );
    var outputStream = await convertToPdf.Files.First().FileStreamAsync();
    Console.Write(new StreamReader(outputStream).ReadToEnd());
}

For more advanced techniques, please find our useful code examples on convertapi-dotnet GitHub repository.

Conclusion

Nowadays most of the documents are digitally shared and stored online, which makes it all about performance. By using our service, you can increase the effectiveness significantly. Our PDF compression tool is super simple to integrate into your project. It is fast, reliable, and secure. We provide 99.99% uptime so that you can compress your documents anytime, anywhere. You can find all compression parameters as well as the auto-generated code snippet on our PDF Compress API page. For more advanced techniques, please look at our code examples on GitHub. Happy coding!

Conversion parameters

Preset Collection

Choose a compression level from the available presets. If a preset is selected, all other compression options will be ignored. These presets are optimized for various use cases, such as balancing file size and quality.

Values:   none text archive web ebook printer

AutoImageCompress Bool

Automatically adjust image dimensions based on the PDF's DPI, reducing image quality to 90% for efficient compression.

For example, if an image has 300 DPI and the PDF has 96 DPI, the image dimensions will be reduced to comply with 96 DPI. When combined with ImageResolution, the method that results in greater compression is applied. For instance: If images originally have 300 DPI, ImageResolution is set to 150, and AutoImageCompress determines 100 DPI is optimal, the final result will dimensions reduced to comply with 100 DPI. Conversely, if ImageResolution specifies a lower value, it will take precedence.

ImageResolution Integer

Set the maximum image resolution in DPI. This setting can be combined with AutoImageCompress. In such cases, the compression will apply the lower resolution value, whether determined by the DPI setting or the AutoImageCompress property.

ImageQuality Integer

Set image quality in percentage. This setting overrides the default 90% quality value of AutoImageCompress.

RemoveForms Bool

Remove PDF forms from the PDF file.

RemoveDuplicates Bool

Remove duplicate fonts and color profiles from the PDF file.

RemovePieceInformation Bool

Remove piece information dictionaries like Adobe Illustrator or Photoshop private data.

RemoveEmbeddedFiles Bool

Remove embedded/attachments files from the PDF file.

RemoveStructureInformation Bool

Remove all structure information from the PDF document.

RemoveMetadata Bool

Detach the XMP metadata embedded in the document from its catalog, clear all properties in all schemas, and remove metadata from marked content.

RemoveUnusedResources Bool

Remove references to resources such as fonts, images, patterns.

UnembedBaseFonts Bool

Specifies whether to remove the base fonts from the PDF file.

SubsetEmbeddedFonts Bool

Output PDF should only contain font characters utilized in the original document, and any unused glyphs from all fonts in the document should be removed.

Optimize Bool

Optimize page content streams in the PDF file.

PreservePdfa Bool

Preserve the PDF/A standard in the PDF file.

Try Compress PDF for free!