【问题标题】:Generate PDF in using windows form使用 windows 窗体生成 PDF
【发布时间】:2017-11-22 04:21:22
【问题描述】:

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

using System;
using System.Windows.Forms;
using System.Diagnostics;
using PdfSharp;
using PdfSharp.Drawing;
using PdfSharp.Pdf;
using System.Data.SqlClient;
using System.Data;
using System.Configuration;


namespace printPDF
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click_1(object sender, EventArgs e)
        {
            try
            {
                string connetionString = null;
                SqlConnection connection ;
                SqlCommand command ;
                SqlDataAdapter adapter = new SqlDataAdapter();
                DataSet ds = new DataSet();
                int i = 0;
                string sql = null;
                int yPoint = 0;
                string pubname = null;
                string city = null;
                string state = null;

                connetionString = "Data Source=EEVO-SALMAN\\MY_PC;Initial Catalog=;User ID=s***;Password=******";
              //  var connectionString = ConfigurationManager.ConnectionStrings["CharityManagement"].ConnectionString;
                sql = "select NAME,NAME,uid from tblumaster";
                connection = new SqlConnection(connetionString);
                connection.Open();
                command = new SqlCommand(sql, connection);
                adapter.SelectCommand = command;
                adapter.Fill(ds);
                connection.Close();

                PdfDocument pdf = new PdfDocument();
                pdf.Info.Title = "Database to PDF";
                PdfPage pdfPage = pdf.AddPage();
                XGraphics graph = XGraphics.FromPdfPage(pdfPage);
                XFont font = new XFont("Verdana", 20, XFontStyle.Regular );

                yPoint = yPoint + 100;

                for (i = 0; i <=ds.Tables[0].Rows.Count-1; i++)
                {
                    pubname = ds.Tables[0].Rows[i].ItemArray[0].ToString ();
                    city = ds.Tables[0].Rows[i].ItemArray[1].ToString();
                    state = ds.Tables[0].Rows[i].ItemArray[2].ToString();

                    graph.DrawString(pubname, font, XBrushes.Black, new XRect(10, yPoint, pdfPage.Width.Point, pdfPage.Height.Point), XStringFormats.TopLeft);

                    graph.DrawString(city, font, XBrushes.Black, new XRect(200, yPoint, pdfPage.Width.Point, pdfPage.Height.Point), XStringFormats.TopLeft);

                    graph.DrawString(state, font, XBrushes.Black, new XRect(400, yPoint, pdfPage.Width.Point, pdfPage.Height.Point), XStringFormats.TopLeft);

                    yPoint = yPoint + 40;
                }


                string pdfFilename = "dbtopdf.pdf";
                pdf.Save(pdfFilename);
                Process.Start(pdfFilename);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
        }
    }
}

【问题讨论】:

  • stackoverflow.com/questions/7601145/c-winform-creating-pdf 如果您需要特定格式的 pdf,请添加更多说明。
  • 感谢回复 我知道如何创建 pdf,但我想将 SQL 服务器(数据库)中的数据输入 pdf 的特定字段
  • 如果您可以分享到目前为止您尝试过的代码,那么它将有助于解决您的问题。 @Subham
  • 这是我的代码..

标签: c# winforms pdf pdf-generation desktop-application


【解决方案1】:

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

示例代码可以在这里找到, http://forum.pdfsharp.net/viewtopic.php?p=2637#p2637

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

【讨论】:

    【解决方案2】:

    这是我用来填写 PDF 表单的一些 VB.Net 代码。您需要一个带有与 SQL 记录字段名称匹配的表单控件名称的 PDF 可填写表单。

    它调用一个例程 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
    

    【讨论】:

      猜你喜欢
      • 2017-12-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-03-16
      • 1970-01-01
      相关资源
      最近更新 更多