Content
I will explain how to add a new page into a runtime generated PDF functionality using Visual Studio Ultimate 2015 Preview.
I will briefly generate the runtime PDF using ITextSharp.
Note: I will use the "iTextSharp.dll" as a PDF generator library. You can download it from itextsharp and iTextSharp.
You can find it on the attached file in "bin" folder of this article but the best way to add the ItextSharp is in Step B.
Step A
Create a new Website named "Website1".
Step B
Add the ItextSharp library from NuGet package using the following sub-steps:
- Click on Tools
- NuGet Package Manager
- Manage NuGet Packages for Solution.
Then a popup window will open like:
Type "ItextSharp" into the Search TextBox. Then you will get the "ItextSharp" library in the left pane. To add it to the website just click on the Install button of the right pane.
After the installation, you see the "Right" sign in the left pane that indicates that the library has been installed.
You can also check it from the Solution Explorer.
Step C
- Add a button to the default page named "Default.aspx" and change the text to "Generate PDF".
- Double-click on the button to generate an Onclick event (to generate the PDF) on the Form.
- Add the following 2 namespaces to the top of the ".cs" file:
- using iTextSharp.text;
- using iTextSharp.text.pdf;
- using System.IO;
- Write the code to generate the PDF file on the click event of the button:
- protected void Button1_Click(object sender, EventArgs e)
- {
- try
- {
- Document document = new Document();
- PdfWriter.GetInstance(document, new FileStream("E:/Rahul/test.pdf", FileMode.Create));
- document.Open();
- Paragraph p1 = new Paragraph("This is First Page");
- document.Add(p1);
- document.NewPage();
- Paragraph p2 = new Paragraph("This is Second Page");
- document.Add(p2);
- document.Close();
- }
- catch (Exception ex)
- {
- }
- }
Here "document.NewPage()" is used for adding a new page.
Note
You can provide any name for the generated file and any text that you want to print in the PDF file. For example here I provided "test.pdf" and path also.
Step D
- Run the page that will be like:
- Click on the the "Generate PDF" button.
Result
- Follow the specified path and open the folder, you will see the PDF file.
- Open the PDF file and see the both pages in the PDF file.
Page 1
Page 2