Cómo comprimir PDFs en C#

How to Compress PDFs

This article was translated from English: Does it need improvement?
Translated
View the article in English

PDF compression refers to the process of reducing the file size of a PDF (Portable Document Format) document. This compression is applied to make the PDF file more manageable for storage, sharing, and transmission, especially when dealing with large or image-rich documents.

Images typically occupy a significant portion of PDF file sizes because they are generally larger in size compared to text and other content. IronPdf offers PDF compression features that compress the embedded images and reduce the tree structure that often accompanies table data in PDFs.

Quickstart: Compress PDF Files with IronPDF

Effortlessly reduce your PDF file sizes using IronPDF's powerful compression tools. Start by loading your PDF with PdfDocument.FromFile, apply compression with the Compress method using default options, and save your optimized PDF. This quick and easy process ensures significant file size reduction while maintaining quality, perfect for developers seeking efficient document management in .NET C#.

Nuget IconGet started making PDFs with NuGet now:

  1. Install IronPDF with NuGet Package Manager

    PM > Install-Package IronPdf

  2. Copy and run this code snippet.

    PdfDocument.FromFile("input.pdf").CompressImages(40).SaveAs("compressed.pdf");
  3. Deploy to test on your live environment

    Start using IronPDF in your project today with a free trial
    arrow pointer


Compress Images Example

The way resizing JPEGs works, 100% quality has almost no loss, and 1% is a very low-quality output image.

  • 90% and above: considered high-quality
  • 80%-90%: considered medium-quality
  • 70%-80%: considered low-quality

Feel free to explore various values to understand the trade-off between quality and file size. It's important to note that the quality reduction will vary based on the type of input image, and certain images may experience more noticeable clarity reduction than others.

:path=/static-assets/pdf/content-code-examples/how-to/pdf-compression-image.cs
using IronPdf;

ChromePdfRenderer renderer = new ChromePdfRenderer();

PdfDocument pdf = renderer.RenderUrlAsPdf("https://en.wikipedia.org/wiki/Main_Page");

// Compress images in the PDF
pdf.CompressImages(40);

pdf.SaveAs("compressed.pdf");
Imports IronPdf

Private renderer As New ChromePdfRenderer()

Private pdf As PdfDocument = renderer.RenderUrlAsPdf("https://en.wikipedia.org/wiki/Main_Page")

' Compress images in the PDF
pdf.CompressImages(40)

pdf.SaveAs("compressed.pdf")
$vbLabelText   $csharpLabel

Compress Images - Size Comparison

Reduced by 39.24%!!

Compress images - size comparison

Understanding Image Compression Options

Let's delve into the details of our image compression options:

ShrinkImage: This feature scales down the image resolution based on its visible size in the PDF document. By doing so, it significantly reduces the size and quality of the images, optimizing them for efficient storage and transmission.

HighQualitySubsampling: This setting determines the chroma subsampling method used for image compression. Selecting "True" utilizes 4:4:4 chroma subsampling, ensuring a higher quality image with full color detail. Conversely, choosing "False" employs 4:1:1 chroma subsampling, which sacrifices some color detail to further reduce the image size.

Chroma subsampling is a crucial technique in digital image compression, aimed at reducing the data required to represent an image while preserving its visual quality. It achieves this by selectively reducing the resolution of color information (chrominance) while maintaining the full resolution of brightness information (luminance).

In "4:4:4" chroma subsampling, each pixel retains its own color information, resulting in no loss of color detail. Conversely, in "4:1:1" chroma subsampling, the color information is subsampled at a lower resolution, reducing color detail but also reducing file size.


Compress Tree Structure Example

This feature is used to reduce the size of the PDF by minimizing the tree structure created by the Chrome Engine. It works well with PDFs generated by the Chrome Engine from HTML containing extensive table data. Some PDF rendering engines might output PDFs without this tree structure, making the feature not effective.

The downside of removing all this tree structure is that for some PDFs, highlighting text or extracting may not work as effectively.

Let's use the PDF with table data to test the CompressStructTree method.

:path=/static-assets/pdf/content-code-examples/how-to/pdf-compression-tree-structure.cs
using IronPdf;

PdfDocument pdf = PdfDocument.FromFile("table.pdf");

// Compress tree structure in PDF
pdf.CompressStructTree();

pdf.SaveAs("compressedTable.pdf");
Imports IronPdf

Private pdf As PdfDocument = PdfDocument.FromFile("table.pdf")

' Compress tree structure in PDF
pdf.CompressStructTree()

pdf.SaveAs("compressedTable.pdf")
$vbLabelText   $csharpLabel

Compress Tree Structure - Size Comparison

Reduced by 67.90%!! This percentage increases with larger table PDFs.

Compress tree structure - size comparison

Advanced Compression Methods

IronPdf also has a Compress method that can be used to configure both image compression and tree structure compression, making compressing documents easier than ever.

:path=/static-assets/pdf/content-code-examples/how-to/pdf-compression-compress.cs
using IronPdf;

PdfDocument pdf = PdfDocument.FromFile("sample.pdf");

CompressionOptions compressionOptions = new CompressionOptions();

// Configure image compression
compressionOptions.CompressImages = true;
compressionOptions.JpegQuality = 80;
compressionOptions.HighQualityImageSubsampling = true;
compressionOptions.ShrinkImages = true;

// Configure tree structure compression
compressionOptions.RemoveStructureTree = true;

pdf.Compress(compressionOptions);

pdf.SaveAs("compressed.pdf");
Imports IronPdf

Private pdf As PdfDocument = PdfDocument.FromFile("sample.pdf")

Private compressionOptions As New CompressionOptions()

