首页 文章

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

提问于
浏览
0

我需要开发一个从Excel工作表数据生成pdf文件的Windows窗体应用程序 . 应该使用xml文件将excel工作表中的数据映射到pdf中的控件 . 必须为每行生成一个pdf文件 . 单击按钮即可获得Excel表单 . 这样做了怎么办?

1 回答

  • 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
    

相关问题