How to Create a PDF file in ASP Net MVC using iTextSharp DLL

How to Create a PDF file in ASP Net MVC using iTextSharp DLL

If you have to Create a PDF file you can use iTextSharp DLL. It is a free DLL which you can install from NuGet.

Next include the below 2 namespaces in your Controller:

using iTextSharp.text;
using iTextSharp.text.pdf;
Creating iTextSharp’s Document & Writer

When you Create a Pdf file, the first step is to create a Document and a PdfWriter. Then you need to open the Document.

Document pdfDoc = new Document(PageSize.A4, 25, 25, 25, 15);
PdfWriter pdfWriter = PdfWriter.GetInstance(pdfDoc, Response.OutputStream);
pdfDoc.Open(); 

Here I created the Document and set the page size as A4 and provided margins to it. Then I created an instance of PdfWriter classes and attached it to the Document.

On the 3rd line of code I opened the Document.

Creating the PDF file

When you have to Create a Pdf file then use the following code:

pdfWriter.CloseStream = false;
pdfDoc.Close();
Response.Buffer = true;
Response.ContentType = "application/pdf";
Response.AddHeader("content-disposition", "attachment;filename=Credit-Card-Report.pdf");
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.Write(pdfDoc);
Response.End();

I closed the PdfWriter stream and the document then set the ContentType to “application/pdf”. In the Response.AddHeader() I gave the Pdf file name and with Response.Write() the Pdf file is created.

Combining the Code

We combine the above two codes and inside them you add PDF element like paragraphs, lines, tables and so on. In this way the whole PDF file is created.

So look at the structure of the combined code:

/*Creating iTextSharp’s Document & Writer*/
Document pdfDoc = new Document(PageSize.A4, 25, 25, 25, 15);
PdfWriter pdfWriter = PdfWriter.GetInstance(pdfDoc, Response.OutputStream);
pdfDoc.Open();
/*End*/

//Here you create PDF elements like paragraph, table, lines and so on.

/*Creating the PDF file*/
pdfWriter.CloseStream = false;
pdfDoc.Close();
Response.Buffer = true;
Response.ContentType = "application/pdf";
Response.AddHeader("content-disposition", "attachment;filename=Credit-Card-Report.pdf");
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.Write(pdfDoc);
Response.End();
/*End*/ 

Creating PDF Elements on iTextSharp

The iTextSharp provide lots of PDF elements which you can add to the PDF document. These are Paragraph, Image, Table, Chunk and so on. Let us discuss each of them:

Chunk

Chunk is a building block of element through which you can add a text with a certain font. To create a text, with Arial font, font-size as 20, font-weight as bold & italic and color of magenta, use chunk like this:

Chunk chunk = new Chunk("Your Text", FontFactory.GetFont("Arial", 20, Font.BOLDITALIC, BaseColor.MAGENTA));

Paragraph

A paragraph is similar a chunk and is used to create a certain text.

Paragraph para = new Paragraph("Your Text"); 
A paragraph with Chunk can be used to create a Horizontal line like this:
Paragraph line = new Paragraph(new Chunk(new iTextSharp.text.pdf.draw.LineSeparator(0.0F, 100.0F, BaseColor.BLACK, Element.ALIGN_LEFT, 1)));

Image

Image represents a Graphical Element. You can use it to add any image to your PDF file.

Image image = Image.GetInstance(Server.MapPath("~/myPic.jpg"));

PdfTable & PdfPCell

PdfTable is a table element containing rows and columns. It contains PdfPCell and PdfCell can contain other elements like Image, Chunk, Paragraph, etc.

PdfPTable table = new PdfPTable(2);
PdfPCell cell = new PdfPCell();

Image image = Image.GetInstance(Server.MapPath("~/myPic.jpg"));
cell.AddElement(image);
table.AddCell(cell);

Paragraph para = new Paragraph("Your Text"); 
cell = new PdfPCell();
cell.AddElement(para);
table.AddCell(cell);

