10

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

 10 months ago
source link: https://damienbod.com/2024/06/05/creating-and-downloading-a-pdf-or-docx-in-asp-net-core/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

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.

aspnetcore_pdf_gembox_01.png?w=734

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.

aspnetcore_pdf_gembox_02.png?w=1024

Links

https://www.gemboxsoftware.com/document

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

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


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK