1

I want to generate a PDF using windows form in the desktop application. I have readymade pdf design and I just want to feed data from database in that blank section of pdf for each user. (One type of receipt). Please guide me. I have searched but most of the time there is the solution in asp.net for the web application. I want to do in the desktop app. Here is my code I am able to fatch data from database and print in pdf. But main problem is trhat I have already designed pdf and I want to place data exactly at same field (ie name, Amount, date etc.)

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());
            }
        }
    }
}
Subham
  • 671
  • 9
  • 23

2 Answers2

0

Instead of modifying the document, please create a new document and copy the pages from the old document to new document

sample code can be found here, http://forum.pdfsharp.net/viewtopic.php?p=2637#p2637

Because modifying pdf is not recommended using 'PdfSharp' library. if you still want to edit you can use 'ISharp' library which needs a license.

Ravi Kumar G N
  • 396
  • 1
  • 3
  • 11
0

Here is some VB.Net code I use to fill PDF forms. You need a PDF fillable form with form control names matching the SQL record field names.

It calls a routine Gen.GetDataTable() that just builds a typical DataTable. You could re-code to accept a pre-built Datatable as a parameter. Only the top row is processed. The code can be modified to work with a DataRow (.Table.Columns for column reference) or a 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
rheitzman
  • 2,247
  • 3
  • 20
  • 36