Windows Forms: How to Create a PDF document file in C#

This post shows you How to Create a PDF document file using iTextSharp in C#

Creating a PDF document in C# using iTextSharp involves several steps. First, ensure you have iTextSharp installed in your project.

How to Create a PDF document file using iTextSharp in C#

Open your Visual Studio, then click New Project -> Select Visual C# on the left, then Windows and then select Windows Forms Application. Enter your project name is "MakePdf" and then click OK button.

You can install it via NuGet Package Manager in Visual Studio by right-clicking on your project select Manage NuGet Packages -> Search itextsharp -> Install

c# itextsharp

iText is a PDF library that allows you to CREATE, ADAPT, INSPECT and MAINTAIN documents in the Portable Document Format (PDF), allowing you to add PDF functionality to your software projects with ease.  We even have documentation to help you get coding.

Once installed, you can follow these steps to create a PDF document.

Drag and drop RichTexBox, Button controls from the Visual Studio toolbox onto your form desiger, then you can design a simple UI as below

c# create pdf file

Add a click event handler to the Save button allows you to export pdf file from text in c#

// c# create pdf file
private void btnSave_Click(object sender, EventArgs e)
{
    // Set the file path where you want to save the PDF using SaveFileDialog
    using (SaveFileDialog sfd = new SaveFileDialog() { Filter = "PDF file|*.pdf", ValidateNames = true })
    {
        if (sfd.ShowDialog() == DialogResult.OK)
        {
            // Create a document
            iTextSharp.text.Document doc = new iTextSharp.text.Document(PageSize.A4.Rotate());
            try
            {
                // Create a PdfWriter instance to write the document to the file
                PdfWriter.GetInstance(doc, new FileStream(sfd.FileName, FileMode.Create));
                doc.Open();
                // Add content to the document
                doc.Add(new iTextSharp.text.Paragraph(richTextBox.Text));
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Message", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            finally
            {
                doc.Close();
            }
        }
    }
}

This code will create a PDF file with the text from RichTextBox control. It's a simple PDF document created using iTextSharp in C#

VIDEO TUTORIALS