Click here to Skip to main content
15,867,308 members
Articles / Programming Languages / C#
Article

PDF Library for creating PDF with tables and text, in C#

Rate me:
Please Sign up or sign in to vote.
4.65/5 (53 votes)
3 Jul 2004CPOL4 min read 597.5K   10.1K   183   173
Create PDF files on the fly using this simple library.

Introduction

This is my second article towards creating PDF files. The earlier one employed on simple text and this version in C# can add tables to the PDF files. This library can be used for simple HTML conversion, or conversion from other documents if you know that document format. At present, it can add only tables, and create PDF document with any number of pages.

Let us begin by using the library. Download the library and add a reference to the library in your .NET project.

Creating a PDF Document

Creating a PDF document can be divided into three steps.

  1. Writing the header of the PDF file.
  2. Creating pages of the document.
    1. Add text.
    2. Add table.
  3. Finish the document.

In each step, you open a file specifying the output file name. In the first step, it's is opened as create, and in every other step it is open as append. In PDF format, every object we create and write are referenced by the byte offset of that object within the file.

Step One

I will go by explaining the code sample for using the PDF library.

C#
//Create a Catalog Dictionary
CatalogDict catalogDict=new CatalogDict();

//Create a Page Tree Dictionary
PageTreeDict pageTreeDict=new PageTreeDict();

//Create a Font Dictionary
FontDict TimesRoman=new FontDict();
FontDict TimesItalic=new FontDict();

//Create the info Dictionary
InfoDict infoDict=new InfoDict();

//Create the font called Times Roman
TimesRoman.CreateFontDict("T1","Times-Roman");

//Create the font called Times Italic
TimesItalic.CreateFontDict("T2","Times-Italic");

//Set the info Dictionary. 
infoDict.SetInfo("title","author","company");

//Create a utility object
Utility pdfUtility=new Utility();

//Open a file specifying the file name as the output pdffile 
FileStream file=new FileStream(@"c:\text.pdf",FileMode.Create);
int size=0;
file.Write(pdfUtility.GetHeader("1.5",out size),0,size);
file.Close();
//Now we finished doing the first step

Create the pages in the document. Here we are creating only one page. This process can be repeated to include any number of pages. A page will have its contents. Contents are the text and table that we create. This content is an object of the type ContentDict. A page can have any number of ContentDicts, but two or more pages cannot have the same ContentDict.

Every page must be added to the PageTreeDict. This is the RootNode of the pages in the PDF Document structure. In a PDF document, there will be only one PageTree (created with this library). This is created by using PageTreeDict.AddPage(). The order of the page in the document will be in the order how there were added to the PageTree.

To every page, resources must be added. These resource include the font that must be used inside the page and the objects of the ContentDict. This is done by calling PageDict.AddResource. The font types that are to be used are specified in the library. In this library, only fonts of type Times New Roman will be correctly centered and right aligned. This is because, for aligning, we must have the width of all the character glimpses. I have stored only the width of Times New Roman.

In AddPage, we specify the objNum of the page to be added, and in AddResource, we add the objNum of the ContentDict.

For adding text and tables in the page, create an object of type TextAndTables. For adding text, call addText specifying the X and Y coordinates.

For adding table, first fill the parameters of the table using TableParams. In the constructor, specify the number of columns and their widths. If the widths are same then you can use the other constructor just specifying the number of columns and setting the numColumns parameter of the structure. In this version, only the three parameters of the table need to be set, they are:

  1. row height
  2. X coordinate
  3. Y coordinate

Now, we can specify the alignment of each text within a cell. If we have two columns, create an array of two Align elements.

After this much initialization, call the TextAndTable.AddRow() member. This can be called as many times as to add new rows. When finished, call EndTable(). This will return a string. This string should be passed to content.SetStream().

Now add these things to the file. Then we have finished our second step.

C#
//Create a Page Dictionary , this represents a visible page
PageDict page=new PageDict();
ContentDict content=new ContentDict();

//The page size object will hold all the page size information
PageSize pSize=new PageSize(612,792);
pSize.SetMargins(10,10,10,10);
page.CreatePage(pageTreeDict.objectNum,pSize);
pageTreeDict.AddPage(page.objectNum);
page.AddResource(TimesRoman,content.objectNum);

//Create a Text And Table Object that present the elements in the page
TextAndTables textAndtable=new TextAndTables(pSize);

//Add text to the page
textAndtable.AddText(20,10,"Testing",10,"T1",Align.CenterAlign);

//Create the array for alignment value.
//This is specified for text in each column 
//of the table, here we have two columns
Align[] align=new Align[2];
align[0]=Align.LeftAlign;
align[1]=Align.LeftAlign;

//Specify the color for the cell and the line
ColorSpec cellColor=new ColorSpec(100,100,100);
ColorSpec lineColor=new ColorSpec(98,200,200);

//Fill in the parameters for the table
TableParams table=new TableParams(2,200,200);
table.yPos=700;
table.xPos=100;
table.rowHeight=20;

//Set the parameters of this table
textAndtable.SetParams(table,cellColor,Align.CenterAlign,3);
textAndtable.AddRow(false,10,"T1",align,"First Column","Second Column");
textAndtable.AddRow(false,10,"T1",align,"Second Row","Second Row");

//Repeat till we require the number of rows.
//After drawing table and text add them to the page 
content.SetStream(textAndtable.EndTable(lineColor));
content.SetStream(textAndtable.EndText());
size=0;
file=new FileStream(@"c:\text.pdf",FileMode.Append); 
file.Write(page.GetPageDict(file.Length,out size),0,size);
file.Write(content.GetContentDict(file.Length,out size),0,size);
file.Close();

