1、使用背景
     最近公司需要把html页面的内容生成pdf并下载,试过很多方法都没有满意的效果,后来找到wkhtmltopdf这款软件,终于解决了这个问题。

     wkhtmltopdf是exe文件,需要下载安装,之后全部文件放到mvc项目,用C#的ProcessStartInfo调用执行。

     要导出的html页面:

    

 

2、下载安装
     官网:https://wkhtmltopdf.org/ <https://wkhtmltopdf.org/>。

     主页download里下载对应系统的版本安装并把安装后的文件放到vs里面方便之后调用。

     

3、使用的参数

      wkhtmltopdf的参数有四种: 封面对象、目录对象、文档对象和页面对象。这里需要用到的是文档对象和页面对象。

     

      还有很多其他参数,具体的参数列表可以看官方文档:https://wkhtmltopdf.org/usage/wkhtmltopdf.txt
<https://wkhtmltopdf.org/usage/wkhtmltopdf.txt>

      使用方法:wkhtmltop
      df [GLOBAL OPTION]... [OBJECT]... <output file>

      

     从左到右依次是:命令开始、使用灰度模式、禁止智能缩放、设置页眉为html文件、生成pdf的页面网址、生成的pdf文件名称。
     上面是在命令提示符使用的方式,在mvc里使用:
1 ProcessStartInfo startInfo = new ProcessStartInfo(); 2 startInfo.FileName =
file;3 startInfo.Arguments = "wkhtmltopdf --grayscale --disable-smart-shrinking
--header-html head.html https://www.baidu.com 123.pdf"; 4
startInfo.CreateNoWindow =true; 5 startInfo.WindowStyle =
ProcessWindowStyle.Hidden;6 var cc = Process.Start(startInfo); 7
cc.WaitForExit();8 cc.Close(); View Code
 

4、添加水印
   
 公司要求生成的pdf需要添加水印,每页pdf显示两个logo水印图片。开始是用给每个div设置背景图片的方式添加水印,让背景图片以y轴重复。由于每个div的高度不定,导致一个水印生成在两个pdf页面,影响美观,果断放弃。后来使用页眉设置html的方式来显示水印,这里要注意的是,页眉会占用html的位置,所以我用before和after伪元素来写两个logo水印。

水印效果图:

 
1 <!DOCTYPE html> 2 <html> 3 <head> 4 <style> 5 * { margin:0;padding:0;}
6 #divd::before{content:"";width:400px;height:400px;background:url(mark.png);
position:absolute;opacity:0.3;left:50%;margin-left:-200px;} 7 #divd::after{
content:"";width:400px;height:400px;background:url(mark.png);position:absolute;
opacity:0.3;left:50%;margin-left:-200px;top:400px} 8 </style> 9 </head> 10 <
bodystyle="border:0; margin: 0;"> 11 <div id="divd" style=""></div> 12 </body>
13 </html> View Code

之后只要用--header-html head.html方式调用这个页面就会每页pdf生成两个水印图片。

 

5、pdf分页
默认pdf生成是把内容从上往下写入,并不好看,导出的pdf效果:



 

公司要求每个div处需要从新的页开始,这里给需要分页的div添加page-break-before:left样式即可,最终pdf效果:



 

6、其他
     a、如果有td或者th需要隐藏border,需要使用这个样式border:0。
     b、生成的pdf设置间距时用padding不用margin。

友情链接
ioDraw流程图
API参考文档
OK工具箱
云服务器优惠
阿里云优惠券
腾讯云优惠券
华为云优惠券
站点信息
问题反馈
邮箱:ixiaoyang8@qq.com
QQ群:637538335
关注微信