How to convert HTML to a PDF using React Application?
The HTML-to-PDF convertor is a .NET PDF library for converting webpages, SVG MHTML and HTML files to PDF using C# in React. It uses the popular rendering engine Blink (Google Chrome). It is reliable and accurate. The result preserves all graphics, images, text, fonts, and the layout of the original HTML document or webpage.
Using this library you can convert the HTML to PDF using React application.
Steps to convert HTML to a PDF using React Application
- Create a new react application in the Net core project.
- Create a new HtmltoPdf API controller in the controller folder.
- Use the following code samples in NavMenu.js to create a button.
<navitem>
<navlink tag="{Link}" classname="text-dark" to="/fetch-data">Create PDF</navlink>
</navitem>
- Use the following code samples in fetchData.js.
constructor(props) {
super(props);
this.state = { forecasts: [], loading: true };
let htmlHead = document.head.innerHTML;
let htmlBody = document.body.innerHTML;
let htmlPage = htmlHead + htmlBody;
console.log(htmlPage);
request
.post('/api/HtmltoPdf/test')
.set('Content-Type', 'application/x-www-form-urlencoded')
.send({ test: htmlPage.toString() })
.end(function (err, res) {
console.log(res.text);
});
}
render() {
let contents = this.state.loading
? <p><em>Creating a PDF document using our syncfusion library. PDF document is ready.</em></p>
: FetchData.renderForecastsTable(this.state.forecasts);
return (
<div>
<h1>Welcome to React App</h1>
{contents}
</div>
);
}
- Include the following namespaces in the HtmltoPdfController.cs file.
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Syncfusion.HtmlConverter;
using Syncfusion.Pdf;
using System.IO;
- Add a hostingEnvironment in the HtmltoPdfController.cs file and include the following code example.
private readonly IHostingEnvironment _hostingEnvironment;
public HtmltoPdfController(IHostingEnvironment hostingEnvironment)
{
_hostingEnvironment = hostingEnvironment;
}
- Add a new method named test in the HtmltoPdfController.cs file and include the following code example to convert HTML to a PDF document in HtmltoPdfController.cs.
[HttpPost("test")]
public void test(string test)
{
string PdfFolderPath = Path.Combine(_hostingEnvironment.ContentRootPath);
string PdfFilePath = string.Empty;
PdfFilePath = PdfFolderPath + "\\" + "ReactSample.pdf";
//Initialize the HTML to PDF converter with the Blink rendering engine.
HtmlToPdfConverter htmlConverter = new HtmlToPdfConverter(HtmlRenderingEngine.Blink);
BlinkConverterSettings blinkConverterSettings = new BlinkConverterSettings();
//Assign Blink converter settings to HTML converter.
htmlConverter.ConverterSettings = blinkConverterSettings;
string html = Path.Combine(_hostingEnvironment.ContentRootPath, "Input.html");
//Convert existing current page URL to PDF.
PdfDocument document = htmlConverter.Convert(html);
//Saving the PDF to the MemoryStream.
MemoryStream stream = new MemoryStream();
document.Save(stream);
stream.Position = 0;
using (FileStream file = new FileStream(PdfFilePath, FileMode.Create, FileAccess.ReadWrite))
{
byte[] bytes = new byte[stream.Length];
stream.Read(bytes, 0, (int)stream.Length);
file.Write(bytes, 0, bytes.Length);
stream.Close();
}
document.Close(true);
}
- Open the ClientApp folder from the src folder in the command prompt.
- Install the required node modules by using the following commands in the command prompt.
npm install
npm install superagent –save
- Build and run the application. The website will open in the browser, then click the created PDF.
By exporting HTML to PDF, you will get a PDF document as follows.
You can download a complete working sample from HTMLToPDF_React.zip
Take a moment to peruse the documentation, where you can find converting HTML pages to PDF document along with respective customization options and features.
Click here to explore the rich set of Syncfusion Essential PDF features.
Note:
Starting with v16.2.0.x, if you reference Syncfusion assemblies from trial setup or the NuGet feed, include a license key in your projects. Refer to the link to learn about generating and registering the Syncfusion license key in your application to use the components without trail message.
Conclusion
I hope you enjoyed learning about how to convert HTML to a PDF using React Application.
You can refer to our React feature tour page to know about its other groundbreaking feature representations and documentation, and how to quickly get started for configuration specifications. You can also explore our React example to understand how to create and manipulate data.
For current customers, you can check out our components from the License and Downloads page. If you are new to Syncfusion, you can try our 30-day free trial to check out our other controls.
If you have any queries or require clarifications, please let us know in the comments section below. You can also contact us through our support forums, Direct-Trac, or feedback portal. We are always happy to assist you!