How to Generate a Runtime PDF in Landscape Page Mode in ASP.Net

I will explain here how to generate a runtime PDF in landscape page mode using Visual Studio Ultimate 2015 Preview.

Briefly, I will generate the runtime PDF using ITextSharp.

Note: I will use the "iTextSharp.dll" as a PDF generator library. You can download it from: Sourceforge and NuGet.

You can find it in the attached file in the "bin" folder of this article but the best way to add the ItextSharp is described in Step B.

Step A: Create a new website named "Website1".

new Website

Step B: Add the ItextSharp library from the NuGet package using the following sub-steps:

  1. Click on Tools

  2. NuGet Package Manager

  3. Manage NuGet Packages for Solution

ItextSharp

Then a popup windows will open like:

popup windows

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.

right pane

After the installation, you see the "Right" sign in left pane that indicates that library has been installed.

installation

You can also check it from the Solution Explorer.

solution explorer

Step C

  1. Add a button to default page named "Default.aspx" and change the text to "Generate PDF".

    Generate PDF

  2. Double-click on the button to generate an Onclick event (to generate the PDF) on the Form.

  3. Add the following 2 namespaces to the top of the ".cs" file:
    1. using iTextSharp.text;  
    2. using iTextSharp.text.pdf;  
    3. using System.IO; 
  4. Write the code to generate the PDF file on the click event of the button:
    1. protected void Button1_Click(object sender, EventArgs e)  
    2. {  
    3.     try  
    4.     {  
    5.         Document pdfDoc = new Document(PageSize.A4.Rotate(), 0, 0, 5, 0);  
    6.         PdfWriter pdfWriter = PdfWriter.GetInstance(pdfDoc, HttpContext.Current.Response.OutputStream);  
    7.         pdfDoc.Open();  
    8.         pdfDoc.Add(new Paragraph("This is Landscape Page"));   
    9.         pdfWriter.CloseStream = false;  
    10.         pdfDoc.Close();  
    11.         Response.Buffer = true;  
    12.         Response.ContentType = "application/pdf";  
    13.         Response.AddHeader("content-disposition""attachment;filename=Test.pdf");  
    14.         Response.Cache.SetCacheability(HttpCacheability.NoCache);  
    15.     }  
    16.     catch (Exception ex)  
    17.     {  
    18.     }  

    Here "PageSize.A4.Rotate()" is used for the landscape page.

    PageSize

    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".

Step D

  1. Run the page that will be like:

    Run

  2. Click on the "Generate PDF" button and open it.

    PDF

    Result:

    Result


Similar Articles