Compress PDF using C#

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

PDF

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.

Try for FREE

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("your-api-secret");

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 -->

Upload the file and see how it works

You can set up the advanced conversion parameters and test the conversion result online using our interactive demo tool. It will auto-generate the code snippet for you!


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!

Advanced Compress PDF conversion parameters

Password String

Sets the password to open protected documents.

Presets Collection

Choose compression level from presets. If preset is selected all other compression options are ignored.

Values:   none text archive web ebook printer

ColorImageCompression Collection

Color image compression algorithm.

Values:   none jpg jpx zip

ColorImageQuality Integer

Color image compression quality. The parameter applies only to JPX and JPG compressions.

ColorImageDownsample Bool

Enable Bicubic image downsampling and decreases the number of pixels in the color image which in turn makes the file smaller.

ColorImageThresholdDpi Integer

Threshold in DPI to activate color images resampling. ColorImageDownsample property must be enabled.

ColorImageResampleDpi Integer

Color image resolution in DPI after Bicubic resampling. ColorImageDownsample property must be enabled.

GrayscaleImageCompression Collection

Grayscale image compression algorithm.

Values:   none jpg jpx zip

GrayscaleImageQuality Integer

Grayscale image compression quality. The parameter applies only to JPX and JPG compressions.

GrayscaleImageDownsample Bool

Enable Bicubic image downsampling and decreases the number of pixels in the grayscale image which in turn makes the file smaller.

GrayscaleImageThresholdDpi Integer

Threshold in DPI to activate grayscale images resampling. GrayscaleImageDownsample property must be enabled.

GrayscaleImageResampleDpi Integer

Grayscale image resolution in DPI after Bicubic resampling. GrayscaleImageDownsample property must be enabled.

MonochromeImageCompression Collection

Monochrome image compression algorithm.

Values:   none jbig2 jbig2l fax zip

MonochromeImageQuality Integer

Monochrome image compression quality. The parameter applies only to jbig2 and jbig2l compressions.

MonochromeImageDownsample Bool

Enable Bicubic image downsampling and decreases the number of pixels in the monochrome image which in turn makes the file smaller.

MonochromeImageThresholdDpi Integer

Threshold in DPI to activate Monochrome images resampling. MonochromeImageDownsample property must be enabled.

MonochromeImageResampleDpi Integer

Monochrome image resolution in DPI after Bicubic resampling. MonochromeImageDownsample property must be enabled.

RemoveBookmarks Bool

Remove bookmarks from the PDF file.

RemoveAnnotations Bool

Remove text annotations from the PDF file.

RemoveForms Bool

Remove PDF forms from the PDF file.

RemovePageLabels Bool

Remove page labels from the PDF file.

RemoveLayers Bool

Removes hidden layers and flatten visible ones.

RemoveArticleThreads Bool

Remove article threads from the PDF file.

RemoveTaggedInfo Bool

Remove tagged information from the PDF file.

RemovePageThumbnails Bool

Remove page thumbnails from the PDF file.

RemoveDuplicates Bool

Remove duplicate fonts and color profiles from the PDF file.

RemoveAlternateImages Bool

Removes alternate images and leave only the one for on-screen viewing.

RemoveNamedDestinations Bool

Remove named destinations from the PDF file.

RemoveEmbeddedFiles Bool

Remove embedded/attachments files from the PDF file.

RemovePieceInformation Bool

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

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.

CreateObjectStreams Bool

Create object streams in the PDF file. An object stream represents a stream that contains a sequence of PDF objects. This allows a greater number of PDF objects to be compressed. Property compatible with Acrobat 6/PDF v1.5 and later.

Optimize Bool

Optimize page content streams in the PDF file.

LzwToFlate Bool

In streams that use LZW encoding, use Flate instead.

Linearize Bool

Linearize PDF file and optimize for fast Web View.

PreservePdfa Bool

Preserve the PDF/A standard in the PDF file.

Try Compress PDF for free!