"We are what our thoughts have made us; so take care about what you think. Words are secondary. Thoughts live; they travel far."

Create PDF document using iTextSharp in ASP.Net 4.0 and MemoryMappedFile

In this article I am going to demonstrate how ASP.Net developers can programmatically create PDF documents using iTextSharp. iTextSharp is a software component, that allows developers to programmatically create or manipulate PDF documents. Also this article discusses the process of creating in-memory file, read/write data from/to the in-memory file utilizing the new feature MemoryMappedFile.

I have a database of users, where I need to send a notice to all my users as a PDF document. The sending mail part of it is not covered in this article. The PDF document will contain the company letter head, to make it more official.

I have a list of users stored in a database table named “tblusers”. For each user I need to send customized message addressed to them personally. The database structure for the users is give below.

id

Title

Full Name

1

Mr.

Sreeju Nair K. G.

2

Dr.

Alberto Mathews

3

Prof.

Venketachalam

Now I am going to generate the pdf document that contains some message to the user, in the following format.

Dear <Title> <FullName>,

The message for the user.

Regards,
Administrator

Also I have an image, bg.jpg that contains the background for the document generated.

I have created .Net 4.0 empty web application project named “iTextSharpSample”. First thing I need to do is to download the iTextSharp dll from the source forge. You can find the url for the download here. http://sourceforge.net/projects/itextsharp/files/

I have extracted the Zip file and added the itextsharp.dll as a reference to my project. Also I have added a web form named default.aspx to my project. After doing all this, the solution explorer have the following view.

clip_image001

In the default.aspx page, I inserted one grid view and associated it with a SQL Data source control that bind data from tblusers. I have added a button column in the grid view with text “generate pdf”. The output of the page in the browser is as follows.

clip_image002

Now I am going to create a pdf document when the user clicking on the Generate PDF button. As I mentioned before, I am going to work with the file in memory, I am not going to create a file in the disk. I added an event handler for button by specifying onrowcommand event handler. My gridview source looks like

<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"

DataSourceID="SqlDataSource1" Width="481px"

CellPadding="4" ForeColor="#333333" GridLines="None"

onrowcommand="Generate_PDF" >

…………………………………………………………………………..

…………………………………………………………………………..

</asp:GridView>

In the code behind, I wrote the corresponding event handler.

protected void Generate_PDF(object sender, GridViewCommandEventArgs e)

{

// The button click event handler code.

// I am going to explain the code for this section in the remaining part of the article

}

The Generate_PDF method is straight forward, It get the title, fullname and message to some variables, then create the pdf using these variables.

The code for getting data from the grid view is as follows

// get the row index stored in the CommandArgument property

int index = Convert.ToInt32(e.CommandArgument);

// get the GridViewRow where the command is raised

GridViewRow selectedRow = ((GridView)e.CommandSource).Rows[index];

string title = selectedRow.Cells[1].Text;

string fullname = selectedRow.Cells[2].Text;

string msg = @"There are some changes in the company policy, due to this matter you need to submit your latest address to us. Please update your contact details      personnal details by visiting the member area of the website. ................................... ";

since I don’t want to save the file in the disk, I am going the new feature introduced in .Net framework 4, called Memory-Mapped Files. Using Memory-Mapped mapped file, you can created non-persisted memory mapped files, that are not associated with a file in a disk. So I am going to create a temporary file in memory, add the pdf content to it, then write it to the output stream.

To read more about MemoryMappedFile, read this msdn article

http://msdn.microsoft.com/en-us/library/dd997372.aspx

The below portion of the code using MemoryMappedFile object to create a test pdf document in memory and perform read/write operation on file. The CreateViewStream() object will give you a stream that can be used to read or write data to/from file. The code is very straight forward and I included comment so that you can understand the code.

using (MemoryMappedFile mmf = MemoryMappedFile.CreateNew("test1.pdf", 1000000))

{

// Create a new pdf document object using the constructor. The parameters passed are document size, left margin, right margin, top margin and bottom margin.

iTextSharp.text.Document d = new iTextSharp.text.Document(PageSize.A4, 72,72,172,72);

//get an instance of the memory mapped file to stream object so that user can write to this

using (MemoryMappedViewStream stream = mmf.CreateViewStream())

{

// associate the document to the stream.

PdfWriter.GetInstance(d, stream);

//add an image as bg

iTextSharp.text.Image jpg = iTextSharp.text.Image.GetInstance(Server.MapPath("Image/bg.png"));

jpg.Alignment = iTextSharp.text.Image.UNDERLYING;

jpg.SetAbsolutePosition(0, 0);

//this is the size of my background letter head image. the size is in points. this will fit to A4 size document.

jpg.ScaleToFit(595, 842);

d.Open();

d.Add(jpg);

d.Add(new Paragraph(String.Format("Dear {0} {1},", title, fullname)));

d.Add(new Paragraph("\n"));

d.Add(new Paragraph(msg));

d.Add(new Paragraph("\n"));

d.Add(new Paragraph(String.Format("Administrator")));

d.Close();

}

//read the data from the file and send it to the response stream

byte[] b;

using (MemoryMappedViewStream stream = mmf.CreateViewStream())

{

BinaryReader rdr = new BinaryReader(stream);

b = new byte[mmf.CreateViewStream().Length];

rdr.Read(b, 0, (int)mmf.CreateViewStream().Length);

}

Response.Clear();

Response.ContentType = "Application/pdf";

Response.BinaryWrite(b);

Response.End();

}

Press ctrl + f5 to run the application. First I got the user list. Click on the generate pdf icon. The created looks as follows.

clip_image003

Summary:

Creating pdf document using iTextSharp is easy. You will get lot of information while surfing the www. Some useful resources and references are mentioned below

http://itextsharp.com/

http://www.mikesdotnetting.com/Article/82/iTextSharp-Adding-Text-with-Chunks-Phrases-and-Paragraphs

http://somewebguy.wordpress.com/2009/05/08/itextsharp-simplify-your-html-to-pdf-creation/

Hope you enjoyed the article.

11 Comments

Comments have been disabled for this content.