是的,iText 是一個用于處理 PDF 文件的庫,它提供了多種方法來壓縮 PDF 文件。在 C# 中,你可以使用 iTextSharp 或 iText 7(iText 的最新版本)來實現 PDF 壓縮。
以下是一個使用 iTextSharp 壓縮 PDF 文件的示例代碼:
using System;
using System.IO;
using iTextSharp.text;
using iTextSharp.text.pdf;
namespace PdfCompression
{
class Program
{
static void Main(string[] args)
{
string inputPath = "input.pdf";
string outputPath = "output.pdf";
using (FileStream fs = new FileStream(inputPath, FileMode.Open))
{
using (PdfReader reader = new PdfReader(fs))
{
using (FileStream fos = new FileStream(outputPath, FileMode.Create))
{
using (PdfStamper stamper = new PdfStamper(reader, fos))
{
stamper.SetFullCompressionMode();
stamper.CompressContent();
}
}
}
}
}
}
}
這個示例代碼首先打開輸入 PDF 文件,然后創建一個新的 PDFStamper 對象,并設置壓縮模式為 FullCompressionMode
。接著調用 CompressContent()
方法來壓縮 PDF 文件的內容。最后將壓縮后的 PDF 文件保存到輸出路徑。
請注意,iTextSharp 是一個較舊的庫,而 iText 7 是 iText 的最新版本,提供了更多的功能和更好的性能。如果你正在使用較新的項目,建議使用 iText 7。以下是使用 iText 7 壓縮 PDF 文件的示例代碼:
using System;
using System.IO;
using iText.Kernel.Pdf;
using iText.Kernel.Pdf.Compression;
namespace PdfCompression
{
class Program
{
static void Main(string[] args)
{
string inputPath = "input.pdf";
string outputPath = "output.pdf";
using (FileStream fs = new FileStream(inputPath, FileMode.Open))
{
using (PdfReader reader = new PdfReader(fs))
{
using (FileStream fos = new FileStream(outputPath, FileMode.Create))
{
using (PdfWriter writer = new PdfWriter(fos, new WriterProperties()
{
CompressionLevel = CompressionConstants.FLATE_COMPRESSION_LEVEL_9
}))
{
reader.CopyTo(writer);
}
}
}
}
}
}
}
在這個示例代碼中,我們使用了 iText 7 的 PdfWriter
類,并通過 WriterProperties
設置壓縮級別為 FLATE_COMPRESSION_LEVEL_9
,這是最高的壓縮級別。然后使用 CopyTo()
方法將輸入 PDF 文件復制到輸出文件,并進行壓縮。