Creating and downloading a PDF or DOCX in ASP.NET Core

The post shows how a PDF can be created from data in an ASP.NET Core backend and downloaded using an API. The data could be loaded from different locations and exported then as a PDF or a docx or whatever you require.

Code: https://github.com/damienbod/AspNetCoreCreatePdf

Why GemBox?

There are many different tools to generate PDF all with advantages and disadvantages. I required a tool to download PDFs created in an ASP.NET Core backend using data from a database. This was recommended to me and after trying this out, I think this is a good choice. GemBox.document has a good licensing model, it is simple to use and it provides PDF signing. You can create different formats direct from C# data classes. It is easy to use and does not require a windows host environment.

Import the GemBox Nuget package

The GemBox.Document Nuget package is added to project and you have everything you require.

Note:

If deploying to Linux, add the HarfBuzzSharp.NativeAssets.Linux Nuget package as well.

Create an API to download PDF/Docx

The download controller is used as the public API. This class has two methods, one for downloading the data as a PDF and a second method to download the same data as a docx file.

public class DownloadController(DocumentService _documentService) : ControllerBase
{
  [Route("pdf/{id}")]
  [HttpGet]
  public FileStreamResult DownloadPdf(string id)
  {
    var stream = _documentService.GeneratePdf(id);
    return File(stream, "application/pdf");
  }

  [Route("docx/{id}")]
  [HttpGet]
  public FileStreamResult DownloadDocx(string id)
  {
    var stream = _documentService.GenerateDocx(id);
    return File(stream, 
     "application/vnd.openxmlformats-officedocument.wordprocessingml.document");
  }
}

The Document service class implements the document specification. This service uses data from a C# DTO and creates a GemBox document which can be exported to many different formats.

using GemBox.Document;

namespace ApiCreatePdf;

public class DocumentService
{

public Stream GeneratePdf(string id)
{
    var documentData = GetDocumentData(id, SaveOptions.PdfDefault);
    
    var pdf = new MemoryStream();
    var document = CreateDocument(documentData);

    document.Save(pdf, SaveOptions.PdfDefault);

    return pdf;
}

public Stream GenerateDocx(string id)
{
    var documentData = GetDocumentData(id, SaveOptions.DocxDefault);

    var docx = new MemoryStream();
    var document = CreateDocument(documentData);

    document.Save(docx, SaveOptions.DocxDefault);

    return docx;
}

private static DocumentModel CreateDocument(DocumentData documentData)
{
    // If using the Professional version, put your serial key below.
    ComponentInfo.SetLicense("FREE-LIMITED-KEY");

    var document = new DocumentModel();

    var section = new Section(document);
    document.Sections.Add(section);

    // Main text 
    var paragraph = new Paragraph(document);
    section.Blocks.Add(paragraph);
    var run = new Run(document, documentData.MainContentText);
    paragraph.Inlines.Add(run);

    var bookmarkName = "TopOfDocument";

    document.Sections.Add(
        new Section(document,
            new Paragraph(document,
                new BookmarkStart(document, bookmarkName),
                new Run(document, "This is a 'TopOfDocument' bookmark."),
                new BookmarkEnd(document, bookmarkName)),
            new Paragraph(document,
                new Run(document, "The following is a link to "),
                new Hyperlink(document, "https://www.gemboxsoftware.com/document", "GemBox.Document Overview"),
                new Run(document, " page.")),
             new Paragraph(document,
                new SpecialCharacter(document, SpecialCharacterType.PageBreak),
                new Run(document, "This is a document's second page."),
                new SpecialCharacter(document, SpecialCharacterType.LineBreak),
                new Hyperlink(document, bookmarkName, "Return to 'TopOfDocument'.") { IsBookmarkLink = true })));

    return document;
}

private DocumentData GetDocumentData(string id, SaveOptions docType)
{
    return new DocumentData
    {
        MainContentText = $"{docType.ContentType} created for id: {id}"
    };
}

}

Downloading files

When the application is started, a PDF or a docx file can be downloaded and opened. the data can come from the database or anywhere. This is just a demo and when using data from user inputs and returning it to the clients, the data needs to be validated and sanitized.

Links

https://www.gemboxsoftware.com/document

https://www.nuget.org/packages/GemBox.Document/

https://github.com/GemBoxLtd/GemBox.Document.Examples

4 comments

  1. […] Creating and downloading a PDF or DOCX in ASP.NET Core (Damien Bowden) […]

  2. […] Creating and downloading a PDF or DOCX in ASP.NET Core – Damien Bowden […]

  3. Ryan Rivera · · Reply

    You might want to try ZetPDF.com for generating PDF files in C#. It has worked well for me.

    1. Thanks for the tip, will have a look at it

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.