在生成pdf时获取异常“文档是开放的”

时间:2014-02-21 16:24:46

标签: vb.net pdf itextsharp tiff

我正在尝试使用iTextSharp库将tiff文件转换为pdf并获取此异常。 的 "document is open"

这是我的代码:

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()

任何人都可以说我错在哪里和哪里?

修改

当我尝试添加尺寸时:

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

enter image description here

1 个答案:

答案 0 :(得分:1)

正如我在my book about iText中解释的那样,在使用iText(夏普)时,您应该分5步创建PDF。创建writer是第2步,打开文档是第3步。您已经切换了这两个步骤,这就是导致错误的原因。

您需要将行document.Open()向下移动几行。在创建writer之后和创建cb实例之前。