现在有许多将HTML导出PDF的第三方包,这里介绍使用的是Select.HtmlToPdf.NetCore
使用Select.HtmlToPdf.NetCore
整体思路是将cshtml内容读出来,然后再转为Pdf文档
读取cshtml内容有两种方法,第一种使用第三方包 RazorEngine.NetCore,第二种使用官方方法进行读取。(注意两种方法的cshtml内容略有不同)
效果图展示
我把所有的源代码都上传到了我的个人Github,有需要的请自取:https://github.com/WeiMing0803/ExportPdf

首先使用ChatGPT生成个人简历信息

代码部分
HomeController.cs :
public async Task<IActionResult> ToPdf()
{
PdfDocument pdfDocument = new PdfDocument();
HtmlToPdf converter = new HtmlToPdf();//实例化一个html到pdf转换器对象
converter.Options.PdfPageOrientation = PdfPageOrientation.Portrait;//设置页面方向
converter.Options.PdfPageSize = PdfPageSize.A4;//设置页面大小
converter.Options.MarginTop = 10;//设置页边距
converter.Options.MarginBottom = 10;
converter.Options.MarginLeft = 10;
converter.Options.MarginRight = 10;
PdfReportModel model = new PdfReportModel { Name = "彭于晏", Email = "pengyuyan@outlook.com" };
//string htmlResult = readByEngineRazor(model);//第一种方法,使用RazorEngine.NetCore读取Cshtml文件
string htmlResult = await readCshtml(model);//第二种方法
if (!string.IsNullOrEmpty(htmlResult))
{
pdfDocument = converter.ConvertHtmlString(htmlResult);
}
string savePath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), $@"ExportPDF\{DateTime.Now.ToString("yyyyMMdd")}");
Directory.CreateDirectory(savePath);
string filename = Path.Combine(savePath, $"{DateTime.Now.ToString("yyyyMMddHHmmssffff")}.pdf");
pdfDocument.Save(filename);
byte[] bytes =