使用xml和Windows窗体从Excel工作表生成pdf文件

时间:2016-06-06 08:50:16

标签: c# xml excel winforms pdf-generation

我需要开发一个从Excel工作表数据生成pdf文件的Windows窗体应用程序。应该使用xml文件将excel工作表中的数据映射到pdf中的控件。必须为每个文件生成一个pdf文件点击一个按钮就可以看到excel表格的一行。这怎么办?

1 个答案:

答案 0 :(得分:0)

这是一个库例程,它使用字段名称和值的字典来填充PDF模板。对于您的情况,您需要从Excel行数据创建字典,将数据正确映射到模板中的字段名称(区分大小写)。你不需要填写"缺少"字段除非您要插入默认值。

项目需要引用itextsharp。需要将itextsharp.dll复制到输出目录。

Imports iTextSharp.text.pdf
Import System.IO
Public Function FillPDFForm(PDF_MasterPath As String, Flds As Dictionary(Of String, String), Optional PDF_FinalPath As String = "", Optional FlattenForm As Boolean = True) As Boolean
    ' case matters: Dictionary Keys == PDF Form Field Names
    Dim pdfFormFields As AcroFields
    Dim pdfReader As PdfReader
    Dim pdfStamper As PdfStamper

    Try
        If PDF_FinalPath = "" Then PDF_FinalPath = PDF_MasterPath.Replace(".pdf", "_Out.pdf")
        Dim newFile As String = PDF_FinalPath

        pdfReader = New PdfReader(PDF_MasterPath)
        pdfStamper = New PdfStamper(pdfReader, New FileStream(newFile, FileMode.Create))
        pdfReader.Close()
        pdfFormFields = pdfStamper.AcroFields

        For Each sKVP As KeyValuePair(Of String, String) In Flds
            pdfFormFields.SetField(sKVP.Key, sKVP.Value)
        Next

        ' flatten the form to remove editing options?
        ' set it to false to leave the form open to subsequent manual edits
        If My.Computer.Keyboard.CtrlKeyDown Then
            ' leave in editable state
            pdfStamper.FormFlattening = False
        Else
            pdfStamper.FormFlattening = FlattenForm
        End If

        pdfStamper.Close()

        Process.Start(newFile)
        Return True
    Catch ex As Exception
        MsgBox(ex.Message)
        Return False
    Finally
        pdfStamper = Nothing
        pdfReader = Nothing
    End Try
End Function

这里有一些代码用于从PDF表单中获取表单字段名称:

Private Function PDFFieldNames(pdfPath As String) As String
    Try
        Dim s As String = ""

        ' create a new PDF reader based on the PDF template document
        Dim pdfReader As PdfReader = New PdfReader(pdfPath)

        Dim fields As IDictionary(Of String, iTextSharp.text.pdf.AcroFields.Item) = pdfReader.AcroFields.Fields
        For Each key As String In fields.Keys
            's = "pdfFormFields.SetField(""{fname}"", Row!{fname})".Replace("{fname}", key)
            s &= key & "|"
        Next
        pdfReader.Close()
        Return s
    Catch ex As Exception
        MsgBox(ex.Message)
        Return ""
    End Try
End Function