我正在使用 iTextSharp (LGPL / MPL) 4.1.6 从现有 PDF 流中获取页面范围,对其进行压缩并将其保存到新文件中:
private static void CreateFile(Stream stream, string filename, int first, int last)
{
RandomAccessFileOrArray raf = new RandomAccessFileOrArray(stream);
PdfReader reader = new PdfReader(raf, null);
reader.SelectPages(string.Format("{0}-{1}", first, last));
char version = reader.PdfVersion; // == '4'
using (FileStream fs = new FileStream(filename, FileMode.Create))
{
PdfStamper stamper = new PdfStamper(reader, fs, PdfWriter.VERSION_1_5);
PdfWriter writer = stamper.Writer;
writer.SetPdfVersion(PdfWriter.PDF_VERSION_1_5);
writer.CompressionLevel = PdfStream.BEST_COMPRESSION;
// this will always be true - why?
if (PdfStream.DEFAULT_COMPRESSION == writer.CompressionLevel)
{
var help = "what am I doing wrong?";
}
for (int i = 1; i <= reader.NumberOfPages; i++)
{
reader.SetPageContent(i, reader.GetPageContent(i));
}
stamper.SetFullCompression();
stamper.Close();
}
reader.Close();
raf.Close();
}
压缩线是新的。但我注意到添加压缩代码之前和之后的文件大小几乎没有差异。在调试模式下单步执行时,我看到 CompressionLevel 始终为 -1(默认),即使我明确将其设置为 9(最佳)。
如何将压缩级别设置为最佳并使其坚持下去?