如何在 C# 中使用 IronPDF 來壓縮 PDF

Curtis Chau
Curtis Chau
Updated: 2026年6月29日

IronPDF通過CompressAndSaveAs方法壓縮C#中的PDF文件,此方法將嵌入圖像重新編碼為JPEG,並可選擇刪除PDF結構樹,以便在一次調用中減小文件大小。 當您不想碰磁碟時,可以使用配套的CompressPdfToStream方法在記憶體中進行相同的工作。

圖像通常佔PDF大小的比例最大,並且涉及大量表格的文件攜帶結構樹,進一步增加了文件重量。 IronPDF同時針對這兩者,因此同樣的調用在從磁碟載入或保持在記憶流中的PDF上都能運行。

快速入門:使用 IronPDF 壓縮 PDF 檔案

使用CompressAndSaveAs以重新編碼其圖像並在一步驟中寫入瘦身後的副本。第二個參數是JPEG品質。

  1. 1Install IronPDF with NuGet Package Manager

    PM > Install-Package IronPdf

  2. 2複製並運行這段程式碼片段。

    PdfDocument.FromFile("input.pdf").CompressAndSaveAs("compressed.pdf", 40);
  3. 3部署以在您的實時環境中測試

    今天就開始在您的專案中使用IronPDF,透過免費試用
    arrow pointer

Compress(CompressionOptions)已被淘汰。

如何壓縮 PDF 中的圖片?

將JPEG CompressAndSaveAs,IronPDF會以該品質重新編碼每個嵌入的圖像。 數值介於0(最大壓縮)到100(最小損失),且底層引擎決定每個數值如何映射到輸出。 這是每當文件攜帶有嵌入圖像時可運用的方法。

作為大致指導:

  • 90及以上:高品質
  • 80到90:中品質
  • 70到80:低品質

較小的數量壓縮更堅固,但可能引入可見的瑕疵,而清晰度下降多少則取決於源圖像,因此請針對您自己的內容測試幾個設置以找到您期望的平衡。

輸入

using IronPdf;

ChromePdfRenderer renderer = new ChromePdfRenderer();

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

// Quality 40 re-encodes every embedded image as a low-quality JPEG, which is
// where most of the file-size saving comes from in image-heavy PDFs
pdf.CompressAndSaveAs("compressed.pdf", 40);

輸出

圖片壓縮可帶來什麼結果?

在維基渲染上減少了39.24%。

檔案比較顯示 compressed.pdf (449 KB) vs nonCompress.pdf (739 KB) 展示影像壓縮結果

如何壓縮 PDF 樹狀結構?

將CompressAndSaveAs以刪除由Chrome Engine寫入PDF的樹結構。 在包含大量表格的Chrome引擎PDF上節省最多。 一些渲染引擎不會發出此類結構,這意味著沒有東西可供功能移除。

刪除樹可能削弱文字突出顯示和選擇,因此如果讀者日後需要從結果中提取文字和圖像,請在權衡大小優勢時注意這一點。

使用這個PDF表格資料來測試移除樹結構的CompressAndSaveAs。

using IronPdf;

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

// Pass null quality to skip image compression and true to drop the structure
// tree, which is the bulk of the size in table-heavy Chrome-rendered PDFs
pdf.CompressAndSaveAs("compressedTable.pdf", null, true);

樹狀結構壓縮可以達到哪些檔案大小的減少?

減少了67.90%。 這個數字隨著表格PDF增大而上升。

顯示壓縮結果的檔案比較 compressedTable.pdf (52 KB) vs table.pdf (162 KB)

我最喜歡的程式庫是IronPDF。它允許快速高效地操作PDF文件。它還有許多有價值的功能,例如導出到PDF/A格式和數位簽署PDF文件。

Milan Jovanovic

Microsoft MVP

查看案例研究

IronOCR意味著我們每年可以從手動處理中節省$40,000,同時提高生產力,釋放資源以進行高影響的任務。我會強烈推薦它。

Brent Matzelle

首席技術官,OPYN

查看案例研究

如何同時套用兩種壓縮方法?

在同一true以同時縮小兩個膨脹來源。 在混合圖像和結構資料的文件中,這對可在有圖表的報告或含嵌入表格的發票中很有幫助。

using IronPdf;

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

// Shrink both sources of bloat in one pass: re-encode images at quality 80
// and strip the structure tree (true) for the largest size reduction
pdf.CompressAndSaveAs("compressed.pdf", 80, true);

