背景:将前台页面转换成pdf文档保存到服务器
最开始计划使用canvas2pdf在前端进行生成。但是canva2pdf转换的pdf有严重的失真问题,然后决定使用wkhtmltopdf工具进行生成。
思路:服务器准备好模板(html页面),前台将数据传回后台,将数据把模板中的占位符替换掉,然后生成临时html页面,再使用wkhtmltopdf工具将html页面转换成pdf
这里注意:模板中使用到的图片和引用css的路径需要使用绝对路径(带盘符如:c:\a.jpg 或者为localhost:5555/src/a.css)否则wkhtmltopdf工具会找不到引用资源。
将数据填充到html的过程这里就不做展示。只展示转换过程
//导出html ???????????string outputDir = ConvertPdfHelper.GetAbsolutePath("outputDir", false); ???????????DateTime now = DateTime.Now; ???????????string filePath = now.ToString("yyyy/MM/dd") + "/" + salesOrderNo + ".html"; ???????????string temphtmlPath = Path.Combine(outputDir, filePath); ???????????string pdfPath = temphtmlPath.Replace(".html", ".pdf"); ???????????//保證文件夾存在 ???????????FileInfo fileInfo = new FileInfo(temphtmlPath); ???????????fileInfo.Directory.Create(); ???????????string wtHtmlToPdfEXEPath = ConvertPdfHelper.GetAbsolutePath("htmltopdfTool", false); ???????????using (StreamWriter writer = new StreamWriter(temphtmlPath, false, Encoding.UTF8)) ???????????{ ???????????????writer.WriteLine(layoutSb); ???????????????writer.Flush(); ???????????????writer.Close(); ???????????} ???????????//轉pdf ???????????string switches = ""; ???????????switches += "--margin-top 0mm --margin-bottom 0mm --margin-right 0mm --margin-left 0mm "; ???????????switches += "--page-size A5 "; ???????????switches += "--orientation Landscape "; ???????????switches += "--javascript-delay 1000 "; ???????????switches += "--image-quality 50 --lowquality "; ???????????switches += "--disable-smart-shrinking "; ???????????switches += " " + temphtmlPath + " " + pdfPath + ""; ???????????ProcessStartInfo startInfo = new ProcessStartInfo(wtHtmlToPdfEXEPath, switches); ???????????startInfo.CreateNoWindow = true; ???????????startInfo.UseShellExecute = false; ???????????//将输出信息重定向 ???????????startInfo.RedirectStandardOutput = true; ???????????Process process = Process.Start(startInfo); ???????????process.WaitForExit();
Done!
wkhtmltopdf的工具参数详解在这里
HTML 转 PDF 之 wkhtmltopdf 工具精讲
使用wkhtmltopdf工具生成pdf
原文地址:https://www.cnblogs.com/c-supreme/p/9894753.html