Step Three

Now that we have finished the creation of the page, we can end the creation of the PDF document. This is done by writing every piece of information to the file.

C#
//Write everything file size=0;
file=new FileStream(@"c:\text.pdf",FileMode.Append);
file.Write(catalogDict.GetCatalogDict(pageTreeDict.objectNum, 
                                  file.Length,out size),0,size);
file.Write(pageTreeDict.GetPageTree(file.Length,out size),0,size);
file.Write(TimesRoman.GetFontDict(file.Length,out size),0,size);
file.Write(TimesItalic.GetFontDict(file.Length,out size),0,size);
file.Write(infoDict.GetInfoDict(file.Length,out size),0,size);
file.Write(pdfUtility.CreateXrefTable(file.Length,out size),0,size);
file.Write(pdfUtility.GetTrailer(catalogDict.objectNum,
                           infoDict.objectNum,out size),0,size);
file.Close();

Testing

All the code above is included inside a single function. Usually, for creating HTML files, the steps one and three will be done only once, but step two will be repeated many times. You can use this library and clarify any doubts as you go using this. Try experimenting with this.

Conclusion

This is a very basic library for creating PDF files. Once you know the PDF format, you can modify the library to include many more features like drawing lines and circles. Actually, the project I have been working only required simple tables to be added to the PDF files. That's is why I had to limit to only that feature.

License

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


Written By
Engineer Hydenso Steel & Engineering Pvt Ltd
India India
Settled in the beautiful city of Kochi in India.
Started working in VC++, dotnet in the hometown from 2003 after searching hard for some position in research in robotics and Aritificial Interlligence.

Comments and Discussions

 
QuestionMessage Closed Pin
30-Jul-20 1:30
Michael Breeden30-Jul-20 1:30 
QuestionPDF in MFC Pin
Member 1064177917-Mar-14 23:26
Member 1064177917-Mar-14 23:26 
QuestionProblem with creating multiple pages Pin
gingeekrishna7-Mar-14 21:01
professionalgingeekrishna7-Mar-14 21:01 
This article is very amazing but i am getting problem with creating multiple pages. Please help me.


Thanks in advance.
QuestionCreating Multiple Pages. Pin
Brian252530-Jul-13 6:17
Brian252530-Jul-13 6:17 
QuestionProblem with center align Pin
Amarjeet Banwait26-Jul-13 20:06
Amarjeet Banwait26-Jul-13 20:06 
QuestionProblem With Rows Pin
Agustin Gibson Leyva Vazquez3-Jul-13 8:20
Agustin Gibson Leyva Vazquez3-Jul-13 8:20 
GeneralMy vote of 1 Pin
Member 1001668628-Apr-13 21:36
Member 1001668628-Apr-13 21:36 
QuestionIs the DLL needed to use the C# file? Pin
Awchie8-Nov-12 15:30
Awchie8-Nov-12 15:30 
AnswerRe: Is the DLL needed to use the C# file? Pin
Southmountain28-Jul-22 17:19
Southmountain28-Jul-22 17:19 
QuestionHow to extend Page according to data Pin
Member 93402726-Nov-12 21:15
Member 93402726-Nov-12 21:15 
Question@ Zainu : License Question Pin
sun_kkd4-Apr-12 12:13
sun_kkd4-Apr-12 12:13 
AnswerRe: @ Zainu : License Question Pin
shiraz12324-Aug-12 5:17
shiraz12324-Aug-12 5:17 
GeneralRe: @ Zainu : License Question Pin
Awchie8-Nov-12 15:35
Awchie8-Nov-12 15:35 
QuestionUnable to open pdf when Emailed Pin
sun_kkd4-Apr-12 10:06
sun_kkd4-Apr-12 10:06 
QuestionDocx to pdf conversion Pin
masdhasdh4-Apr-12 0:32
masdhasdh4-Apr-12 0:32 
QuestionWorking Well Pin
venkatganess13-Mar-12 0:41
venkatganess13-Mar-12 0:41 
GeneralMy vote of 5 Pin
DineshMaind15-Feb-12 22:10
DineshMaind15-Feb-12 22:10 
GeneralMy vote of 5 Pin
Manoj Kumar Choubey9-Feb-12 22:04
professionalManoj Kumar Choubey9-Feb-12 22:04 
GeneralMy vote of 1 Pin
ravi1six318-Nov-11 3:42
ravi1six318-Nov-11 3:42 
Questioncreate pdf in c# without third party tools Pin
deepakmoghekar20-Aug-11 4:18
deepakmoghekar20-Aug-11 4:18 
GeneralRead table data from PDF and dump to excel Pin
MrNilesh8-May-11 20:48
MrNilesh8-May-11 20:48 
GeneralMy vote of 4 Pin
Manik Kundu2-Mar-11 7:19
Manik Kundu2-Mar-11 7:19 
GeneralAdding Bookmarks using report.net dll Pin
V4u15-Feb-11 5:12
V4u15-Feb-11 5:12 
QuestionDifferent language Pin
Anh Chu8-Nov-10 19:01
Anh Chu8-Nov-10 19:01 
Questionhow to extract text from pdf file using c#.net ? Pin
Uday Phadke Pune12-Sep-10 3:02
Uday Phadke Pune12-Sep-10 3:02 

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.