Creating PDF File using Visual C# Form and MS Word Template

Admin
0
The code below is used to create Visual C# form that capable of populate MS Word template and convert the result to .PDF File.

For detail , I recommend you to check the tutorial video step by step in my Youtube Channel.

Or, watch it directly here.








using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;



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

        private void label1_Click(object sender, EventArgs e)
        {
            
        }

        private void button1_Click(object sender, EventArgs e)
        {
            // read input
            string Name     = NameBox.Text;
            string Address  = AddressBox.Text;
            string Phone    = PhoneBox.Text;

            // template path
            string tmpPath = @"C:\Users\User\Documents\TUTORIAL\CreatePDF\Template.docx";

            // output path
            string outputName = @"C:\Users\User\Documents\TUTORIAL\CreatePDF\Output.pdf";

            // shadow file name
            string shadowFile = @"C:\Users\User\Documents\TUTORIAL\CreatePDF\temp.docx";

            // Create shadow File
            System.IO.File.Copy(tmpPath, shadowFile, true);


            // open word
            Microsoft.Office.Interop.Word.Application app = new Microsoft.Office.Interop.Word.Application();
            Microsoft.Office.Interop.Word.Document doc = app.Documents.Open(shadowFile);

            // fill the "Name" bookmarks
            object oBookMark = "NameField";
            doc.Bookmarks.get_Item(ref oBookMark).Range.Text = Name;

            // fill the "Address" bookmarks
            oBookMark = "AddressField";
            doc.Bookmarks.get_Item(ref oBookMark).Range.Text = Address;

            // fill the "Phone" bookmarks
            oBookMark = "PhoneField";
            doc.Bookmarks.get_Item(ref oBookMark).Range.Text = Phone;

            doc.ExportAsFixedFormat(outputName, Microsoft.Office.Interop.Word.WdExportFormat.wdExportFormatPDF);

            doc.Close();
            app.Quit();
            System.IO.File.Delete(shadowFile);


            
        }
    }
}

Post a Comment

0Comments
* Please Don't Spam Here. All the Comments are Reviewed by Admin.
Post a Comment (0)

Disclaimer : Content provided on this page is for general informational purposes only. We make no representation or warranty of any kind, express or implied, regarding the accuracy, adequacy, validity, reliability, availability or completeness of any information.

#buttons=(Accept !) #days=(20)

Our website uses cookies to enhance your experience. Learn More
Accept !
To Top