In the above code I created PdfPTable that has 2 columns. Then I created a PdfPCell and an Image element and added the image to the PdfPCell. Then I added that PdfPCell to the PdfPTable.

In the same way I added a Paragraph element to another cell and added that cell to the table.

Example: Create a Pdf

I give you a complete example that explains How to Create a Pdf file with iTextSharp.

This PDF file will look like the image that is shown below:

created pdf file

To download this PDF file click here.

This Pdf file has the following sections:

  • 1. A top heading with a text.
  • 2. Few horizontal line.
  • 3. A table containing 2 columns – a picture of a person on the first columns and person’s details on the second column.
  • 4. A table containing 5 columns and looks like a Grid.
  • 5. A paragraph containing hello message.
  • 6. A Link.
Starting with the Code

First you create a Document and a PdfWriter and open the Document.

Document pdfDoc = new Document(PageSize.A4, 25, 25, 25, 15);
PdfWriter pdfWriter = PdfWriter.GetInstance(pdfDoc, Response.OutputStream);
pdfDoc.Open();
Top Heading

Create a top heading with Chunk and add it to the Document.

Chunk chunk = new Chunk("Your Credit Card Statement Report has been Generated", FontFactory.GetFont("Arial", 20, Font.BOLDITALIC, BaseColor.MAGENTA));
pdfDoc.Add(chunk);
Horizontal Line

Create a horizontal like using Paragraph and Chunk and add it to the document.

Paragraph line = new Paragraph(new Chunk(new iTextSharp.text.pdf.draw.LineSeparator(0.0F, 100.0F, BaseColor.BLACK, Element.ALIGN_LEFT, 1)));
pdfDoc.Add(line);
Table with 2 Columns

Create a table and set its width to 100% of the size of the Document. Align it to left size of the document (.HorizontalAlignment=0) and provide some spacings to it.

Add the 2 columns (set border=0 as I don’t want any border on these 2 cells). In the first cell put image and on the second cell put text.

Add the cells to the table and then add this table to document.

//Table
PdfPTable table = new PdfPTable(2);
table.WidthPercentage = 100;
table.HorizontalAlignment = 0; //0=Left, 1=Centre, 2=Right
table.SpacingBefore = 20f;
table.SpacingAfter = 30f;

//Cell no 1
PdfPCell cell = new PdfPCell();
cell.Border = 0;
Image image = Image.GetInstance(Server.MapPath("~/Content/Upload/salma.jpg"));
image.ScaleAbsolute(200, 150);
cell.AddElement(image);
table.AddCell(cell);

//Cell no 2
chunk = new Chunk("Name: Mrs. Salma Mukherji,\nAddress: Latham Village, Latham, New York, US, \nOccupation: Nurse, \nAge: 35 years", FontFactory.GetFont("Arial", 15, Font.NORMAL, BaseColor.PINK));
cell = new PdfPCell();
cell.Border = 0;
cell.AddElement(chunk);
table.AddCell(cell);

//Add table to document    
pdfDoc.Add(table);
Table with 5 columns that looks like a Grid

Create the PdfTable(5), in the first cell make it Colspan=5 because I want it to be the size of the full row.

So the next cells will automatically come down from the 2nd row.

//Table
table = new PdfPTable(5);
table.WidthPercentage = 100;
table.HorizontalAlignment = 0;
table.SpacingBefore = 20f;
table.SpacingAfter = 30f;

//Cell
cell = new PdfPCell();
chunk = new Chunk("This Month's Transactions of your Credit Card");
cell.AddElement(chunk);
cell.Colspan = 5;
cell.BackgroundColor = BaseColor.PINK;
table.AddCell(cell);

table.AddCell("S.No");
table.AddCell("NYC Junction");
table.AddCell("Item");
table.AddCell("Cost");
table.AddCell("Date");

table.AddCell("1");
table.AddCell("David Food Store");
table.AddCell("Fruits & Vegetables");
table.AddCell("$100.00");
table.AddCell("June 1");

