public static void CompressPdf(string inputFilePath, string outputFilePath)
{
// Load the input PDF document
using (var inputStream = File.OpenRead(inputFilePath))
{
var pdfDocument = PdfReader.Open(inputStream, PdfDocumentOpenMode.Import);
// Create a new, empty output PDF document
var outputDocument = new PdfDocument();
// Compress each page of the input document and add it to the output document
foreach (var page in pdfDocument.Pages)
{
using (var stream = new MemoryStream())
{
// Save the page to a stream
page.Save(stream, false);
// Compress the stream using DotNetZip
stream.Position = 0;
var compressedStream = new MemoryStream();
using (var zip = new ZipFile())
{
zip.AddEntry("Page" + page.PageNumber.ToString(), stream);
zip.Save(compressedStream);
}
// Create a new PDF page from the compressed stream and add it to the output document
compressedStream.Position = 0;
var compressedPage = PdfReader.Open(compressedStream, PdfDocumentOpenMode.Import).Pages[0];
outputDocument.AddPage(compressedPage);
}
}
// Save the compressed PDF document to the output file
using (var outputStream = File.Create(outputFilePath))
{
outputDocument.Save(outputStream);
}
}
}
1条答案
按热度按时间lmvvr0a81#
GzipStream仅用于压缩和解压缩GZIP格式的文件。
如果你想压缩你的pdf文档,你可以使用PdfSharp和DotnetZip包,这是免费的和开源的。
示例: