The article explains how to convert HTML to PDF with Microsoft .Net Core 2.1 using Microsoft.AspNetCore.NodeServices to execute Node.js modules for conversion. The demo is created using an .NetCore console application.
Microsoft.AspNetCore.NodeServices
NodeServices provides a fast and robust way for .NET code to run JavaScript on the server inside a Node.js environment. These services can be used to consume arbitrary functionality from NPM packages at runtime in a ASP.NET Core app.
html-pdf (https://www.npmjs.com/package/html-pdf)
HTML to PDF converter uses phantomjs. This is an NPM package which can be used in NodeJs enviroment to convert HTML to pdf files. In this demo we do not explore all the options available with this package. The aim is to understand a very basic usage of package.
Application Walkthrough
NodeJs
Install Node.js enviroment on your machine following the steps from https://nodejs.org/en/
After installation you can verfiy by executing the following command in the command line:
package.json
- {
- "version": "1.0.0",
- "name": "exp.pdfgen",
- "private": true,
- "dependencies": {
- "html-pdf": "^2.2.0"
- }
- }
The file indicates the dependencies required to be downloaded. To install them copy the contents into the package.json file and execute the below command from command line.
After execution of the command, you will see node_modules folder created which will contain the node dependencies.
generatePDF.js
This is a small module, which will be invoked by our application. This refers to the node_modules folder for dependencies.
This will read the html file, and pass and invoke the html-pdf module with the appropriate options and parameters.
- module.exports = function (callback, inputFilePath, outputFilePath) {
-
-
-
-
-
-
- var fs = require('fs');
- var pdf = require('html-pdf');
- var html = fs.readFileSync(inputFilePath, 'utf8');
- var options = { format: 'Letter' };
-
-
- pdf.create(html, options).toFile(outputFilePath, function (err, res) {
- if (err) return callback(null, "Failed to generate PDF");
- callback(null, "Generated PDF Successfully");
- });
-
- }
Application Code
The paths mentioned can be changed as per your directory structure. To keep the article simple, publishing the node_modules and the project to relative paths is not done.
- using System;
- using System.Threading.Tasks;
- using Microsoft.AspNetCore.NodeServices;
- using Microsoft.Extensions.DependencyInjection;
-
- namespace exp.pdfgen
- {
- class Program
- {
- static void Main(string[] args)
- {
-
- var serviceCollection = new ServiceCollection();
-
-
- serviceCollection.AddNodeServices();
-
-
- var serviceProvider = serviceCollection.BuildServiceProvider();
- var nodeService = serviceProvider.GetRequiredService<INodeServices>();
-
-
-
- var inputFilePath = "D:\\Repository\\NetCore\\experiments\\exp\\exp.pdfgen\\sample.html";
-
-
- var outputFilePath = "D:\\Repository\\NetCore\\experiments\\exp\\exp.pdfgen\\sampleOutput.pdf";
-
- var taskResult = GeneratePdf(nodeService, inputFilePath, outputFilePath);
-
- Task.WaitAll(taskResult);
-
- if (taskResult.IsCompletedSuccessfully)
- {
- Console.WriteLine(taskResult.Result);
- }
-
- Console.ReadKey();
- }
-
- private static async Task<string> GeneratePdf(INodeServices nodeService, string inputFilePath, string outputFilePath)
- {
-
-
- return await nodeService.InvokeAsync<string>(@"D:\\Repository\\NetCore\\experiments\\exp\\exp.pdfgen\\generatePDF.js", inputFilePath, outputFilePath);
-
- }
-
-
- }
- }
Sample.html
- <html>
-
- <body>
- <p>This is Sample Text</p>
- <p style="font:20px;color:magenta;">This is Colored Text</p>
-
- </body>
-
- </html>
Output
I hope the article helps you understand how to use Node.js based modules like html-pdf to generate PDF from HTML from .NetCore applications.