blog

home / developersection / blogs / convert text document to pdf file

Convert Text Document to PDF File

Anonymous User 5.73 K 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.     OpenFileDialog This class is use to open file dialog for select text file.that text file convert into pdf file.


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


3.   Document This class allows creating a new instance for Creating PDF File.


4.   PdfWriter This class, an instantaneous access to write a PDF document from an object ofDocumentclass. 


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:

 

  private void button1_Click(object sender, EventArgs e)
        {
            var t = new Thread((ThreadStart)(() =>
            {
                OpenFileDialog op = new OpenFileDialog();
                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:
  private void button2_Click(object sender, EventArgs e)
        {
            StreamReader rdr = new StreamReader(txtInput.Text);
            Document doc = new Document();
          
            PdfWriter.GetInstance(doc, new FileStream(txtOutput.Text, FileMode.Create));
            doc.Open();
            doc.Add(new Paragraph(rdr.ReadToEnd()));
            doc.Close();
            MessageBox.Show("Conversion Successful....");
            System.Diagnostics.Process.Start(txtOutput.Text);
        }
Form_Load:
  private void Form1_Load(object sender, EventArgs e)
        {
            Form1.CheckForIllegalCrossThreadCalls = false;
        }
Output:

 

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


c# c#  .net 
Updated 14-Oct-2014

I am a content writter !

Leave Comment

Comments

Liked By