zoukankan      html  css  js  c++  java
  • wkhtmltopdf导出html到pdf

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

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

         要导出的html页面:

        

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

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

         

    3、使用的参数

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

         

          还有很多其他参数,具体的参数列表可以看官方文档: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 <body style="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,类似“padding:1px 2px 3px 4px”这种样式要改成“padding-top:1px;padding-right:2px;padding-bottom:3px;padding-left:4px;”。

         c、html里面如果有font-family样式和h1、h2、h3标签也会出错;解决方法是去掉或者替换这些字符串。

  • 相关阅读:
    警告:ORA-00600 2252 错误正在SCN问题下不断爆发(转)
    Linux批量清除木马文件photo.scr
    500 OOPS: vsftpd: refusing to run with writable root inside chroot() Login failed. 421 Service not available, remote server has closed connection
    Linux后门入侵检测工具(转)
    解决Docker无法删除镜像
    通过DataX从Oracle同步数据到MySQL-安装配置过程
    Server2008 R2安装、配置Freesshd(Jenkins持续集成-Windows)
    Mysql死锁解决办法
    Mssql 2017修改master默认排序规则
    可能需要用到的Mac技巧or软件
  • 原文地址:https://www.cnblogs.com/82xb/p/7837597.html
Copyright © 2011-2022 走看看