Function to
Convert/Export text file to PDF using iTextSharp, C#, DotNet
iTextSharp is free dll available for download
on http://sourceforge.net/projects/itextsharp/
Add reference to iTextSharp dll in your
project
Description:
About Classes used -
#1: StreamReader
class provides an access to read the data from Stream such as Text File.
#2: Document
class allows creating a new instance for Creating PDF File.
#3: PdfWriter
class, an instantaneous access to write a PDF document from an object of Documentclass.
*
Namespace
Required:
System.IO,
iTextSharp,
iTextSharp.text,
iTextSharp.text.pdf
/// <summary>
/// Convert Text File into a PDF File
/// </summary>
/// <param
name="sInputFilePath">
Input text File Path</param>
/// <param
name="sOutputFilePath">Output
text File Path</param>
private void
ConvertTextFileToPDF(string sInputFilePath, string sOutputFilePath)
{
try
{
//Read the
Data from Input File
StreamReader
rdr = new StreamReader(sInputFilePath);
//Create a
New instance on Document Class
Document
doc = new Document();
//Create a
New instance of PDFWriter Class for Output File
PdfWriter.GetInstance(doc,
new FileStream(sOutputFilePath,
FileMode.Create));
//Open the
Document
doc.Open();
//Add the
content of Text File to PDF File
doc.Add(new
Paragraph(rdr.ReadToEnd()));
//Close the
Document
doc.Close();
//Open the
Converted PDF File in Desktop application using below line
System.Diagnostics.Process.Start(sOutputFilePath); //Comment it for web application
}
catch (Exception ex)
{
throw
ex;
}
}
Calling Example:
ConvertTextFileToPDF(@"C:\Users\user\Desktop\UID.txt", @"C:\Users\user\Desktop\UID.pdf");
No comments:
Post a Comment