Introduction
This article presents a basic text to PDF library. With this library, you can convert a plain text file to PDF format (PDF is an abbreviation of Portable Document Format). You can break your text file into PDF pages at any place (as long as you set up a page break "1" at column 1). This article also presents a sample application to demonstrate how to use this DLL.
Background
I started writing this library because I really couldn�t find a good C# library for exporting my reports. Of course, you can create your own library to suit your own purposes.
Implementation of the Library
To achieve the page break functionality, I created StartPage
, EndPage
, StartObject
, and StorePage
functions. If the stream reader reads the page break "1" of the input text file, I'll be able to end this page and start a new page. That is the whole idea.
The Dotext
function is as follows:
private void DoText(StreamReader sr)
{
string strLine = string.Empty;
StartPage();
try
{
while (sr.Peek() >= 0)
{
strLine = sr.ReadLine()+"\r\n";
if(yPos <= this.margin)
{
EndPage();
StartPage();
}
if(strLine == "" || strLine == null)
{
FileStreamWrite(outFileStream,@"T*\r\n");
}
else
{
int cmpPageVal = String.Compare(strLine.Substring(0,1),"1");
int cmpfVal = String.Compare(strLine.Substring(0,1),"\f");
bool bl = false;
if(cmpfVal == 0)
{
EndPage();
StartPage();
}
else
{
if (cmpPageVal == 0)
{
EndPage();
StartPage();
strLine = strLine.Remove(0,1);
}
FileStreamWrite(outFileStream,@"(");
char[] textchars=strLine.ToCharArray();
for (int index=0;index<textchars.Length;index++)
{
char c=textchars[index];
if(c=='1' && strLine.Length == 2)
{
EndPage();
StartPage();
}
else if(c=='\n')
{
if (!bl)
FileStreamWrite(outFileStream,@")'");
else
FileStreamWrite(outFileStream,@"T*\n");
bl = true;
}
else
{
FileStreamWrite(outFileStream,c.ToString());
bl=false;
}
}
if (!bl)
FileStreamWrite(outFileStream,@")\r\n");
}
}
yPos -= leadSize;
}
sr.Close();
sr = null;
EndPage();
}
catch( Exception ex )
{
string error = ("The process failed: " + ex.Message);
}
}
Using This Library
In the sample application, I put a Button
in a .aspx page.
Here is the code behind the button Click
function:
private void Button1_Click(object sender, System.EventArgs e)
{
string fileName = @"TextFile.txt";
string filePath = Server.MapPath("temp/" + fileName);
TextPDF.PdfWriter pdfWriter =
new TextPDF.PdfWriter(842.0f, 1190.0f, 10.0f, 10.0f);
if(filePath.Length > 0)
{
pdfWriter.Write(filePath);
}
}
Conclusion
By using this library, you can easily covert a plain text file to a PDF format file. You can also create a page break anywhere in the text file.
Note: I put the PDF output file underneath the "c:\temp\txtPdf.pdf" directory; and the input text file under the "TextPdfSample\temp\TextFile.txt".
History
- 12/10/2005 - Posted the article.