I want to convert html to pdf in my website (ASP.NET Core 6.0), but I can't find the solution.
It should be created by specifing a url.
In ASP.NET MVC 5 era, I had used the library called Tuespeckin.
Is there any solution, which is free and elegant , that can work in ASP.NET Core 6.0?
Although following article was so helpful, it may a little obsolete.
Can PDFSharp create Pdf file from a Html string in Net Core?
First answer mention SelectPDF, but I wish more modern methods, if any.
CodePudding user response:
You can use Syncfusion
to convert html to pdf.
First, Install Syncfusion.HtmlToPdfConverter.Net.Windows
NuGet package.
Then, Edit the corresponding method in the controller:
public class HomeController : Controller
{
public IActionResult Index()
{
return View();
}
public IActionResult ExportToPDF()
{
HtmlToPdfConverter htmlConverter = new HtmlToPdfConverter();
//Convert URL to PDF document
PdfDocument document = htmlConverter.Convert("https://www.syncfusion.com");
//Create memory stream
MemoryStream stream = new MemoryStream();
//Save the document
document.Save(stream);
return File(stream.ToArray(), System.Net.Mime.MediaTypeNames.Application.Pdf, "HTML-to-PDF.pdf");
}
}
Don't forget to add the namespace:
using Syncfusion.Pdf;
using Syncfusion.HtmlConverter;
Finally, Add the call in Index.cshtml
:
@{
Html.BeginForm("ExportToPDF", "Home", FormMethod.Post);
{
<div>
<input type="submit" value="Convert HTML to PDF" style="width:250px;height:27px" />
</div>
}
Html.EndForm();
}
You can change the URL Page you want to download in the controller method:
PdfDocument document = htmlConverter.Convert("Your Url");
For more details, you can refer to this document.
Update:
Yes, it's not actually open source, you need to get a license key to remove it (only 30 days free trial).
Free and effective first choice is actually SelectPDF.
If you really don't want to use it, you can choose the following two:
PuppeteerSharp: It's a headless chrome instance which can capture pdfs, and has a nice C# library (Puppeteer Sharp).
jsPDF: This is also a conversion tool used by open source.
Just my opinion, I think the experience of these two is not as good as SelectPDF. Maybe there are other free and up-to-date PDF converters, but I haven't found them and haven't used them.