27 Sep 202217 minutes to read
The Syncfusion .NET Core 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 Core PDF library into your ASP.NET Core application, please refer to the NuGet Package Required or Assemblies Required documentation.
Steps to create PDF document in ASP.NET Core
Create a new C# ASP.NET Core Web Application project.
Select Web Application pattern (Model-View-Controller) for the project.
Install the Syncfusion.Pdf.Net.Core NuGet package as reference to your ASP.NET Core applications from NuGet.org.
A default controller with name HomeController.cs gets added on creation of ASP.NET Core project. Include the following namespaces in that HomeController.cs file.
using Syncfusion.Pdf;using Syncfusion.Pdf.Graphics;using Syncfusion.Drawing;using System.IO;
A default action method named Index will be present in HomeController.cs. Right click on 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 shown below.
@{Html.BeginForm("CreatePDFDocument", "Home", FormMethod.Get);{<div> <input type="submit" value="Generate PDF Document" style="width:150px;height:27px" /></div>}Html.EndForm();}
Add a new action method CreatePDFDocument in HomeController.cs and include the below code snippet to generate a PDF file and download it from a ASP.NET Core application.
//Create a new PDF documentPdfDocument document = new PdfDocument(); //Add a page to the documentPdfPage page = document.Pages.Add(); //Create PDF graphics for the pagePdfGraphics graphics = page.Graphics; //Set the standard fontPdfFont font = new PdfStandardFont(PdfFontFamily.Helvetica, 20); //Draw the textgraphics.DrawString("Hello World!!!", font, PdfBrushes.Black, new PointF(0, 0)); //Saving the PDF to the MemoryStreamMemoryStream stream = new MemoryStream(); document.Save(stream); //Set the position as '0'.stream.Position = 0; //Download the PDF document in the browserFileStreamResult fileStreamResult = new FileStreamResult(stream, "application/pdf"); fileStreamResult.FileDownloadName = "Sample.pdf"; return fileStreamResult;
A complete work sample can be downloaded from Create-PDF-file.zip
You can download a complete working sample from GitHub.
By executing the program, you will get the PDF document as follows.
NOTE
The WinForms and WPF controls support in .NET Core 3.0 have been provided. To run this application, please install the System.Drawing.Common NuGet package as a dependent package.
Creating a PDF document with image
The following code example shows how to create a PDF document with an image.
//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 pagePdfGraphics graphics = page.Graphics;//Load the image as stream.FileStream imageStream = new FileStream("Autumn Leaves.jpg", FileMode.Open, FileAccess.Read);PdfBitmap image = new PdfBitmap(imageStream);//Draw the imagegraphics.DrawImage(image, 0, 0);//Save the PDF document to streamMemoryStream stream = new MemoryStream();doc.Save(stream);//If the position is not set to '0' then the PDF will be empty.stream.Position = 0;//Close the document.doc.Close(true);//Defining the ContentType for pdf file.string contentType = "application/pdf";//Define the file name.string fileName = "Output.pdf";//Creates a FileContentResult object by using the file contents, content type, and file name.return File(stream, contentType, fileName);
You can download a complete working sample from GitHub.
Creating a PDF document with table
The following code example shows how to create a PDF document with a simple table.
//Generate a new PDF document.PdfDocument doc = new PdfDocument();//Add a page.PdfPage page = doc.Pages.Add();//Create a PdfGrid.PdfGrid pdfGrid = new PdfGrid();//Add values to listList<object> data = new List<object>();Object row1 = new { ID = "E01", Name = "Clay" };Object row2 = new { ID = "E02", Name = "Thomas" };Object row3 = new { ID = "E03", Name = "Andrew" };Object row4 = new { ID = "E04", Name = "Paul" };Object row5 = new { ID = "E05", Name = "Gray" };data.Add(row1);data.Add(row2);data.Add(row3);data.Add(row4);data.Add(row5);//Add list to IEnumerableIEnumerable<object> dataTable = data;//Assign data source.pdfGrid.DataSource = dataTable;//Draw grid to the page of PDF document.pdfGrid.Draw(page, new Syncfusion.Drawing.PointF(10, 10));//Write the PDF document to streamMemoryStream stream = new MemoryStream();doc.Save(stream);//If the position is not set to '0' then the PDF will be empty.stream.Position = 0;//Close the document.doc.Close(true);//Defining the ContentType for pdf file.string contentType = "application/pdf";//Define the file name.string fileName = "Output.pdf";//Creates a FileContentResult object by using the file contents, content type, and file name.return File(stream, contentType, fileName);
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.
//Creates a new PDF documentPdfDocument document = new PdfDocument();//Adds page settingsdocument.PageSettings.Orientation = PdfPageOrientation.Landscape;document.PageSettings.Margins.All = 50;//Adds a page to the documentPdfPage page = document.Pages.Add();PdfGraphics graphics = page.Graphics;
- 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.
- Unlike System.Drawing APIs all the units are measured in point instead of pixel.
- In PDF, all the elements are placed in absolute positions and has the possibility for content overlapping if misplaced.
- 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.
//Loads the image as streamFileStream imageStream = new FileStream("AdventureCycle.jpg", FileMode.Open, FileAccess.Read);RectangleF bounds = new RectangleF(176, 0, 390, 130);PdfImage image = PdfImage.FromStream(imageStream);//Draws the image to the PDF pagepage.Graphics.DrawImage(image, bounds);
The following methods can be used to add text to a PDF document.
- DrawString() method of the PdfGraphics
- 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.
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 pagePdfFont subHeadingFont = new PdfStandardFont(PdfFontFamily.TimesRoman, 14);//Creates a text element to add the invoice numberPdfTextElement element = new PdfTextElement("INVOICE " + id.ToString(), subHeadingFont);element.Brush = PdfBrushes.White;//Draws the heading on the pagePdfLayoutResult 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 locationSizeF textSize = subHeadingFont.MeasureString(currentDate);PointF textPosition = new PointF(graphics.ClientSize.Width - textSize.Width - 10, result.Bounds.Y);//Draws the date by using DrawString methodgraphics.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 addressgraphics.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.
//Creates the datasource for the tableDataTable invoiceDetails = GetProductDetailsAsDataTable();//Creates a PDF gridPdfGrid grid = new PdfGrid();//Adds the data sourcegrid.DataSource = invoiceDetails;//Creates the grid cell stylesPdfGridCellStyle cellStyle = new PdfGridCellStyle();cellStyle.Borders.All = PdfPens.White;PdfGridRow header = grid.Headers[0];//Creates the header stylePdfGridCellStyle 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 customizationsfor (int i = 0; i < header.Cells.Count; i++){if (i == 0 || i == 1)header.Cells[i].StringFormat = new PdfStringFormat(PdfTextAlignment.Left, PdfVerticalAlignment.Middle);elseheader.Cells[i].StringFormat = new PdfStringFormat(PdfTextAlignment.Right, PdfVerticalAlignment.Middle);}//Applies the header styleheader.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 gridPdfGridLayoutFormat layoutFormat = new PdfGridLayoutFormat();// Creates layout format settings to allow the table paginationlayoutFormat.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.
FileStream fileStream = new FileStream("Sample.pdf", FileMode.CreateNew, FileAccess.ReadWrite);//Save and close the PDF document document.Save(fileStream);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.
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 can contain any number of fields appearing in any combination of pages, all of that make a single, globally interactive form spanning the entire document.
.NET Core PDF library allows you to create and manipulate existing form in PDF document. To work with existing form documents, the following namespaces are required.
- Syncfusion.Pdf
- Syncfusion.Pdf.Parsing
The following guide shows how to fill a sample PDF form as shown.
.NET Core PDF library allows you to fill the form fields by using PdfLoadedField class. You can get the form field either by using its field name or field index.
//Load the PDF documentFileStream docStream = new FileStream("JobApplication.pdf", FileMode.Open, FileAccess.Read);PdfLoadedDocument loadedDocument = new PdfLoadedDocument(docStream);//Loads the formPdfLoadedForm 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 groupPdfLoadedRadioButtonItemCollection radioButtonCollection = (form.Fields["Gender"] as PdfLoadedRadioButtonListField).Items;//Checks the 'Male' optionradioButtonCollection[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;//Write the PDF document to streamMemoryStream stream = new MemoryStream();loadedDocument.Save(stream);//If the position is not set to '0' then the PDF will be empty.stream.Position = 0;//Close the document.loadedDocument.Close(true);//Defining the ContentType for pdf file.string contentType = "application/pdf";//Define the file name.string fileName = "output.pdf";//Creates a FileContentResult object by using the file contents, content type, and file name.return File(stream, contentType, fileName);
You can download a complete working sample from GitHub.
The filled form is shown in adobe reader application as follows.
Merge PDF Documents
.NET Core PDF library supports merging multiple PDF documents from stream using Merge method.
You can merge the PDF document streams by using the following code example.
//Generate a PDF documentPdfDocument finalDoc = new PdfDocument();FileStream stream1 = new FileStream("file1.pdf", FileMode.Open, FileAccess.Read);FileStream stream2 = new FileStream("file2.pdf", FileMode.Open, FileAccess.Read);// Creates a PDF stream for mergingStream[] streams = { stream1, stream2 };// Merges PDFDocument.PdfDocumentBase.Merge(finalDoc, streams);//Save the PDF document to streamMemoryStream stream = new MemoryStream();finalDoc.Save(stream);//If the position is not set to '0' then the PDF will be empty.stream.Position = 0;//Close the document.finalDoc.Close(true);//Defining the ContentType for pdf file.string contentType = "application/pdf";//Define the file name.string fileName = "sample.pdf";//Creates a FileContentResult object by using the file contents, content type, and file name.return File(stream, contentType, fileName);
You can download a complete working sample from GitHub.
NOTE
You can also explore our .NET Core PDF library demo that shows how to create and modify PDF files from C# with just five lines of code.