table.AddCell("2");
table.AddCell("Child Store");
table.AddCell("Diaper Pack");
table.AddCell("$6.00");
table.AddCell("June 9");

table.AddCell("3");
table.AddCell("Punjabi Restaurant");
table.AddCell("Dinner");
table.AddCell("$29.00");
table.AddCell("June 15");

table.AddCell("4");
table.AddCell("Wallmart Albany");
table.AddCell("Grocery");
table.AddCell("$299.50");
table.AddCell("June 25");

table.AddCell("5");
table.AddCell("Singh Drugs");
table.AddCell("Back Pain Tablets");
table.AddCell("$14.99");
table.AddCell("June 28");

//Add table to document
pdfDoc.Add(table);
Paragraph Containing Hello text

Add the below code for this:

Paragraph para = new Paragraph();
para.Add("Hello Salma,\n\nThank you for being our valuable customer. We hope our letter finds you in the best of health and wealth.\n\nYours Sincerely, \nBank of America");
pdfDoc.Add(para);
Text with Link

To create a link I use Chunk and use its .SetAnchor() method to provide the link URL to the Chunk text.

See the below code for creating link in Pdf document:

chunk = new Chunk("How to Create a Pdf File");
chunk.Font = FontFactory.GetFont("Arial", 25, Font.BOLD, BaseColor.RED);
chunk.SetAnchor("http://www.yogihosting.com/create-pdf-asp-net-mvc/");
pdfDoc.Add(chunk);
Ending by creating the Pdf

To create a Pdf use the below code and place it on the end.

pdfWriter.CloseStream = false;
pdfDoc.Close();
Response.Buffer = true;
Response.ContentType = "application/pdf";
Response.AddHeader("content-disposition", "attachment;filename=Credit-Card-Report.pdf");
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.Write(pdfDoc);
Response.End();

Full Code of Creating Pdf in ASP.NET MVC

Create a Controller and name it CreatePdfController then add the below Action method to it.

