blog

Home / DeveloperSection / Blogs / Convert Text Document to PDF File

Convert Text Document to PDF File

Anonymous User5447 14-Oct-2014

In this blog I’m explaining about how to convert text document to pdf file in c#.

Description:-

About classes used:-

1.     OpenFileDialogThis class is use to open file dialog for select text file.that text file convert into pdf file.


2.   StreamReaderThis class provides an access to read the data from Stream such as Text File.


3.   DocumentThisclass allows creating a new instance for Creating PDF File.


4.   PdfWriterThisclass, an instantaneous access to write a PDF document from an object of Documentclass. 


About namespace used:-

1.  using iTextSharp.text;

2.  using iTextSharp.text.pdf;

3.  using System;

4.  using System.IO;

5.  using System.Threading;

6.   using System.Windows.Forms;


About controls used:-
1.       TextBox Control (txtInput, txtOutput)
2.       Button Control (btnSelect, btnCreatePDF)  

Here I’m implementing to convert text document into pdf file use iTextSharp dll.

Button1:

 

  privatevoid button1_Click(object sender, EventArgs e)
        {
            var t = newThread((ThreadStart)(() =>
            {
                OpenFileDialog op = newOpenFileDialog();
                if (op.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                {
                    txtInput.Text = op.FileName;
                    txtOutput.Text = (txtInput.Text).Replace(".txt", ".pdf");
                }
            }));
            t.SetApartmentState(ApartmentState.STA);
            t.Start();
        }
Button2:
  privatevoid button2_Click(object sender, EventArgs e)
        {
            StreamReader rdr = newStreamReader(txtInput.Text);
            Document doc = newDocument();
          
            PdfWriter.GetInstance(doc, newFileStream(txtOutput.Text, FileMode.Create));
            doc.Open();
            doc.Add(newParagraph(rdr.ReadToEnd()));
            doc.Close();
            MessageBox.Show("Conversion Successful....");
            System.Diagnostics.Process.Start(txtOutput.Text);
        }
Form_Load:
  privatevoid Form1_Load(object sender, EventArgs e)
        {
            Form1.CheckForIllegalCrossThreadCalls = false;
        }
Output:

 Convert Text Document to PDF File

in my next post i'll explain about Substring methods in C#


Updated 14-Oct-2014
I am a content writter !

Leave Comment

Comments

Liked By