Introduction
This article describes how to generate a PDF file at runtime in ASP.NET. For generating the PDF file, you need to use a PDF generator library.
Note: I will use the "iTextSharp.dll" as a PDF generator library. You can download it from:
- Links
http://sourceforge.net/projects/itextsharp
https://www.nuget.org/packages/iTextSharp/
- You can download the attached file of this article.
To explain this article, I will do the procedure like:
- Add a reference of the downloaded "iTextSharp.dll" to the Project/Website.
- Write some code in the ".cs" file to generate the PDF file with some text for the button Click event.
The following are the details of the preceding procedure.
Step 1
- Create a new empty Website named "PDF_Generation".
- Right-click on the website and click on "Add Reference".
- Use the following sub steps in the "Reference Manager".
- Click on the Browse tab on the left side
- Click on the Browse button at the bottom
- Select the "iTextSharp.dll" from the system
- Click on the Add button
Finally it will look like:
Now click on the "OK" button and see the "Solution Explorer" where the "iTextSharp.dll" reference has been added to the "Bin" folder.
Step 2
- Add a new Page named GenerateFile.aspx.
- Add a Button with Onclick event (to generate the PDF) on the page.
- <asp:Button ID="btnGenerate" runat="server" Text="Generate PDF" OnClick="btnGenerate_Click" />
- Add the following 2 namespaces to the top of the ".cs" file:
- using iTextSharp.text;
- using iTextSharp.text.pdf;
- Write the code to generate the PDF file on click event of the button:
- protected void btnGenerate_Click(object sender, EventArgs e)
- {
- try
- {
- Document pdfDoc = new Document(PageSize.A4, 25, 10, 25, 10);
- PdfWriter pdfWriter = PdfWriter.GetInstance(pdfDoc, Response.OutputStream);
- pdfDoc.Open();
- Paragraph Text = new Paragraph("This is test file");
- pdfDoc.Add(Text);
- pdfWriter.CloseStream = false;
- pdfDoc.Close();
- Response.Buffer = true;
- Response.ContentType = "application/pdf";
- Response.AddHeader("content-disposition", "attachment;filename=Example.pdf");
- Response.Cache.SetCacheability(HttpCacheability.NoCache);
- Response.Write(pdfDoc);
- Response.End();
- }
- catch (Exception ex)
- { Response.Write(ex.Message); }
- }
Note: You can provide any name of the generated file and any text that you want to print in the PDF file. For example here I provided "filename=Example.pdf" and the text as "This is test file".
Step 3
- Run the page that will be like:
- Click on the "Generate PDF" button and save the "Example.pdf" file.
Result: Open the PDF file and see your text in the PDF file.