Search code examples
c#pdfitextpdf-generation

Add new page to PDF document using iTextSharp - C#


I want to generate a PDF file with multiple scanned pages using scanner. I used iTextSharp to achieve this:

bool continueScanning = true;

ScanDirectory = Environment.ExpandEnvironmentVariables("%USERPROFILE%/AppData/Local/Temp") + @"\docs\";
System.IO.Directory.CreateDirectory(ScanDirectory);
string pdfPath = Path.Combine(ScanDirectory, "doc" + DateTime.Now.ToString("hhmmss") + ".pdf");
Document document = new Document(PageSize.A4);
PdfWriter writer = PdfWriter.GetInstance(document, new FileStream(pdfPath, FileMode.Create));
while (continueScanning)
{               
        var dialog = new WIA.CommonDialog();
        ImageFile image = dialog.ShowAcquireImage(AlwaysSelectDevice: true);    
        MemoryStream MStream = null;                       
        byte[] ImgBytes = (byte[])image.FileData.get_BinaryData();
        MStream = new MemoryStream(ImgBytes);
        Bitmap Bmp = new Bitmap(MStream);
        document.Open();
        document.NewPage();    
        iTextSharp.text.Image pdfImage = iTextSharp.text.Image.GetInstance(Bmp, System.Drawing.Imaging.ImageFormat.Jpeg);    
        pdfImage.ScaleToFit(document.PageSize);
        pdfImage.SetAbsolutePosition(0, 0);
        pdfImage.Alignment = iTextSharp.text.Image.ALIGN_TOP; 
        document.Add(pdfImage);    
        continueScanning = (MessageBox.Show("Continue scanning?", "Scan", MessageBoxButtons.YesNo) == DialogResult.Yes);                                  
}
document.Close();
writer.Close();

This code generates a PDF file with just one page which is the last scanned page, but the size of the file in the disk is bigger than the size when i just only scan this page alone. So how to add the new scanned page in a new page?


Solution

  • Move the document.Open(); in front of your loop!

    You have

    Document document = new Document(PageSize.A4);
    PdfWriter writer = PdfWriter.GetInstance(document, new FileStream(pdfPath, FileMode.Create));
    while (continueScanning)
    {
       ...
       document.Open();
       ...
    }
    document.Close();
    writer.Close();
    

    Change it to

    Document document = new Document(PageSize.A4);
    PdfWriter writer = PdfWriter.GetInstance(document, new FileStream(pdfPath, FileMode.Create));
    document.Open();
    while (continueScanning)
    {
       ...
       ...
    }
    document.Close();