0

我正在使用 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(最佳)。

如何将压缩级别设置为最佳并使其坚持下去?

4

1 回答 1

1

如果您将4.1.6 代码当前代码进行比较,您会发现它们正在对内部compressionLevel变量而不是属性的value.

4.1.6

public int CompressionLevel {
    set {
        if (compressionLevel < PdfStream.NO_COMPRESSION || compressionLevel > PdfStream.BEST_COMPRESSION)
            compressionLevel = PdfStream.DEFAULT_COMPRESSION;
        else
            compressionLevel = value;
    }
    get {
        return compressionLevel;
    }
}

5.4.0

public int CompressionLevel {
    set {
        if (value < PdfStream.NO_COMPRESSION || value > PdfStream.BEST_COMPRESSION)
            compressionLevel = PdfStream.DEFAULT_COMPRESSION;
        else
            compressionLevel = value;
    }
    get {
        return compressionLevel;
    }
}

4.x 系列不再受支持,但您可以自行下载源代码并进行更改。

于 2013-04-10T17:29:12.987 回答