ITextSharp returning same size pdf when I'm trying to compress pdf file with different levels

谁都会走 提交于 2019-11-29 11:42:49

You have a couple of questions and I'll try my best to answer them.

PdfStamper is a helper class that ultimately uses another class called PdfStamperImp to do most of the work. PdfStamperImp is derived from PdfWriter and when you use stamper.Writer you are actually getting back this implementation class. Many of the properties on PdfStamper also pass directly through to the implementation class. So these two calls actually do the same thing.

stamper.SetFullCompression();
stamper.Writer.SetFullCompression();

Another point of confusion is that SetFullCompression and the CompressionLevel aren't actually related at all. "Full compression" represents a feature that was added in PDF 1.5 called "Object Streams" that allows grouping PDF objects together to potentially allow for greater compression. There's actually no requirement that what we think of as "compression" actually occurs but in reality I think it would always happen. (Possibly a super simple document might get larger with this enabled, not sure and don't feel like testing.)

The CompressionLevel is actually what you normally think of as compression, a number from 0 to 9 or -1 to mean default (which currently equals six I think). This property is actually part of the PdfStream class which many classes ultimately derive from. This setting doesn't "trickle down", however. Since you are importing a stream from another location via GetPageContent() and SetPageContent() that specific stream has its own compression settings unrelated to the Writer's compression settings. There's actually a third parameter that you can pass to SetPageContent() to set your specific compression level if you want.

reader.SetPageContent(1, reader.GetPageContent(1), PdfStream.BEST_COMPRESSION);
Vikas Chauhan

I am using the below code and it is not getting compressed. Output file is also having the same size as that of input size.

PdfReader reader = new PdfReader("/tmp/before.pdf");
PdfStamper stamper = new PdfStamper(reader, new FileOutputStream("/tmp/temp.pdf"), PdfWriter.VERSION_1_5);

stamper.getWriter().setCompressionLevel(9);
int total = reader.getNumberOfPages() + 1;
for(int i=1;i<total;i++){
    reader.setPageContent(i, reader.getPageContent(i), PdfStream.BEST_COMPRESSION);
}

stamper.setFullCompression();
stamper.close();
reader.close();
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!