The following code creates a .pdf
first which is okay and looks perfect, I have taken the rest of the code (which makes the compression) from another post on this site. The problem is that the compressed.pdf
file is 1kb and acrobat says the file is damaged and cannot be repaired. I have never made a pdf compressor before. Please, take a look at my code and if it is possible offer some corrections to make it working.
private void btnEndScan_Click(object sender, EventArgs e)
{
Document doc1 = new Document(PageSize.A4, 0, 0, 0, 0);
string filename = "Prot_" + label.Text + ".pdf";
try
{
PdfWriter.GetInstance(doc1, new FileStream("C:/" + filename, FileMode.Create));
doc1.Open();
for (int i = 0; i < imageArray.Length; i++)
{
iTextSharp.text.Image pic = iTextSharp.text.Image.GetInstance(imageArray[i], System.Drawing.Imaging.ImageFormat.Bmp);
pic.ScalePercent(36f);
doc1.Add(pic);
}
}
catch (Exception ex)
{
MessageBox.Show("Error creating pdf file" + ex);
}
finally
{
doc1.Close();
PdfReader reader = new PdfReader("C:/" + filename);
string filepath = "C:/compressed/" + filename;
using (MemoryStream ms = new MemoryStream())
{
PdfStamper stamper = new PdfStamper(reader, ms, PdfWriter.VERSION_1_5);
PdfWriter writer = stamper.Writer;
writer.CompressionLevel = PdfStream.BEST_COMPRESSION;
reader.RemoveFields();
reader.RemoveUnusedObjects();
stamper.Reader.RemoveUnusedObjects();
stamper.SetFullCompression();
stamper.Writer.SetFullCompression();
byte[] compressed = ms.ToArray();
reader.Close();
stamper.Close();
using (FileStream fs = File.Create("C:/compressed/compressed.pdf"))
{
fs.Write(compressed, 0, (int)compressed.Length);
fs.Close();
}
}
}
}