使用Net将HTML简历导出为PDF格式

发布时间 2023-03-22 21:13:55作者: 漫思

使用Net将HTML简历导出为PDF格式

 

现在有许多将HTML导出PDF的第三方包,这里介绍使用的是Select.HtmlToPdf.NetCore

使用Select.HtmlToPdf.NetCore

  1. 整体思路是将cshtml内容读出来,然后再转为Pdf文档
  2. 读取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 = System.IO.File.ReadAllBytes(filename);
    return File(bytes, "application/pdf", Path.GetFileName(filename));
}

 private string readByEngineRazor(PdfReportModel model)
{
    string template = System.IO.File.ReadAllText("Views/Report/PdfReport.cshtml");
    string htmlResult = Engine.Razor.RunCompile(template, "PdfReport", typeof(PdfReportModel), model);
    return htmlResult;
}

private async Task<string> readCshtml(PdfReportModel model)
{
    string htmlResult = await _viewRenderService.RenderToStringAsync("Report/PdfReport", model);
    return htmlResult;
}

TemplateGadgetProvider.cs :

public class TemplateGadgetProvider
{
    public static TemplateGadgetProvider _instance;
    public static TemplateGadgetProvider Instance
    {
        get
        {
            if (_instance == null)
                _instance = new TemplateGadgetProvider();
            return _instance;
        }
    }

    public string Load(string virtualPath)
    {
        return File.ReadAllText(virtualPath);
    }
}

pdfReport.css :

Css样式文件:点击查看详细内容

PdfReport.cshtml :

使用RazorEngine.NetCore需要修改下面两处地方

  1. 删除 @model PdfReportModel
  2. @Html.Raw(@style) 修改为 @@Raw(@style)
视图文件:点击查看详细内容

ViewRenderService :
public class ViewRenderService
{
    private readonly IRazorViewEngine _razorViewEngine;
    private readonly ITempDataProvider _tempDataProvider;
    private readonly IServiceProvider _serviceProvider;

    public ViewRenderService(IRazorViewEngine razorViewEngine,
        ITempDataProvider tempDataProvider,
        IServiceProvider serviceProvider)
    {
        _razorViewEngine = razorViewEngine;
        _tempDataProvider = tempDataProvider;
        _serviceProvider = serviceProvider;
    }

    public async Task<string> RenderToStringAsync(string viewName, object model)
    {
        var httpContext = new DefaultHttpContext { RequestServices = _serviceProvider };
        var actionContext = new ActionContext(httpContext, new RouteData(), new ActionDescriptor());

        using (var sw = new StringWriter())
        {
            var viewResult = _razorViewEngine.FindView(actionContext, viewName, false);

            if (viewResult.View == null)
            {
                throw new ArgumentNullException($"{viewName} does not match any available view");
            }

            var viewDictionary = new ViewDataDictionary(new EmptyModelMetadataProvider(), new ModelStateDictionary())
            {
                Model = model
            };

            var viewContext = new ViewContext(
                actionContext,
                viewResult.View,
                viewDictionary,
                new TempDataDictionary(actionContext.HttpContext, _tempDataProvider),
                sw,
                new HtmlHelperOptions()
            );

            await viewResult.View.RenderAsync(viewContext);
            return sw.ToString();
        }
    }
}

Program.cs :

builder.Services.AddTransient<ViewRenderService>();

以上就是使用Select.HtmlToPdf.NetCore将HTML导出为PDF的全部内容!

作者:百宝门-明维

原文地址:https://blog.baibaomen.com/97-2/