[HttpPost]
[ActionName("Index")]
public ActionResult Index_Post()
{
    Document pdfDoc = new Document(PageSize.A4, 25, 25, 25, 15);
    PdfWriter pdfWriter = PdfWriter.GetInstance(pdfDoc, Response.OutputStream);
    pdfDoc.Open();

    //Top Heading
    Chunk chunk = new Chunk("Your Credit Card Statement Report has been Generated", FontFactory.GetFont("Arial", 20, Font.BOLDITALIC, BaseColor.MAGENTA));
    pdfDoc.Add(chunk);

    //Horizontal Line
    Paragraph line = new Paragraph(new Chunk(new iTextSharp.text.pdf.draw.LineSeparator(0.0F, 100.0F, BaseColor.BLACK, Element.ALIGN_LEFT, 1)));
    pdfDoc.Add(line);

    //Table
    PdfPTable table = new PdfPTable(2);
    table.WidthPercentage = 100;
    //0=Left, 1=Centre, 2=Right
    table.HorizontalAlignment = 0;
    table.SpacingBefore = 20f;
    table.SpacingAfter = 30f;

    //Cell no 1
    PdfPCell cell = new PdfPCell();
    cell.Border = 0;
    Image image = Image.GetInstance(Server.MapPath("~/Content/Upload/salma.jpg"));
    image.ScaleAbsolute(200, 150);
    cell.AddElement(image);
    table.AddCell(cell);

    //Cell no 2
    chunk = new Chunk("Name: Mrs. Salma Mukherji,\nAddress: Latham Village, Latham, New York, US, \nOccupation: Nurse, \nAge: 35 years", FontFactory.GetFont("Arial", 15, Font.NORMAL, BaseColor.PINK));
    cell = new PdfPCell();
    cell.Border = 0;
    cell.AddElement(chunk);
    table.AddCell(cell);

    //Add table to document
    pdfDoc.Add(table);

    //Horizontal Line
    line = new Paragraph(new Chunk(new iTextSharp.text.pdf.draw.LineSeparator(0.0F, 100.0F, BaseColor.BLACK, Element.ALIGN_LEFT, 1)));
    pdfDoc.Add(line);

    //Table
    table = new PdfPTable(5);
    table.WidthPercentage = 100;
    table.HorizontalAlignment = 0;
    table.SpacingBefore = 20f;
    table.SpacingAfter = 30f;

    //Cell
    cell = new PdfPCell();
    chunk = new Chunk("This Month's Transactions of your Credit Card");
    cell.AddElement(chunk);
    cell.Colspan = 5;
    cell.BackgroundColor = BaseColor.PINK;
    table.AddCell(cell);

    table.AddCell("S.No");
    table.AddCell("NYC Junction");
    table.AddCell("Item");
    table.AddCell("Cost");
    table.AddCell("Date");

    table.AddCell("1");
    table.AddCell("David Food Store");
    table.AddCell("Fruits & Vegetables");
    table.AddCell("$100.00");
    table.AddCell("June 1");

    table.AddCell("2");
    table.AddCell("Child Store");
    table.AddCell("Diaper Pack");
    table.AddCell("$6.00");
    table.AddCell("June 9");

    table.AddCell("3");
    table.AddCell("Punjabi Restaurant");
    table.AddCell("Dinner");
    table.AddCell("$29.00");
    table.AddCell("June 15");

    table.AddCell("4");
    table.AddCell("Wallmart Albany");
    table.AddCell("Grocery");
    table.AddCell("$299.50");
    table.AddCell("June 25");

    table.AddCell("5");
    table.AddCell("Singh Drugs");
    table.AddCell("Back Pain Tablets");
    table.AddCell("$14.99");
    table.AddCell("June 28");

    pdfDoc.Add(table);

    Paragraph para = new Paragraph();
    para.Add("Hello Salma,\n\nThank you for being our valuable customer. We hope our letter finds you in the best of health and wealth.\n\nYours Sincerely, \nBank of America");
    pdfDoc.Add(para);

    //Horizontal Line
    line = new Paragraph(new Chunk(new iTextSharp.text.pdf.draw.LineSeparator(0.0F, 100.0F, BaseColor.BLACK, Element.ALIGN_LEFT, 1)));
    pdfDoc.Add(line);

    para = new Paragraph();
    para.Add("This PDF is generated using iTextSharp. You can read the turorial:");
    para.SpacingBefore = 20f;
    para.SpacingAfter = 20f;
    pdfDoc.Add(para);

    //Creating link
    chunk = new Chunk("How to Create a Pdf File");
    chunk.Font = FontFactory.GetFont("Arial", 25, Font.BOLD, BaseColor.RED);
    chunk.SetAnchor("http://www.yogihosting.com/create-pdf-asp-net-mvc/");
    pdfDoc.Add(chunk);

    pdfWriter.CloseStream = false;
    pdfDoc.Close();
    Response.Buffer = true;
    Response.ContentType = "application/pdf";
    Response.AddHeader("content-disposition", "attachment;filename=Credit-Card-Report.pdf");
    Response.Cache.SetCacheability(HttpCacheability.NoCache);
    Response.Write(pdfDoc);
    Response.End();

    return View();
}

Now add the below code to the View:

@using (Html.BeginForm("Index", "CreatePdf"))
{
    <button id="submitButton" type="submit">Create Pdf</button>
}

Now run the Application and go to the Index view. On clicking the Create Pdf button on the View, your Pdf file will be created.

DOWNLOAD

You should also view these ASP.NET Tutorial on Excel Files:

Conclusion
In this way you can Create a Pdf file using iTextSharp. I hope you enjoyed this tutorial and learned something new today. Please share this tutorial on your facebook, twitter and instagram accounts and let others know how easy it is to create any pdf file in asp.net mvc application.

Share this article -

yogihosting

ABOUT THE AUTHOR

This article has been written by the Technical Staff of YogiHosting. Check out other articles on “WordPress, SEO, jQuery, HTML” and more.