一、新建项目:QuestPDFDemo
<PackageReference Include="NReco.PdfGenerator" Version="1.2.1" />
二、上代码
cs
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using QuestPDFDemo.Models;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
namespace QuestPDFDemo.Controllers
{
public class HomeController : Controller
{
private readonly ILogger<HomeController> _logger;
public HomeController(ILogger<HomeController> logger)
{
_logger = logger;
}
public IActionResult Index()
{
var path = System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "test.pdf");
var htmlContent = "<html><meta http-equiv=\"content-type\" content=\"text/html; charset=utf-8\" /><body>你好呀!</body></html>";
var htmlToPdf = new NReco.PdfGenerator.HtmlToPdfConverter();
var pdfBytes = htmlToPdf.GeneratePdf(htmlContent);
System.IO.File.Delete(path);
System.IO.File.WriteAllBytes(path, pdfBytes.ToArray());
return View();
}
}
}
效果: