C# 使用windows窗体生成PDF

C# 使用windows窗体生成PDF,c#,winforms,pdf,pdf-generation,desktop-application,C#,Winforms,Pdf,Pdf Generation,Desktop Application,我想在桌面应用程序中使用windows窗体生成PDF。我有现成的pdf设计,我只想从数据库中为每个用户提供pdf空白部分的数据。(一种收据)。请引导我。我已经搜索过了,但大多数时候,asp.net中都有针对web应用程序的解决方案。我想在桌面应用程序中执行。这是我的代码,我可以从数据库中提取数据并以pdf格式打印。但主要的问题是,我已经设计了pdf,我想把数据完全放在同一个字段(即名称、金额、日期等) 使用系统; 使用System.Windows.Forms; 使用系统诊断; 使用PdfShar

我想在桌面应用程序中使用windows窗体生成PDF。我有现成的pdf设计,我只想从数据库中为每个用户提供pdf空白部分的数据。(一种收据)。请引导我。我已经搜索过了,但大多数时候,asp.net中都有针对web应用程序的解决方案。我想在桌面应用程序中执行。这是我的代码,我可以从数据库中提取数据并以pdf格式打印。但主要的问题是,我已经设计了pdf,我想把数据完全放在同一个字段(即名称、金额、日期等)

