我是使用iTextSharp进行编程的新手。我有一个用PDF文件写的应用程序。文件以文字书写,而不是以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
'WriteData的代码
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