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.
Document Thisclass allows creating a new instance for Creating PDF File.
3.PdfWriter Thisclass, an instantaneous access to write a PDF document from an object of Documentclass.
4.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:
in my next post i'll explain about Substring methods in C#
Leave Comment