Create or Generate PDF file in ASP.NET MVC

4 Dec 202416 minutes to read

The Syncfusion® .NET PDF library is used to create, read, and edit PDF documents. This library also offers functionality to merge, split, stamp, forms and secure PDF files.

To include the .NET PDF library into your ASP.NET MVC application, please refer to the NuGet Package Required or Assemblies Required documentation.

Steps to create PDF document in ASP.NET MVC

Step 1: Create a new ASP.NET MVC application project.
Create ASP.NET MVC Web application in Visual Studio

Step 2: Install the Syncfusion.Pdf.AspNet.Mvc5 NuGet package as a reference to your ASP.NET MVC applications from NuGet.org.
Install PDF MVC NuGet package

NOTE

Starting with v16.2.0.x, if you reference Syncfusion® assemblies from trial setup or from the NuGet feed, you also have to add “Syncfusion.Licensing” assembly reference and include a license key in your projects. Please refer to this link to know about registering Syncfusion® license key in your application to use our components.

Step 3: A default controller with name HomeController.cs gets added on creation of ASP.NET MVC project. Include the following namespaces in that HomeController.cs file.

  • C#
  • using Syncfusion.Pdf;
    using Syncfusion.Pdf.Graphics;
    using System.Drawing;

    Step 4: A default action method named Index will be present in HomeController.cs. Right-click on this Index method and select Go To View where you will be directed to its associated view page Index.cshtml. Add a new button in the Index.cshtml as follows.

  • C#
  • @{Html.BeginForm("CreatePDFDocument", "Home", FormMethod.Get);
        {
            <div>
                <input type="submit" value="Generate PDF Document" style="width:150px;height:27px" />
            </div>
        }
        Html.EndForm();
    }

    Step 5: Add a new action method named CreatePDFDocument in HomeController.cs and include the below code example to generate a PDF document using the PdfDocument class. Then use the DrawString method of the PdfGraphics object to draw the text on the PDF page and download the output PDF from ASP.NET MVC application.

  • C#
  • //Create an instance of PdfDocument.
    using (PdfDocument document = new PdfDocument())
    {
    //Add a page to the document.
    PdfPage page = document.Pages.Add();
    //Create PDF graphics for the page.
    PdfGraphics graphics = page.Graphics;
    //Set the standard font.
    PdfFont font = new PdfStandardFont(PdfFontFamily.Helvetica, 20);
    //Draw the text.
    graphics.DrawString("Hello World!!!", font, PdfBrushes.Black, new PointF(0, 0));
    //Open the document in browser after saving it. 
    document.Save("Output.pdf", HttpContext.ApplicationInstance.Response, HttpReadType.Save);
    }

    By executing the program, you will get the PDF document as follows.
    ASP.Net Core output PDF document

    You can download a complete working sample from GitHub.

    Creating a PDF document with image

    Load image stream from the local files on disk and draw the images through the DrawImage method of the PdfGraphics class. The following code example shows how to create a PDF document with an image.

  • C#
  • //Create a new PDF document.
    PdfDocument doc = new PdfDocument();
    //Add a page to the document.
    PdfPage page = doc.Pages.Add();
    //Create PDF graphics for the page.
    PdfGraphics graphics = page.Graphics;
    //Load the image from the disk.
    PdfBitmap image = new PdfBitmap(Server.MapPath("~/Adventure Cycles.png"));
    //Draw the image.
    graphics.DrawImage(image, 0, 0);
    //Open the document in browser after saving it.
    doc.Save("Output.pdf", HttpContext.ApplicationInstance.Response, HttpReadType.Save);
    //Close the document.
    doc.Close(true);

    By executing the program, you will get the PDF document as follows.
    ASP.Net Core output PDF document

    You can download a complete working sample from GitHub.

    Creating a PDF document with table

    The PdfGrid allows you to create a table from a DataSource (data set, data table, arrays, or IEnumerable object) in a PDF document.The following code example shows how to create a PDF document with a simple table.

  • C#
  • //Create a new PDF document.
    PdfDocument doc = new PdfDocument();
    //Add a page.
    PdfPage page = doc.Pages.Add();
    //Create a PdfGrid.
    PdfGrid pdfGrid = new PdfGrid();
    //Create a DataTable.
    DataTable dataTable = new DataTable();
    //Add columns to the DataTable.
    dataTable.Columns.Add("ID");
    dataTable.Columns.Add("Name");
    //Add rows to the DataTable.
    dataTable.Rows.Add(new object[] { "E01", "Clay" });
    dataTable.Rows.Add(new object[] { "E02", "Thomas" });
    dataTable.Rows.Add(new object[] { "E03", "Andrew" });
    dataTable.Rows.Add(new object[] { "E04", "Paul" });
    dataTable.Rows.Add(new object[] { "E05", "Gary" });
    //Assign data source.
    pdfGrid.DataSource = dataTable;
    //Apply built-in table style
    pdfGrid.ApplyBuiltinStyle(PdfGridBuiltinStyle.GridTable4Accent1);
    //Draw grid to the page of PDF document.
    pdfGrid.Draw(page, new PointF(10, 10));
    //Open the document in browser after saving it.
    doc.Save("Output.pdf", HttpContext.ApplicationInstance.Response, HttpReadType.Save);
    //Close the document.
    doc.Close(true);

    By executing the program, you will get the PDF document as follows.
    ASP.Net Core output PDF document

    You can download a complete working sample from GitHub.

    Creating a simple PDF document with basic elements

    The PdfDocument object represents an entire PDF document that is being created. The following code example shows how to generate a PDF document and add a PdfPage to it along with the PdfPageSettings.

  • C#
  • //Generate a new PDF document.
    PdfDocument document = new PdfDocument();
    //Adds page settings.
    document.PageSettings.Orientation = PdfPageOrientation.Landscape;
    document.PageSettings.Margins.All = 50;
    //Adds a page to the document.
    PdfPage page = document.Pages.Add();
    PdfGraphics graphics = page.Graphics;
    1. Essential® PDF has APIs similar to the .NET GDI plus which helps to draw elements to the PDF page just like 2D drawing in .NET.
    2. Unlike System.Drawing APIs all the units are measured in point instead of pixel.
    3. In PDF, all the elements are placed in absolute positions and has the possibility for content overlapping if misplaced.
    4. Essential® PDF provides the rendered bounds for each and every elements added through PdfLayoutResult objects. This can be used to add successive elements and prevent content overlap.

    The following code example explains how to add an image from disk to a PDF document, by providing the rectangle coordinates.

  • C#
  • //Loads the image from disk.
    PdfImage image = PdfImage.FromFile(Server.MapPath("~/AdventureCycle.jpg"));
    RectangleF bounds = new RectangleF(176, 0, 390, 130);
    //Draws the image to the PDF page.
    page.Graphics.DrawImage(image, bounds);

    The following methods can be used to add text to a PDF document.

    1. DrawString() method of the PdfGraphics
    2. PdfTextElement class.

    The PdfTextElement provides the layout result of the added text by using the location of the next element that decides to prevent content overlapping. This is not available in the DrawString method.

    The following code example adds the necessary text such as address, invoice number and date to create a basic invoice application.

  • C#
  • PdfBrush solidBrush = new PdfSolidBrush(new PdfColor(126, 151, 173));
    bounds = new RectangleF(0, bounds.Bottom + 90, graphics.ClientSize.Width, 30);
    //Draws a rectangle to place the heading in that region.
    graphics.DrawRectangle(solidBrush, bounds);
    //Creates a font for adding the heading in the page
    PdfFont subHeadingFont = new PdfStandardFont(PdfFontFamily.TimesRoman, 14);
    //Creates a text element to add the invoice number
    PdfTextElement element = new PdfTextElement("INVOICE " + id.ToString(), subHeadingFont);
    element.Brush = PdfBrushes.White;
    
    //Draws the heading on the page
    PdfLayoutResult result = element.Draw(page, new PointF(10, bounds.Top + 8));
    string currentDate = "DATE " + DateTime.Now.ToString("MM/dd/yyyy");
    //Measures the width of the text to place it in the correct location
    SizeF textSize = subHeadingFont.MeasureString(currentDate);
    PointF textPosition = new PointF(graphics.ClientSize.Width - textSize.Width - 10, result.Bounds.Y);
    //Draws the date by using DrawString method
    graphics.DrawString(currentDate, subHeadingFont, element.Brush, textPosition);
    PdfFont timesRoman = new PdfStandardFont(PdfFontFamily.TimesRoman, 10);
    //Creates text elements to add the address and draw it to the page.
    element = new PdfTextElement("BILL TO ", timesRoman);
    element.Brush = new PdfSolidBrush(new PdfColor(126, 155, 203));
    result = element.Draw(page, new PointF(10, result.Bounds.Bottom + 25));
    PdfPen linePen = new PdfPen(new PdfColor(126, 151, 173), 0.70f);
    PointF startPoint = new PointF(0, result.Bounds.Bottom + 3);
    PointF endPoint = new PointF(graphics.ClientSize.Width, result.Bounds.Bottom + 3);
    //Draws a line at the bottom of the address
    graphics.DrawLine(linePen, startPoint, endPoint);

    Essential® PDF provides two types of table models. The difference between both the table models can be referred from the link
    Difference between PdfLightTable and PdfGrid

    Since the invoice document requires only simple cell customizations, the given code example explains how to create a simple invoice table by using PdfGrid.

  • C#
  • //Creates the datasource for the table
    DataTable invoiceDetails = GetProductDetailsAsDataTable();
    //Creates a PDF grid
    PdfGrid grid = new PdfGrid();
    //Adds the data source
    grid.DataSource = invoiceDetails;
    //Creates the grid cell styles
    PdfGridCellStyle cellStyle = new PdfGridCellStyle();
    cellStyle.Borders.All = PdfPens.White;
    PdfGridRow header = grid.Headers[0];
    //Creates the header style
    PdfGridCellStyle headerStyle = new PdfGridCellStyle();
    headerStyle.Borders.All = new PdfPen(new PdfColor(126, 151, 173));
    headerStyle.BackgroundBrush = new PdfSolidBrush(new PdfColor(126, 151, 173));
    headerStyle.TextBrush = PdfBrushes.White;
    headerStyle.Font = new PdfStandardFont(PdfFontFamily.TimesRoman, 14f, PdfFontStyle.Regular);
    
    //Adds cell customizations
    for (int i = 0; i < header.Cells.Count; i++)
    {
      if (i == 0 || i == 1)
        header.Cells[i].StringFormat = new PdfStringFormat(PdfTextAlignment.Left, PdfVerticalAlignment.Middle);
      else
        header.Cells[i].StringFormat = new PdfStringFormat(PdfTextAlignment.Right, PdfVerticalAlignment.Middle);
    }
    
    //Applies the header style.
    header.ApplyStyle(headerStyle);
    cellStyle.Borders.Bottom = new PdfPen(new PdfColor(217, 217, 217), 0.70f);
    cellStyle.Font = new PdfStandardFont(PdfFontFamily.TimesRoman, 12f);
    cellStyle.TextBrush = new PdfSolidBrush(new PdfColor(131, 130, 136));
    //Creates the layout format for grid.
    PdfGridLayoutFormat layoutFormat = new PdfGridLayoutFormat();
    //Creates layout format settings to allow the table pagination.
    layoutFormat.Layout = PdfLayoutType.Paginate;
    //Draws the grid to the PDF page.
    PdfGridLayoutResult gridResult = grid.Draw(page, new RectangleF(new PointF(0, result.Bounds.Bottom + 40), new SizeF(graphics.ClientSize.Width, graphics.ClientSize.Height - 100)), layoutFormat);

    The following code example shows how to save the invoice document to disk and dispose the PdfDocument object.

  • C#
  • //Open the document in browser after saving it.
    document.Save("Output.pdf", HttpContext.ApplicationInstance.Response, HttpReadType.Save);
    document.Close(true);

    You can download a complete working sample from GitHub.

    The following screenshot shows the invoice PDF document created by using Essential® PDF.
    Invoice PDF document

    Filling forms

    An interactive form, sometimes referred to as an AcroForm, is a collection of fields for gathering information interactively from the user. A PDF document or existing PDF document contain any number of fields appearing in any combination of pages, all that make a single, globally interactive form spanning the entire document.

    The Essential® PDF allows you to create and manipulate existing form in PDF document using the PdfForm class. The PdfLoadedFormFieldCollection class represents the entire field collection of the loaded form.. To work with existing form documents, the following namespaces are required.

    1. Syncfusion.Pdf
    2. Syncfusion.Pdf.Parsing

    The following guide shows how to fill out a sample PDF form.
    Sample PDF form

    The .NET Core PDF library allows you to fill the form fields by using the PdfLoadedField class. Get the form field either by using its field name or field index.

  • C#
  • //Loads the PDF document.
    PdfLoadedDocument loadedDocument = new PdfLoadedDocument(Server.MapPath("~/JobApplication.pdf"));
    //Loads the form.
    PdfLoadedForm form = loadedDocument.Form;
    //Fills the textbox field by using index.
    (form.Fields[0] as PdfLoadedTextBoxField).Text = "John";
    //Fills the textbox fields by using field name.
    (form.Fields["LastName"] as PdfLoadedTextBoxField).Text = "Doe";
    (form.Fields["Address"] as PdfLoadedTextBoxField).Text = " John Doe \n 123 Main St \n Anytown, USA";
    //Loads the radio button group.
    PdfLoadedRadioButtonItemCollection radioButtonCollection = (form.Fields["Gender"] as PdfLoadedRadioButtonListField).Items;
    //Checks the 'Male' option.
    radioButtonCollection[0].Checked = true;
    //Checks the 'business' checkbox field.
    (form.Fields["Business"] as PdfLoadedCheckBoxField).Checked = true;
    //Checks the 'retiree' checkbox field.
    (form.Fields["Retiree"] as PdfLoadedCheckBoxField).Checked = true;
    // Open the document in browser after saving it.
    loadedDocument.Save("Output.pdf", HttpContext.ApplicationInstance.Response, HttpReadType.Save);
    loadedDocument.Close(true);

    You can download a complete working sample from GitHub.

    The filled form is shown in adobe reader application as follows.
    Filled PDF form

    Merge PDF Documents

    The Essential® PDF supports merging multiple PDF documents from disk and stream using Merge method of the PdfDocumentBase class. You can merge the multiple PDF documents from disk by specifying the path of the documents in a string array.

    Refer to the following code example to merge multiple documents from disk.

  • C#
  • //Creates the new PDF document.
    PdfDocument finalDoc = new PdfDocument();
    //Creates a string array of source files to be merged.
    string[] source = System.IO.Directory.GetFiles(Server.MapPath("~/DataFolder"),"*.pdf");
    //Merges PDFDocument.
    PdfDocument.Merge(finalDoc, source);
    //Open the document in browser after saving it.
    finalDoc.Save("Output.pdf", HttpContext.ApplicationInstance.Response, HttpReadType.Save);
    //Closes the document.
    finalDoc.Close(true);

    You can download a complete working sample from GitHub.

    You can merge the PDF document streams by using the following code example.

  • C#
  • //Creates the destination document.
    PdfDocument finalDoc = new PdfDocument();
    Stream stream1 = System.IO.File.OpenRead(Server.MapPath("~/file1.pdf"));
    Stream stream2 = System.IO.File.OpenRead(Server.MapPath("~/file2.pdf"));
    //Creates a PDF stream for merging.
    Stream[] streams = { stream1, stream2 };
    //Merges PDFDocument.
    PdfDocumentBase.Merge(finalDoc, streams);
    //Open the document in browser after saving it.
    finalDoc.Save("Output.pdf", HttpContext.ApplicationInstance.Response, HttpReadType.Save);
    //Closes the document.
    finalDoc.Close(true);

    Click here to explore the rich set of Syncfusion® PDF library features.

    An online sample link to create PDF document in ASP.NET MVC.