0

我是使用 iTextSharp 编程的新手。我有一个在 PDF 文件中写入的应用程序。文件是用word写的,然后保存在PDF中(有2页)。我的问题是,当我想在 PDF 上书写时,我看到了已写入的数据,但输出的 PDF 已损坏。我不明白为什么 PDF 会损坏?

    Public Sub WriteForm(TemplateFilePath As String, NewFilePath As String, data As FormData)
    'input output files
    Dim oldFile As String = TemplateFilePath
    Dim newFile As String = NewFilePath

    'if file already exists then delete it
    If System.IO.File.Exists(newFile) Then
        System.IO.File.Delete(newFile)
    End If

    ' open the reader
    Dim reader As New PdfReader(oldFile)
    Dim size As Rectangle = reader.GetPageSizeWithRotation(1)
    Dim document As New Document(size)

    ' open the writer
    Dim fs As New FileStream(newFile, FileMode.Create, FileAccess.Write)
    Dim writer As PdfWriter = PdfWriter.GetInstance(document, fs)
    document.Open()

    'write data to first page
    Me.WriteData(reader, writer, data)

    'write second page
    Me.AppendCopiedPage(document, writer, reader, 2)

    ' close the streams 
    document.Close()
    fs.Close()
    writer.Close()
    reader.Close()

End Sub

'写数据的代码

    Private Sub WriteData(reader As PdfReader, writer As PdfWriter, data As FormData)`
    Dim cb As PdfContentByte = writer.DirectContent
    Dim bf As BaseFont = BaseFont.CreateFont(BaseFont.TIMES_ROMAN, BaseFont.CP1250, BaseFont.EMBEDDED)
    cb.SetColorFill(BaseColor.BLACK)
    cb.SetFontAndSize(bf, 10)

    ' create the first page and add it to the pdf
    Dim page1 As PdfImportedPage = writer.GetImportedPage(reader, 1)
    cb.AddTemplate(page1, 0, 0)
    Me.WriteText(cb, data.SID, 110, 653)
           ...
End Sub
4

0 回答 0