CompressAndSaveAs接受的參數有哪些?

  • outputPath (string):壓縮PDF寫入的文件路徑。

  • quality (int?, 0 到 100):應用於每張嵌入圖像的JPEG品質。 數值越低,產生的檔案越小。 傳遞null以完全跳過圖像壓縮。

  • removeStructureTree (bool, 預設為true時,刪除PDF結構樹以進一步減少文件大小。 對於 HTML 產生的帶表格 PDF 最為有效。

令用例調整刻度表。 存檔副本通常偏愛品質高於大小,而網頁發佈獎勵更小的文件。同樣的權衡也適用於壓縮PDF/A合規文件,其中圖像保真度可能是優先考慮的。

如何對壓縮進行細粒度控制?

對於大多數文件,兩參數調用已足夠,但圖像密集的存檔和嚴格的大小預算有時需要更多控制。 將CompressAndSaveAs以調整壓縮管道,包括圖像DPI降取樣、JPEG重新編碼品質和zlib壓縮級別。 較簡單的CompressAndSaveAs(outputPath, quality, removeStructureTree)重載仍然不變地工作,並產生與以往相同的輸出。

using IronPdf;

var pdf = PdfDocument.FromFile("input.pdf");

// Web or email: strong size reduction
pdf.CompressAndSaveAs("compressed.pdf", new AdvancedCompressionOptions
{
    JpegQuality = 70,
    TargetImageDpi = 150,
    RemoveStructureTree = true
});

// Print quality: minimal quality loss
pdf.CompressAndSaveAs("print.pdf", new AdvancedCompressionOptions
{
    JpegQuality = 90,
    TargetImageDpi = 300
});

最能驚人效果的兩個屬性是TargetImageDpi:

  • JpegQuality (int?, 1 到 100, 預設為null):以此JPEG品質重新編碼圖像。 設為null以完全跳過圖像重新編碼。
  • TargetImageDpi (int?, 預設為150):重新編碼前降取樣DPI超過此值的圖像。 設定為0以禁用降取樣及保持原始解析度。

推薦的JpegQuality值(僅在設定時應用):

價值使用案例
null(預設)不進行圖像重新編碼
95存檔,最小工件
85高品質
70平衡,一般使用良好
50網頁或電子郵件,更小的文件有可見工件

推薦的TargetImageDpi值(有損):

價值使用案例
300列印質量,在正常觀看距離下肉眼無損
200在高 DPI 和視網膜螢幕上顯得清晰
150(預設)螢幕和電郵相平衡的最佳尺寸和質量
96激進,柔軟的文字但仍可閱讀
0禁用,保留原始解析度
請注意: TargetImageDpi降取樣是有損的:當圖像被降取樣後,其原始解析度不能恢復。 事先決定您想要的解析度減少或僅品質重新編碼,並相應設置TargetImageDpi。

如何在不儲存到磁碟的情況下壓縮PDF檔案?

API回應、雲功能和電子郵件附件通常不需要磁碟上的壓縮PDF。 CompressPdfToBytes返回結果為字節陣列,因此您可以決定下一步這些字節位於何處。

using IronPdf;

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

// Return the compressed PDF as bytes so it can go straight into an HTTP
// response, a database varbinary column, or a queue message with no temp file
byte[] compressedBytes = pdf.CompressPdfToBytes();

File.WriteAllBytes("compressed.pdf", compressedBytes);

如果您需要CompressPdfToStream並將其複製到您的目的地。 這適合於將輸出引道到HTTP回應正文、雲儲存上傳或任何基於流的工作流程。

using IronPdf;
using System.IO;

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

// Stream output so the compressed bytes can be piped straight to an HTTP
// response or cloud upload without first buffering the whole file as byte[]
using Stream compressedStream = pdf.CompressPdfToStream();

// CompressPdfToStream returns a read-only Stream, so copy it to the destination
using FileStream fileStream = File.Create("compressed.pdf");
compressedStream.CopyTo(fileStream);

有哪些Compression模式選項可用?

Compression模式作為參數,以決定工作的進行方式。 部署目標在允許磁碟存取方面存在差異,該模式讓您選擇合適的權衡:

模式磁碟存取圖像重新取樣輸出大小
自動 (預設)嘗試磁碟,回退到記憶體當磁碟可使用時最小的在允許時
快記憶體無ne無較大
高品質需要臨時目錄是最小的

FastMemory。 下例強制HighQuality獲得最小輸出,這需要在運行時獲得系統臨時目錄的寫入許可。

using IronPdf;

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

// HighQuality resamples images using the system temp directory, so it produces
// the smallest output but needs write access to that directory at runtime
byte[] compressedBytes = pdf.CompressPdfToBytes(50, false, CompressionMode.HighQuality);

File.WriteAllBytes("compressed.pdf", compressedBytes);

輸出

CompressPdfToStream現已在所有IronPDF平台上可用,包括Java、無de.js和Python。

結論

您現在擁有一個方法Compression模式下在記憶體中完成相同工作。 自然的下一步是將這些精簡的頁面轉換成縮圖,使用PDF光柵化。

常見問題

透過壓縮PDF文件大小能夠減少多少?

結果因內容而異。在顯示的例子中,圖像壓縮減少了一個文件39.24%,而結構樹的移除使一個表格繁重的PDF減少了67.90%。圖像繁重和表格繁重的文件能夠獲得最大的節省。

IronPDF如何在C#中壓縮PDF?

IronPDF透過單一方法處理壓縮 - CompressAndSaveAs。它使用可配置的JPEG品質(0–100)減小嵌入的圖像尺寸,並可以選擇性地設置removeStructureTree: true來剝除PDF內部的結構樹,這對於表格繁重的文件特別有效。

應該使用哪種JPEG壓縮品質水平在PDF中?

IronPDF支持1%至100%的JPEG壓縮品質。推薦的水平是:90%以上為高品質,80%-90%為中等品質,70%-80%為低品質。最佳設置取決於您在文件大小和視覺品質要求之間的平衡。

我可以只用一行程式碼壓縮PDF嗎?

可以,IronPDF允許在一行程式碼中壓縮PDF:PdfDocument.FromFile("input.pdf").CompressAndSaveAs("compressed.pdf", 40); 這將載入PDF,以40%的品質壓縮圖像,並儲存結果。

壓縮適用於由HTML建立的PDF嗎?

是的,IronPDF的壓縮適用於通過多種方法建立的PDF,包括HTML字串轉PDF、URL轉PDF和HTML文件轉換,以及現有的PDF文件。

哪些型別的內容最能從PDF壓縮中受益?

圖像通常消耗大部分PDF文件大小,使得圖像繁重的文件是壓縮的理想物件。此外,具有複雜表格結構的PDF從IronPDF的結構樹壓縮功能中受益。

我可以壓縮PDF而不將其儲存到磁碟嗎?

可以,IronPDF提供CompressPdfToBytes和CompressPdfToStream方法,它們分別將壓縮的PDF作為位元組陣列或流返回。兩者都接受一個可選的CompressionMode參數,提供自動、快速記憶體或高品質壓縮選項。

壓縮是否適用於其他語言而非C#?

是的,CompressPdfToBytes和CompressPdfToStream現已在所有IronPDF平台上可用,包括Java、Node.js和Python。

如何在C#中獲得對PDF壓縮的精細控制?

向CompressAndSaveAs傳遞一個AdvancedCompressionOptions物件來調整管道,包括透過TargetImageDpi進行圖像DPI降採樣、透過JpegQuality進行JPEG再編碼品質和zlib的CompressionLevel。原本的CompressAndSaveAs(outputPath, quality, removeStructureTree)重載仍然有效且產生與之前相同的輸出。

How can I achieve fine-grained control over PDF compression in IronPDF?

For fine-grained control, IronPDF allows you to pass an AdvancedCompressionOptions object to the CompressAndSaveAs method, letting you adjust JPEG quality, image DPI downsampling, and zlib compression levels.

How do I compress black-and-white scans in IronPDF?

Set BitonalMode to BitonalCompressionMode.Force on an AdvancedCompressionOptions object and pass it to CompressAndSaveAs. IronPDF thresholds each eligible image to 1-bit and encodes it as CCITT Group 4, keeping the result only when it is smaller. It is off by default and is intended for scanned text, faxes and line art rather than colour or photographic content.

Why does my scan look softer after setting BitonalMode to Force?

BitonalResolutionDpi is null by default, which falls back to TargetImageDpi, and TargetImageDpi defaults to 150. Setting only BitonalMode therefore downsamples a 300 DPI scan to 150 DPI before thresholding it. Set BitonalResolutionDpi explicitly, or set TargetImageDpi to null, to threshold at the original resolution.

What does BitonalThreshold do in IronPDF?

BitonalThreshold is the luminance cutoff from 1 to 255 that decides whether a pixel becomes black or white. Leave it null, the default, and IronPDF computes a threshold per image using Otsu's method, which handles scans that vary in exposure. A value of 0, or anything outside 1 to 255, falls back to the automatic threshold.

Can I use bitonal compression with CompressPdfToBytes or CompressPdfToStream?

No. Bitonal compression is only available through the CompressAndSaveAs overloads that accept an AdvancedCompressionOptions object. CompressPdfToBytes and CompressPdfToStream take a JPEG quality value instead, so the in-memory paths cannot produce CCITT Group 4 output.

Curtis Chau擁有Carleton大學的電腦科學學士學位,專精於前端開發,擁有Node.js、TypeScript、JavaScript和React的專業知識。Curtis熱衷於建立直觀且美觀的使用者介面,喜愛使用現代框架並建立結構良好、視覺吸引力的手冊。

閱讀更多

準備開始了嗎?

Nuget Downloads 21,916,531版本:2026.11剛剛發布