In iTextSharp, you can use the CompressionLevel property of the PdfWriter class to set the compression level of stream objects that are written to the FileStream. You can specify one compression option from the table below.
Percentage reduced (in file size)
|Compression level 0 (no compression)||0%|
|Compression level 9 ( best compression)||72.59%|
The compression level 0, default compression, and compression level 9 can be specified by using constant values defined in the PdfStream class: NO_COMPRESSION (0), DEFAULT_COMPRESSION (-1) , and BEST_COMPRESSION (9). You will use the SetFullCompression method of the PdfWriter class to use the full compression option.
var doc = new Document();
PdfWriter writer=PdfWriter.GetInstance(doc, new FileStream(path + "pdfdoc.pdf", FileMode.Create));
writer.CompressionLevel = PdfStream.DEFAULT_COMPRESSION;
Image img = Image.GetInstance("D:/baby.jpg");
doc.Add(new Paragraph(0,"Hello World",new Font(Font.FontFamily.COURIER,50,Font.BOLD)));
The following code helps you compress an existing PDF document. You can use the GetPageContent method to get the content stream of a page, and the SetPageContent method to put it back. By doing this, iTextSharp thinks the stream has changed, and it will use the compression level that was defined for writer object of the PdfStamper.
PdfReader reader = new PdfReader("D:/pdfcontentadded.pdf");
PdfStamper stamper = new PdfStamper(reader, new FileStream("d:/pdfdoccompressed.pdf",FileMode.Create), PdfWriter.VERSION_1_5);
int pageNum = reader.NumberOfPages;
for (int i = 1; i <= pageNum; i++)
This is the Pdf file before being compressed.
This is the Pdf file after being compressed.
To decompress a PDF file, you will set the compress level of the writer object of PdfStamper to NO_COMPRESSION or zero.
PdfReader reader = new PdfReader("D:/pdfcompressed.pdf");
PdfStamper stamper = new PdfStamper(reader, new FileStream("d:/pdfdocdecompressed.pdf", FileMode.Create), PdfWriter.VERSION_1_5);
stamper.Writer.CompressionLevel = 0;
This website intents to provide free and high quality tutorials, examples, exercises and solutions, questions and answers of programming and scripting languages: