Question

I'm trying to convert tiff file to pdf using iTextSharp library and getting this exception. "document is open"

Here is my code:

Dim saveFileDialog1 As New SaveFileDialog()
saveFileDialog1.Filter = "Pdf files (*.pdf)|*.pdf|All files (*.*)|*.*"
saveFileDialog1.FilterIndex = 2
saveFileDialog1.RestoreDirectory = True

    If saveFileDialog1.ShowDialog() = DialogResult.OK Then
     ' creation of the document with a certain size and certain margins  
        Dim document As New iTextSharp.text.Document(iTextSharp.text.PageSize.A4, 0, 0, 0, 0)


        ' load the tiff image and count the total pages  
        Dim bm As New System.Drawing.Bitmap(OpenFileDialog1.FileName)
        Dim total As Integer = bm.GetFrameCount(System.Drawing.Imaging.FrameDimension.Page)

        document.Open()
        ' creation of the different writers  
        Dim writer As iTextSharp.text.pdf.PdfWriter = iTextSharp.text.pdf.PdfWriter.GetInstance(document, New System.IO.FileStream(saveFileDialog1.FileName, System.IO.FileMode.Create))

        Dim cb As iTextSharp.text.pdf.PdfContentByte = writer.DirectContent
        For k As Integer = 0 To total - 1
            bm.SelectActiveFrame(System.Drawing.Imaging.FrameDimension.Page, k)
            Dim img As iTextSharp.text.Image = iTextSharp.text.Image.GetInstance(bm, System.Drawing.Imaging.ImageFormat.Bmp)
            ' scale the image to fit in the page  
            img.ScalePercent(72.0F / img.DpiX * 100)
            img.SetAbsolutePosition(0, 0)
            cb.AddImage(img)
            document.NewPage()
        Next k
        document.Close()

Can anyone say me what and where am I going wrong ?

EDIT:

When I tried to add the dimensions:

img.ScaleToFit(595, 842)
img.SetAbsolutePosition(0, 0)

enter image description here

Was it helpful?

Solution

As I explain in my book about iText, you should create a PDF in 5 steps when using iText(Sharp). Creating the writer is step 2 and opening the document is step 3. You have switched these two steps and this is what causes the error.

You need to move the line document.Open() down a couple of lines. After where you create the writer and before creating the cb instance.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top