I’m working in a console application targeting .NET v8. I’m using PDFsharp nuget package for PDF file generation. I’m using below code to compress a PDF file of 75 KB. The PDF file mostly contains text.
using PdfSharp.Pdf;
using PdfSharp.Pdf.IO;
using (var stream = new MemoryStream(File.ReadAllBytes("D:\test.pdf")) { Position = 0 })
using (var source = PdfReader.Open(stream, PdfDocumentOpenMode.Import))
using (var document = new PdfDocument())
{
var options = document.Options;
options.FlateEncodeMode = PdfFlateEncodeMode.BestCompression;
options.UseFlateDecoderForJpegImages = PdfUseFlateDecoderForJpegImages.Automatic;
options.CompressContentStreams = true;
options.NoCompression = false;
options.EnableCcittCompressionForBilevelImages = true;
foreach (var page in source.Pages)
{
document.AddPage(page);
}
document.Save("D:\testout.pdf");
}
The output file that I get is of 73 KB. So I get reduction of 2 KB only. Is there any way to reduce its size significantly using compression?
2
Enabling PdfFlateEncodeMode.BestCompression
will typically reduce the size by about 2% to 5%.
With the default settings, contents are already “zipped”. Best compression is more effective, but slower.
PDFsharp does not yet support object XREF streams, so other libraries may be able to create even smaller files without losses.