分享web开发知识

注册/登录|最近发布|今日推荐

主页 IT知识网页技术软件开发前端开发代码编程运营维护技术分享教程案例
当前位置:首页 > IT知识

使用wkhtmltopdf工具生成pdf

发布时间:2023-09-06 02:20责任编辑:胡小海关键词:pdf

背景:将前台页面转换成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

知识推荐

我的编程学习网——分享web前端后端开发技术知识。 垃圾信息处理邮箱 tousu563@163.com 网站地图
icp备案号 闽ICP备2023006418号-8 不良信息举报平台 互联网安全管理备案 Copyright 2023 www.wodecom.cn All Rights Reserved