Generate PDF File at Runtime in Windows Forms Application


For generating a 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:

1. Links

2. You can find it on the attached file in the "bin\Debug" folder of this article.

To explain this article, I will use the following procedure:

  1. Add a reference of the downloaded "iTextSharp.dll" to the Windows Forms Application.

  2. Write some code in the ".cs" file to generate the PDF file with some text for the button's Click event.

The following are the details of the preceding procedure.

Step 1

  1. Create a new Windows Forms Application named "WindowsFormsApplication1".

    window form application

  2. Right-click on the "References" in the Solution Explorer and click on "Add Reference".

    Add Reference

  3. Use the following sub-procedure in the "Reference Manager".

    1. Click on the the Browse tab on the left side.
    2. Click on the Browse button at the bottom.
    3. Select the "iTextSharp.dll" from the system.
    4. Click on the Add button.

    Add button

    Finally it will look like:

    dll file

    Now click on the "OK" button and in the "Solution Explorer" you will see that the "iTextSharp.dll" reference has been added.


Step 2

  1. Add a button in the default form named "Form1" and make some changes like make text as "Generate PDF’ and increase the width and height of the button.

    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. Document document = new Document();  
    2. PdfWriter.GetInstance(document, new FileStream("E:/a.pdf", FileMode.Create));  
    3. document.Open();  
    4. Paragraph p = new Paragraph("Test");  
    5. document.Add(p);  
    6. document.Close(); 
    PDF file

    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 "A.pdf" and the text as "This is test PDF" and the path also.

Step 3

  1. Run the page and it will be like:

    Run the page

  2. Click on the "Generate PDF" button.


  1. Follow the specified path and open the folder, you will see the PDF file.

    PDF file Folder

  2. Open the PDF file and see your text in the PDF file.

    text in the PDF file

Similar Articles