PDFsharp Beta 1.50 PdfTextField,Null异常错误,但仍然有效?

时间:2016-07-12 15:13:35

标签: vb.net pdfsharp

我正在使用PDFsharp 1.50 beta 3b。我主要使用它来访问使用更新的PDF文档的能力。我没有使用任何新功能。向下转换我的PDF文档正在杀死它们,我不知道为什么。那说;

Private Sub Print_Form()

    Dim filename As String = ""

    If IO.File.Exists(String.Format("{0}Template\Form.pdf", AppDomain.CurrentDomain.BaseDirectory)) Then
        filename = String.Format("{0}Template\Form.pdf", AppDomain.CurrentDomain.BaseDirectory)
    Else
        MessageBox.Show("You're missing the Templates directory. If you don't know what this means, tell your IT Administrator.", "Missing Files")
        Exit Sub
    End If

    Dim PDFDocument As PdfSharp.Pdf.PdfDocument = PdfSharp.Pdf.IO.PdfReader.Open(filename, PdfSharp.Pdf.IO.PdfDocumentOpenMode.Modify)
    Dim form As PdfSharp.Pdf.AcroForms.PdfAcroForm = PDFDocument.AcroForm

    If form.Elements.ContainsKey("/NeedAppearances") Then
        form.Elements("/NeedAppearances") = New PdfSharp.Pdf.PdfBoolean(True)
    Else
        form.Elements.Add("/NeedAppearances", New PdfSharp.Pdf.PdfBoolean(True))
    End If

    Try
        'the subsequent line causes the exception to be thrown
        CType(form.Fields("StringTest"), PdfSharp.Pdf.AcroForms.PdfTextField).Text = "Test"
    Catch ex As Exception
        Clipboard.SetText(ex.StackTrace)
    End Try

    CType(form.Fields("CheckBoxTest"), PdfSharp.Pdf.AcroForms.PdfCheckBoxField).Checked = True

    PDFDocument.Save("temp.pdf")
    Dim p As New System.Diagnostics.ProcessStartInfo()
    p.Verb = "print"
    p.WindowStyle = ProcessWindowStyle.Hidden
    p.FileName = "temp.pdf"
    p.UseShellExecute = True
    System.Diagnostics.Process.Start(p)

End Sub

这会产生错误;

An unhandled exception of type 'System.NullReferenceException' occurred in PdfSharp.dll

Additional information: Object reference not set to an instance of an object.

at PdfSharp.Pdf.AcroForms.PdfTextField.RenderAppearance()
at PdfSharp.Pdf.AcroForms.PdfTextField.set_Text(String value)
at WOTC_FE.frmInterview.Print_ICF() in d:\Programming\FE\FE\Applications\frmInterview.vb:line 2886

现在是什么让这个奇怪,为什么我要问的是这仍然适用于try / catch块。它将填充该字段,文件在PDF文件中具有正确的文本。我只是想知道为什么会抛出这个异常?

1 个答案:

答案 0 :(得分:3)

我想出了这个问题。新的PDFSharp为其控件使用不同的访问方法。

首先,我们的声明;

Dim PDFDocument As PdfSharp.Pdf.PdfDocument = PdfSharp.Pdf.IO.PdfReader.Open(filename, PdfSharp.Pdf.IO.PdfDocumentOpenMode.Modify)
Dim form As PdfSharp.Pdf.AcroForms.PdfAcroForm = PDFDocument.AcroForm

对于复选框;

CType(form.Fields(<Field Name>), PdfSharp.Pdf.AcroForms.PdfCheckBoxField).Checked = True

对于字符串;

PDFDocument.AcroForm.Fields("Field Name").Value = New PdfSharp.Pdf.PdfString("Input Text")

这样做是有效的,不需要try / catch块,也不会抛出错误。