为什么iTextSharp PdfWriter.CompressionLevel setter不改变值?

时间:2013-04-09 21:20:27

标签: c# pdf itextsharp

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

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

1 个答案:

答案 0 :(得分:1)

如果您将4.1.6 codecurrent code进行比较,您会发现他们正在对内部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系列,但您可以自己download the source进行更改。