' Configure image compression
compressionOptions.CompressImages = True
compressionOptions.JpegQuality = 80
compressionOptions.HighQualityImageSubsampling = True
compressionOptions.ShrinkImages = True

' Configure tree structure compression
compressionOptions.RemoveStructureTree = True

pdf.Compress(compressionOptions)

pdf.SaveAs("compressed.pdf")
$vbLabelText   $csharpLabel

Explore Available Options

  • CompressImages: Controls whether existing images in the document are compressed using JPG encoding. It defaults to false.
  • RemoveStructureTree: Removing the structure tree can significantly reduce the disk space used by the document. However, it may negatively impact text selection, particularly in complicated documents.
  • JpegQuality: Specifies the JPEG quality (ranging from 1 to 100) to be used during image compression. It defaults to 42.
  • HighQualityImageSubsampling: This property determines whether to use 4:4:4 chroma subsampling for higher image quality (true) or 4:1:1 chroma subsampling to further reduce image size (false).
  • ShrinkImages: Scaling down the image resolution can drastically reduce the size and quality of the images in the document.

Ready to see what else you can do? Check out our tutorial page here: Addtional Features

Preguntas Frecuentes

¿Cómo puedo comprimir imágenes PDF en .NET C#?

Puedes utilizar IronPDF para comprimir imágenes PDF en .NET C#. La biblioteca proporciona un método llamado CompressImages, que te permite ajustar la calidad JPEG y elegir entre diferentes opciones de subsampling de croma para reducir el tamaño de las imágenes de manera efectiva.

¿Cuál es el beneficio de usar una biblioteca .NET para la compresión de PDF?

Usar una biblioteca .NET como IronPDF para la compresión de PDF te permite integrar la reducción de tamaño de PDF directamente en tus aplicaciones C#, mejorando la gestión de documentos al reducir el tamaño de los archivos para facilitar su almacenamiento y compartición.

¿Cómo reduzco el tamaño de los PDFs con datos extensivos de tablas?

Para reducir el tamaño de los PDFs con datos extensivos de tablas, puedes usar el método CompressStructTree de IronPDF. Este método minimiza la estructura del árbol del PDF, reduciendo significativamente el tamaño del archivo mientras se mantiene la integridad del documento.

¿Qué opciones están disponibles para el ajuste de calidad de imagen en la compresión de PDF?

IronPDF proporciona opciones para ajustar la calidad de la imagen durante la compresión, como el parámetro JpegQuality, que varía de 1 a 100. Valores más altos mantienen más detalle de la imagen, mientras que valores más bajos aumentan la compresión.

¿Puedo controlar el subsampling de croma durante la compresión de imágenes PDF?

Sí, IronPDF te permite controlar el subsampling de croma durante la compresión de imágenes PDF con la configuración HighQualitySubsampling. Esto te permite elegir entre mayor calidad de imagen (4:4:4) o una mayor reducción de tamaño (4:1:1).

¿Cuáles son las posibles desventajas de eliminar la estructura del árbol en los PDFs?

Aunque eliminar la estructura del árbol en los PDFs usando las funciones de compresión de IronPDF puede reducir significativamente el tamaño del archivo, puede afectar la selección y extracción de texto en documentos complejos, por lo que es importante considerar este compromiso.

¿Cómo configuro la compresión de imágenes y estructura de árbol en los PDFs?

IronPDF ofrece un método Compress que te permite configurar tanto la compresión de imágenes como la de estructura de árbol en los PDFs. Este método proporciona flexibilidad para ajustar las configuraciones y alcanzar el equilibrio deseado entre calidad y tamaño del archivo.

¿Qué pasos debo seguir para comenzar a comprimir PDFs en .NET C#?

Para comenzar a comprimir PDFs en .NET C#, descarga la biblioteca IronPDF desde NuGet, importa un PDF existente o renderiza uno nuevo, y usa métodos como CompressImages y CompressStructTree para reducir efectivamente el tamaño del archivo.

¿IronPDF es totalmente compatible con .NET 10 al comprimir archivos PDF?

Sí, IronPDF es totalmente compatible con .NET 10. Puede usarlo en proyectos .NET 10 para comprimir archivos PDF con los mismos métodos, como CompressImages , CompressStructTree o el método Compress con CompressionOptions , para obtener resultados y un rendimiento consistentes. Es compatible con .NET 10 entre sus versiones de entorno de ejecución. ⁠([ironpdf.com](https://ironpdf.com/?utm_source=openai))

Chaknith Bin
Ingeniero de Software
Chaknith trabaja en IronXL e IronBarcode. Tiene un profundo conocimiento en C# y .NET, ayudando a mejorar el software y apoyar a los clientes. Sus conocimientos derivados de las interacciones con los usuarios contribuyen a mejores productos, documentación y experiencia en general.
Revisado por
Jeff Fritz
Jeffrey T. Fritz
Gerente Principal de Programas - Equipo de la Comunidad .NET
Jeff también es Gerente Principal de Programas para los equipos de .NET y Visual Studio. Es el productor ejecutivo de la serie de conferencias virtuales .NET Conf y anfitrión de 'Fritz and Friends', una transmisión en vivo para desarrolladores que se emite dos veces a la semana donde habla sobre tecnología y escribe código junto con la audiencia. Jeff escribe talleres, presentaciones, y planifica contenido para los eventos de desarrolladores más importantes de Microsoft, incluyendo Microsoft Build, Microsoft Ignite, .NET Conf y la Cumbre de Microsoft MVP.
¿Listo para empezar?
Nuget Descargas 16,154,058 | Versión: 2025.11 recién lanzado