Click here to Skip to main content
15,912,977 members
Articles / Database Development / SQL Server
Article

Convert a Text File to a PDF File

Rate me:
Please Sign up or sign in to vote.
4.57/5 (22 votes)
14 Dec 2005CPOL1 min read 252.5K   8.2K   98   34
This article shows how to convert a text file to PDF.

Sample Image

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:

C#
private void DoText(StreamReader sr)
{
    string strLine = string.Empty;

    //Start Page
    StartPage();

    try
    {
        while (sr.Peek() >= 0)
        {
            //Get one string at a time from the input text file
            strLine = sr.ReadLine()+"\r\n";

            //If yPos <= this.margin?
            if(yPos <= this.margin) 
            {
                //Invoke EndPage and StartPage functions
                EndPage();
                StartPage();
            }

            if(strLine == "" || strLine == null)
            {
                FileStreamWrite(outFileStream,@"T*\r\n");
            }
            else
            {
                //Is there a page break "1"?
                int cmpPageVal = String.Compare(strLine.Substring(0,1),"1");
                
                //Is there a Formfeed?
                int cmpfVal    = String.Compare(strLine.Substring(0,1),"\f");
            
                bool bl = false;

                //Formfeed
                if(cmpfVal == 0)
                {
                    //Invoke EndPage and StartPage functions
                    EndPage();
                    StartPage();
                }
                else
                {
                    //If there is a page break "1"
                    if (cmpPageVal == 0)
                    {
                        //Invoke EndPage and StartPage functions
                        EndPage();
                        StartPage();

                        //Remove the page break "1"
                        strLine = strLine.Remove(0,1);
                    }

                    FileStreamWrite(outFileStream,@"(");

                    //Convert "strLine" to a char array
                    char[] textchars=strLine.ToCharArray();

                    for (int index=0;index<textchars.Length;index++)
                    {
                        char c=textchars[index];

                        //If there is page break
                        if(c=='1' && strLine.Length == 2)
                        {
                            EndPage();
                            StartPage();
                        }
                            //new line
                        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");
                }

            }

            //Set yPos
            yPos -= leadSize;
        }//for loop

        //Close file
        sr.Close();
        sr = null;

        //End page
        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:

C#
private void Button1_Click(object sender, System.EventArgs e)
{
    //The input text file "TextFile.txt"
    string fileName = @"TextFile.txt";
    string filePath = Server.MapPath("temp/" + fileName);
    
    // Create a new PdfWriter
    TextPDF.PdfWriter pdfWriter = 
       new TextPDF.PdfWriter(842.0f, 1190.0f, 10.0f, 10.0f);

    if(filePath.Length > 0)
    {
        //Write to a PDF file
        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.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Web Developer
United States United States
M.S.: Computer Science, B.S.: Physics, MCSD: .NET, MCSD: VS 6

Florence currently works at Confident Software, Inc. Atlanta, U.S.A. Besides programming, during her spare time she enjoys opera.

Comments and Discussions

 
GeneralRe: text to pdf Pin
Florence FZ Li5-Jun-08 3:49
Florence FZ Li5-Jun-08 3:49 
GeneralRe: text to pdf Pin
Member 102920652-Oct-13 22:27
Member 102920652-Oct-13 22:27 
QuestionHow to insert logo? Pin
rao_1025-Oct-07 7:57
rao_1025-Oct-07 7:57 
GeneralThanks...you made my work easy Pin
rao_1019-Oct-07 10:13
rao_1019-Oct-07 10:13 
QuestionBlank first page Pin
kepat20-Sep-07 9:05
kepat20-Sep-07 9:05 
GeneralThanks... but need some explanation about code. Pin
mani_iips16-Aug-07 22:00
mani_iips16-Aug-07 22:00 
GeneralThanks Pin
N_dog15-Jun-07 4:49
N_dog15-Jun-07 4:49 
QuestionError in pdf generation while using brackets Pin
Justin_Joseph14-Jun-07 19:36
Justin_Joseph14-Jun-07 19:36 
I am having a really weird kind of a problem, when my text is having brackets (eg:
The purpose of this (agreement is to define acceptable and unacceptable behaviour when using ABC computing facility) and to clarify what actions may be taken if the agreement is breached.

)

When i write this statement into the pdf document i get some garbage text attached with the above statment and some part of the statement also goes missing. This error only occurs if there are brackets in the text, like the one above, and spans two lines in the pdf.(ie the open bracket is on the first line and the closing bracket is on the second line in the pdf.).
If the open and close brackets is on the same line there is no problem.This problem only occures with circular brackets ( ).

Text from Gios generated pdf for the above statement.

The purpose of this (agreement is to define acceptable and unacceptable ) Tj1 0 0 1 208.5 be taken if the agreement is breached.



The Gios version i am using is 1.0.2503.25090 and Acrobat 7.0.
Even the latest gios version is giving problems while using brackets 1.0.2721.20138
(it replaces brackets with \050)




Justin
AnswerRe: Error in pdf generation while using brackets Pin
g'nads1-Dec-07 6:41
g'nads1-Dec-07 6:41 
QuestionWord Wrap Pin
rye0426-Oct-06 15:06
rye0426-Oct-06 15:06 
GeneralIt's good to explore to learn, but ... Pin
M.Lansdaal20-Dec-05 9:25
M.Lansdaal20-Dec-05 9:25 
GeneralRe: It's good to explore to learn, but ... Pin
Florence FZ Li20-Dec-05 10:21
Florence FZ Li20-Dec-05 10:21 
GeneralRe: It's good to explore to learn, but ... Pin
M.Lansdaal20-Dec-05 10:22
M.Lansdaal20-Dec-05 10:22 
GeneralTrouble with brackets Pin
caiafaverde19-Dec-05 23:01
caiafaverde19-Dec-05 23:01 
GeneralRe: Trouble with brackets Pin
Florence FZ Li20-Dec-05 4:13
Florence FZ Li20-Dec-05 4:13 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.