使用系统;
使用System.Windows.Forms;
使用系统诊断;
使用PdfSharp;
使用PdfSharp.Drawing;
使用PdfSharp.Pdf;
使用System.Data.SqlClient;
使用系统数据;
使用系统配置;
名称空间打印PDF
{
公共部分类Form1:Form
{
公共表格1()
{
初始化组件();
}
私有无效按钮1\u单击\u 1(对象发送者,事件参数e)
{
尝试
{
字符串connetionString=null;
SqlConnection连接;
SqlCommand命令;
SqlDataAdapter=新的SqlDataAdapter();
数据集ds=新数据集();
int i=0;
字符串sql=null;
int-yPoint=0;
字符串pubname=null;
字符串city=null;
字符串状态=null;
connetionString=“数据源=EEVO-SALMAN\\MY_PC;初始目录=;用户ID=s***;密码=*****”;
//var connectionString=ConfigurationManager.connectionString[“CharityManagement”]。connectionString;
sql=“从tblumaster中选择名称、名称、uid”;
连接=新的SqlConnection(connetionString);
connection.Open();
command=newsqlcommand(sql,connection);
adapter.SelectCommand=command;
适配器。填充(ds);
connection.Close();
PdfDocument pdf=新PdfDocument();
pdf.Info.Title=“数据库到pdf”;
PdfPage PdfPage=pdf.AddPage();
XGraphics graph=XGraphics.FromPdfPage(pdfPage);
XFont字体=新的XFont(“Verdana”,20,XFontStyle.Regular);
yPoint=yPoint+100;

对于(i=0;i而不是修改文档,请创建新文档并将页面从旧文档复制到新文档

示例代码可以在这里找到,


因为不建议使用“PdfSharp”库修改pdf。如果仍要编辑,可以使用需要许可证的“ISharp”库。

请创建新文档,并将页面从旧文档复制到新文档,而不是修改文档

示例代码可以在这里找到,


因为不建议使用“PdfSharp”库修改pdf。如果仍要编辑,可以使用需要许可证的“ISharp”库。

以下是我用来填充pdf表单的一些VB.Net代码。您需要一个pdf可填充表单,表单控件名与SQL记录字段名匹配

它调用一个例程Gen.GetDataTable(),该例程只生成一个典型的DataTable。您可以重新编码以接受预构建的DataTable作为参数。只处理最上面的一行。可以修改代码以使用DataRow(.Table.Columns用于列引用)或DataReader

   Public Function FillPDFFormSQL(pdfMasterPath As String, pdfFinalPath As String, SQL As String, Optional FlattenForm As Boolean = True, Optional PrintPDF As Boolean = False, Optional PrinterName As String = "", Optional AllowMissingFields As Boolean = False) As Boolean
    ' case matters SQL <-> PDF Form Field Names
    Dim pdfFormFields As AcroFields
    Dim pdfReader As PdfReader
    Dim pdfStamper As PdfStamper
    Dim s As String = ""
    Try
        If pdfFinalPath = "" Then pdfFinalPath = pdfMasterPath.Replace(".pdf", "_Out.pdf")
        Dim newFile As String = pdfFinalPath
        pdfReader = New PdfReader(pdfMasterPath)
        pdfStamper = New PdfStamper(pdfReader, New FileStream(newFile, FileMode.Create))
        pdfReader.Close()
        pdfFormFields = pdfStamper.AcroFields

        Dim dt As DataTable = Gen.GetDataTable(SQL)
        For i As Integer = 0 To dt.Columns.Count - 1
            s = dt.Columns(i).ColumnName
            If AllowMissingFields Then
                If pdfFormFields.Fields.ContainsKey(s) Then
                    pdfFormFields.SetField(s, dt.Rows(0)(i).ToString.Trim)
                Else
                    Debug.WriteLine($"Missing PDF Field: {s}")
                End If
            Else
                pdfFormFields.SetField(s, dt.Rows(0)(i).ToString.Trim)
            End If

        Next

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

        pdfStamper.Close()

        If Not newFile.Contains("""") Then newFile = """" & newFile & """"
        If Not PrintPDF Then
            Process.Start(newFile)
        Else
            Dim sPDFProgramPath As String = INI.GetValue("OISForms", "PDFProgramPath", "C:\Program Files (x86)\Foxit Software\Foxit PhantomPDF\FoxitPhantomPDF.exe")
            If Not IO.File.Exists(sPDFProgramPath) Then MsgBox("PDF EXE not found:" & vbNewLine & sPDFProgramPath) : Exit Function
            If PrinterName.Length > 0 Then
                Process.Start(sPDFProgramPath, "/t " & newFile & " " & PrinterName)
            Else
                Process.Start(sPDFProgramPath, "/p " & newFile)
            End If
        End If
        Return True
    Catch ex As Exception
        MsgBox(ex.Message)
        Return False
    Finally
        pdfStamper = Nothing
        pdfReader = Nothing
    End Try
End Function
公共函数fillPdformsql(pdfMasterPath为字符串,PdfInalPath为字符串,SQL为字符串,可选FlattForm为Boolean=True,可选PrintPDF为Boolean=False,可选PrinterName为String=,可选AllowMissingFields为Boolean=False)为布尔值
'大小写事务SQL PDF表单字段名称
将pdfFormFields变暗为AcroFields
将pdfReader调暗为pdfReader
将pdfStamper调暗为pdfStamper
Dim s As String=“”
尝试
如果pdfFinalPath=”“,则pdfFinalPath=pdfMasterPath.Replace(“.pdf”,“Out.pdf”)
Dim newFile As String=pdfFinalPath
pdfReader=新pdfReader(pdfMasterPath)
pdfStamper=newpdfstamper(pdfReader,newfilestream(newFile,FileMode.Create))
pdfReader.Close()
pdfFormFields=pdfStamper.AcroFields
Dim dt As DataTable=Gen.GetDataTable(SQL)
对于i,整数=0到dt.Columns.Count-1
s=dt.列(i).列名称
如果AllowMissingFields,则
如果pdfFormFields.Fields.ContainsKey,则
pdfFormFields.SetField(s,dt.Rows(0)(i).ToString.Trim)
其他的
Debug.WriteLine($“缺少PDF字段:{s}”)
如果结束
其他的
pdfFormFields.SetField(s,dt.Rows(0)(i).ToString.Trim)
如果结束
下一个
'展平表单以删除编辑选项
'将其设置为false可使表单保持打开状态,以便进行后续手动编辑
如果My.Computer.Keyboard.CtrlKeyDown,则
pdfStamper.formflatting=False
其他的
pdfStamper.formflatting=flattform
如果结束
pdfStamper.Close()
如果不是newFile.Contains(“”),则为newFile=“”&newFile&“”
如果不打印PDF,则
Process.Start(新文件)
其他的
Dim sPDFProgramPath格式为String=INI.GetValue(“OISForms”、“PDFProgramPath”、“C:\Program Files(x86)\Foxit Software\Foxit PhantomPDF\FoxitPhantomPDF.exe”)
如果不存在IO.File.Exists(sPDFProgramPath),则MsgBox(“未找到PDF EXE:”&vbNewLine&sPDFProgramPath):退出函数
如果PrinterName.Length>0,则
Process.Start(sPDFProgramPath,“/t”&newFile&“&PrinterName)
其他的
Process.Start(sPDFProgramPath,“/p”&newFile)
如果结束
如果结束
返回真值
特例
MsgBox(例如消息)
返回错误
最后
pdfStamper
   Public Function FillPDFFormSQL(pdfMasterPath As String, pdfFinalPath As String, SQL As String, Optional FlattenForm As Boolean = True, Optional PrintPDF As Boolean = False, Optional PrinterName As String = "", Optional AllowMissingFields As Boolean = False) As Boolean
    ' case matters SQL <-> PDF Form Field Names
    Dim pdfFormFields As AcroFields
    Dim pdfReader As PdfReader
    Dim pdfStamper As PdfStamper
    Dim s As String = ""
    Try
        If pdfFinalPath = "" Then pdfFinalPath = pdfMasterPath.Replace(".pdf", "_Out.pdf")
        Dim newFile As String = pdfFinalPath
        pdfReader = New PdfReader(pdfMasterPath)
        pdfStamper = New PdfStamper(pdfReader, New FileStream(newFile, FileMode.Create))
        pdfReader.Close()
        pdfFormFields = pdfStamper.AcroFields

        Dim dt As DataTable = Gen.GetDataTable(SQL)
        For i As Integer = 0 To dt.Columns.Count - 1
            s = dt.Columns(i).ColumnName
            If AllowMissingFields Then
                If pdfFormFields.Fields.ContainsKey(s) Then
                    pdfFormFields.SetField(s, dt.Rows(0)(i).ToString.Trim)
                Else
                    Debug.WriteLine($"Missing PDF Field: {s}")
                End If
            Else
                pdfFormFields.SetField(s, dt.Rows(0)(i).ToString.Trim)
            End If

        Next

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

        pdfStamper.Close()

        If Not newFile.Contains("""") Then newFile = """" & newFile & """"
        If Not PrintPDF Then
            Process.Start(newFile)
        Else
            Dim sPDFProgramPath As String = INI.GetValue("OISForms", "PDFProgramPath", "C:\Program Files (x86)\Foxit Software\Foxit PhantomPDF\FoxitPhantomPDF.exe")
            If Not IO.File.Exists(sPDFProgramPath) Then MsgBox("PDF EXE not found:" & vbNewLine & sPDFProgramPath) : Exit Function
            If PrinterName.Length > 0 Then
                Process.Start(sPDFProgramPath, "/t " & newFile & " " & PrinterName)
            Else
                Process.Start(sPDFProgramPath, "/p " & newFile)
            End If
        End If
        Return True
    Catch ex As Exception
        MsgBox(ex.Message)
        Return False
    Finally
        pdfStamper = Nothing
        pdfReader = Nothing
    End Try
End Function