如何把HTML页面(带Iframe)页面转化成mht或pdf格式的文件?

如何把HTML页面(带Iframe)页面转化成pdf格式的文件?

下载依赖文件

<script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.0.272/jspdf.debug.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/html2canvas/0.4.1/html2canvas.js"></script>

需要输出的网页

流程审批

此图为iframe加载的图片

在这里插入图片描述

pdf生成

  //生成PDF
		  //2020-12-2   houzhanguo
          function printWord() {
            var downPdf = document.getElementById( "pdfDom" ); //整个网页元素
            var pdfDom1 = document.getElementById( "pdfDom1" );//蓝边框
            var iframe1 = document.getElementById( "iframe1" );//iframe1 为iframe的父元素
            var urlx = document.getElementById( "urlx" );      //iframe 元素
            var printDiv = document.getElementById( "printDiv" ); //按钮父元素
            var tableremove = document.getElementById( "tableremove" ); //头部元素
            urlx.style.display = "none";
            printDiv.style.display = "none";
	        //  生成PDF时 网页内有嵌套网页img时,先将嵌套网页获取出来,添加在当前网页上 再生成 即可
            iframe1.appendChild( document.querySelector( "iframe" ).contentDocument.querySelector( 'html' ) );
            html2canvas(
              downPdf ,
              {
                dpi: 172 ,//导出pdf清晰度
                onrendered: function ( canvas ) {
                  var contentWidth = canvas.width;
                  var contentHeight = canvas.height;

                  //一页pdf显示html页面生成的canvas高度;
                  var pageHeight = contentWidth / 592.28 * 841.89;
                  //未生成pdf的html页面高度
                  var leftHeight = contentHeight;
                  //pdf页面偏移
                  var position = 0;
                  //html页面生成的canvas在pdf中图片的宽高(a4纸的尺寸[595.28,841.89])
                  var imgWidth = 595.28;
                  var imgHeight = 592.28 / contentWidth * contentHeight;

                  var pageData = canvas.toDataURL( 'image/jpeg' , 1.0 );
                  var pdf = new jsPDF( '' , 'pt' , 'a4' );

                  //有两个高度需要区分,一个是html页面的实际高度,和生成pdf的页面高度(841.89)
                  //当内容未超过pdf一页显示的范围,无需分页
                  if ( leftHeight < pageHeight ) {
                    pdf.addImage( pageData , 'JPEG' , 0 , 0 , imgWidth , imgHeight );
                  } else {
                    while ( leftHeight > 0 ) {
                      pdf.addImage( pageData , 'JPEG' , 0 , position , imgWidth , imgHeight )
                      leftHeight -= pageHeight;
                      position -= 841.89;
                      //避免添加空白页
                      if ( leftHeight > 0 ) {
                        pdf.addPage();
                      }
                    }
                  }
                  pdf.save( '审批办理.pdf' );
                } ,
                //背景设为白色(默认为黑色)
                background: "#fff"
              } )
          }

生成结果

在这里插入图片描述
测试可以正常显示!

重要代码:

这是代码

注意:

生成pdf之前,先将iframe中的dom元素 获取出来,放在当前网页上,这样的话,html2canvas就可一次性生成!

网页源码

<%@ page language="java" pageEncoding="GBK" %>
<jsp:directive.page import="com.kaiyue.jpf.workflow.struts.form.WfForm"/>
<jsp:directive.page import="com.kaiyue.jpf.workflow.service.dto.WFTask"/>
<jsp:directive.page import="com.kaiyue.common.resource.AppConfig"/>
<jsp:directive.page import="com.kaiyue.common.resource.ResourceConstants"/>
<jsp:directive.page import="java.util.Date"/>
<%@ taglib uri="/WEB-INF/tld/kaiyue-jpf.tld" prefix="WorkFlow" %>
<%@ include file="/include/commonheader.jsp" %>
<%@ include file="/include/stylesheet.jsp" %>
<%@ include file="/website/styl/stylesheet.jsp" %>
<%
    WfForm wfForm = (WfForm) request.getAttribute("wfForm");
    String wfId = wfForm.getWfId();
    session.setAttribute("wf", wfForm);
%>
<html:base/>
<html:html lang="true">
    <head>
        <meta http-equiv="pragma" content="no-cache">
        <meta http-equiv="cache-control" content="no-cache">
        <meta http-equiv="expires" content="0">
        <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
        <meta http-equiv="description" content="This is my page">
        <title>打印会签单</title>
        <script language="jscript" src="<%=jsBasePath%>/public.js"></script>
        <script language="jscript" src="<%=jsBasePath%>/common.js"></script>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/html2canvas/0.4.1/html2canvas.js"></script>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.0.272/jspdf.debug.js"></script>
        <style>
            .tabborder1 {
                border: 0 !important;
            }
        </style>
        <script type="text/javascript">
          // //打印URL
          // function print( url ) {
          //   document.all( "printDiv" ).style.display = "none";
          //   var WebBrowser = '<OBJECT ID="WebBrowser" WIDTH=0 HEIGHT=0 CLASSID="CLSID:8856F961-340A-11D0-A96B-00C04FD705A2"></OBJECT>';
          //   document.body.insertAdjacentHTML( 'beforeEnd' , WebBrowser );
          //   WebBrowser.ExecWB( 6 , 1 );
          //   document.all( "printDiv" ).style.display = "";
          // }

          //打印预览 效果
          function printHqd() {
            // //document.all("qingkongyema").click();//打印之前去掉页眉,页脚
            // document.all( "printDiv" ).style.display = "none"; //打印之前先隐藏不想打印输出的元素(此例中隐藏“打印”和“打印预览”两个按钮)
            // var OLECMDID = 7;
            // var PROMPT = 1;
            // var WebBrowser1 = '<OBJECT ID="WebBrowser1" WIDTH=0 HEIGHT=0 CLASSID="CLSID:8856F961-340A-11D0-A96B-00C04FD705A2"></OBJECT>';
            // document.body.insertAdjacentHTML( 'beforeEnd' , WebBrowser );
            // WebBrowser1.ExecWB( OLECMDID , PROMPT );
            // WebBrowser1.outerHTML = "";
            // document.all( "printDiv" ).style.display = "";//打印之后将该元素显示出来(显示出“打印”和“打印预览”两个按钮,方便别人
	          var downPdf = document.getElementById( "pdfDom" );
	          var pdfDom1 = document.getElementById( "pdfDom1" );
	          var iframe1 = document.getElementById( "iframe1" );
	          var urlx = document.getElementById( "urlx" );
	          var printDiv = document.getElementById( "printDiv" );
	          var tableremove = document.getElementById( "tableremove" );
	          // urlx.style.display = "none";
	          printDiv.style.display = "none";
          }
		  //生成PDF
		  //2020-12-2   houzhanguo
          function printWord() {
            var downPdf = document.getElementById( "pdfDom" ); //整个网页元素
            var pdfDom1 = document.getElementById( "pdfDom1" );//蓝边框
            var iframe1 = document.getElementById( "iframe1" );//iframe1 为iframe的父元素
            var urlx = document.getElementById( "urlx" );      //iframe 元素
            var printDiv = document.getElementById( "printDiv" ); //按钮父元素
            var tableremove = document.getElementById( "tableremove" ); //头部元素
            urlx.style.display = "none";
            printDiv.style.display = "none";
	        //  生成PDF时 网页内有嵌套网页img时,先将嵌套网页获取出来,添加在当前网页上 再生成 即可
            iframe1.appendChild( document.querySelector( "iframe" ).contentDocument.querySelector( 'html' ) );
            html2canvas(
              downPdf ,
              {
                dpi: 172 ,//导出pdf清晰度
                onrendered: function ( canvas ) {
                  var contentWidth = canvas.width;
                  var contentHeight = canvas.height;

                  //一页pdf显示html页面生成的canvas高度;
                  var pageHeight = contentWidth / 592.28 * 841.89;
                  //未生成pdf的html页面高度
                  var leftHeight = contentHeight;
                  //pdf页面偏移
                  var position = 0;
                  //html页面生成的canvas在pdf中图片的宽高(a4纸的尺寸[595.28,841.89])
                  var imgWidth = 595.28;
                  var imgHeight = 592.28 / contentWidth * contentHeight;

                  var pageData = canvas.toDataURL( 'image/jpeg' , 1.0 );
                  var pdf = new jsPDF( '' , 'pt' , 'a4' );

                  //有两个高度需要区分,一个是html页面的实际高度,和生成pdf的页面高度(841.89)
                  //当内容未超过pdf一页显示的范围,无需分页
                  if ( leftHeight < pageHeight ) {
                    pdf.addImage( pageData , 'JPEG' , 0 , 0 , imgWidth , imgHeight );
                  } else {
                    while ( leftHeight > 0 ) {
                      pdf.addImage( pageData , 'JPEG' , 0 , position , imgWidth , imgHeight )
                      leftHeight -= pageHeight;
                      position -= 841.89;
                      //避免添加空白页
                      if ( leftHeight > 0 ) {
                        pdf.addPage();
                      }
                    }
                  }
                  pdf.save( '审批办理.pdf' );
                } ,
                //背景设为白色(默认为黑色)
                background: "#fff"
              } )
          }
        </script>
    </head>
    <body style="padding: 25px 10px 0 10px" id="pdfDom" class="right-aside">
    <html:form action="/wfAction.do?method=toWfExecute">
        <table width="100%" border="0" align="center" cellpadding="0"
               cellspacing="0" background="<%=styleImagePath %>/switch03.gif" style="margin-left: 0;margin-right: 0"
               id="tableremove">
            <tr>
                <td style="background-color: #fff">
                    <table width="100%" border="0" cellspacing="0" cellpadding="0">
                        <tr style="background-color: #fff">
                            <td width="97" height="24" align="center"
                                background="<%=styleImagePath %>/switch01.gif">
                                <strong>审批办理</strong>
                            </td>
                            <td width="1" class="border_B0BEC7">
                            </td>
                            <td class="border_B0BEC7">
                                &nbsp;
                            </td>
                            <td class="border_B0BEC7">
                                &nbsp;
                            </td>
                        </tr>
                    </table>
                </td>
            </tr>
        </table>
        <div class="tabborder" id="pdfDom1">
            <div class="ibox float-e-margins">
                <div class="ibox-title" style="border: 0">
                    <div style="float: left; width: 60%;">
                        <h5></h5>
                    </div>
                    <div align="right" id="printDiv" style="float: left; display:block; width: 40%;" class="ibox-tools">
                            <%--                        <button class="btn btn-primary" onclick="print();" id="print" type="button" style="float: left; width: 90px;--%>
                            <%--    height: 29px;--%>
                            <%--    text-align: center;--%>
                            <%--    padding: 0;--%>
                            <%--    line-height: 29px;">打印--%>
                            <%--                        </button>--%>
                        <button class="btn btn-primary" onClick="printHqd();" type="button" style="float: left;margin-left: 10px; width: 90px;
    height: 29px;
    text-align: center;
    padding: 0;
    line-height: 29px;">打印预览
                        </button>
                        <button class="btn btn-primary" onClick="printWord()" type="button" style="float: left;margin-left: 10px; width: 90px;
    height: 29px;
    text-align: center;
    padding: 0;
    line-height: 29px;">pdf导出
                        </button>
                    </div>
                </div>
            </div>
            <div style="width: 100%; height: 40px;">
                <div align="right" style="float: left;width: 15%; line-height: 40px; font-size: 14px;">
                    文件标题:
                </div>
                <div align="left" style="float: left;width: 85%; line-height: 40px; font-size: 14px;">
                    &nbsp;${wfForm.wfName}
                </div>
            </div>
            <div style="width: 100%; height: 2px; border-bottom: 1px dotted #cccccc; margin-bottom: 8px;"></div>
            <div style="width: 100%; height: 40px;">
                <div align="right" style="float: left;width: 15%; line-height: 40px; font-size: 14px;">
                    文件流程:
                </div>
                <div align="left" style="float: left;width: 25%; line-height: 40px; font-size: 14px;">
                    &nbsp;${wfForm.wftName}
                </div>
                <div align="left" style="float: left;width: 60%; line-height: 40px; font-size: 12px;">
                    <font color="#0099CC">■</font>为已办审批节点&nbsp;&nbsp;
                    <font color="#FF9A00">■</font> 为当前审批节点&nbsp;&nbsp;
                    <font color="#FF0000">■</font> 未接收审批节点&nbsp;&nbsp;
                    <font color="#000000">■</font>为未办审批节点&nbsp;&nbsp;
                </div>
            </div>
            <div style="width: 100%; height: 2px; border-bottom: 1px dotted #cccccc; margin-bottom: 8px;"></div>
            <div style="width: 100%; height: 80px;">
                <div align="right" style="float: left;width: 15%; line-height: 40px; font-size: 14px;">
                    流程图例:
                </div>
                <div align="left" style="float: left;width: 85%;" id="iframe1">
                    <iframe id='urlx' src="publicPrintWF.jsp?wfid=${wfForm.wfId}" frameBorder='0' scrolling='auto'
                            allowTransparency width='100%' height="100%"
                            onload='document.all.urlx.height=urlx.document.body.scrollHeight+50'
                            crossorigin="anonymous"></iframe>
                </div>
            </div>
            <div style="width: 100%; height: 2px; border-bottom: 1px dotted #cccccc; margin-bottom: 8px;"></div>
            <div style="width: 100%; height: 40px; font-size: 16px;" align="center">
                <div align="right" style="float: left;width: 15%; line-height: 40px; font-size: 14px;">
                    办理过程:
                </div>
            </div>
                <%--<div style="width: 100%; height: 2px; border-bottom: 1px dotted #cccccc; margin-bottom: 8px;"></div>--%>
            <table width=100% border=0 cellspacing=1 cellpadding=0 align=center style="word-break: break-all"
                   class="table table-bordered">
                <thead>
                <tr>
                    <td>序号</td>
                    <td>办理人</td>
                    <td>办理结果</td>
                    <td>办理说明</td>
                    <td>接收日期</td>
                    <td>结束日期</td>
                </tr>
                </thead>
                <logic:present name="approveList">
                    <%
                        Object obj = request.getAttribute("approveList");
                        session.setAttribute("approve", obj);
                    %>
                    <logic:iterate id="approveList" name="approveList" indexId="xh">
                        <tr class='listtr4' height=20>
                            <%
                                boolean bl = false;
                                String color = "red";
                                String settingTime = "";
                                //取是否启用
                                String isStartup = AppConfig.getProperty(ResourceConstants.WORKFLOW_ALERT_ENABLE);
                                try {
                                    if (!(isStartup == null || "".equals(isStartup))) {
                                        if (isStartup.contains("true")) {
                                            //取时间
                                            settingTime = AppConfig.getProperty(ResourceConstants.WORKFLOW_ALERT_TIMELIMIT);
                                            if (settingTime != null || settingTime.length() > 0) {
                                                Long time = new Long(settingTime);
                                                time = time * 60 * 60;//把小时转换成
                                                WFTask wf = (WFTask) approveList;
                                                Date stdate = wf.getAcceptTime();
                                                Date enddate = wf.getFinishTime();
                                                stdate = stdate == null ? new Date(System.currentTimeMillis()) : stdate;
                                                enddate = enddate == null ? new Date(System.currentTimeMillis()) : enddate;
                                                long begin = stdate.getTime() / 1000;
                                                long end = enddate.getTime() / 1000;
                                                if ((end - begin) > time) {
                                                    bl = true;
                                                    //取颜色
                                                    color = AppConfig.getProperty(ResourceConstants.WORKFLOW_ALERT_FORECOLOR);
                                                }
                                            }
                                        }
                                    }
                                } catch (Exception e) {
                                }
                                if (bl) {
                            %>
                            <td align=center title="办理时间已经超过<%=settingTime%>小时"
                                bgcolor="<%=color%>">${pageScope.xh+1}</td>
                            <td align=left title="办理时间已经超过<%=settingTime%>小时" bgcolor="<%=color%>">
                                <font color='#0000FF'>
                                    <bean:write property="actorName" name="approveList"/>
                                </font>
                            </td>
                            <td align=left title="办理时间已经超过<%=settingTime%>小时" bgcolor="<%=color%>"><bean:write
                                    property="opinion" name="approveList"/></td>
                            <td align=left title="办理时间已经超过<%=settingTime%>小时" bgcolor="<%=color%>"><bean:write
                                    property="remark" name="approveList"/></td>
                            <td align=center title="办理时间已经超过<%=settingTime%>小时" bgcolor="<%=color%>">
                                <bean:write property="acceptTime" name="approveList" format="yyyy-MM-dd HH:mm"/>
                            </td>
                            <td align=center title="办理时间已经超过<%=settingTime%>小时" bgcolor="<%=color%>">
                                <bean:write property="finishTime" name="approveList" format="yyyy-MM-dd HH:mm"/>
                            </td>
                            <% } else {%>
                            <td align=center>${pageScope.xh+1}</td>
                            <td align=left>
                                <font color='#0000FF'>
                                    <bean:write property="actorName" name="approveList"/>
                                </font>
                            </td>
                            <td align=left><bean:write property="opinion" name="approveList"/></td>
                            <td align=left><bean:write property="remark" name="approveList"/></td>
                            <td align=center>
                                <bean:write property="acceptTime" name="approveList" format="yyyy-MM-dd HH:mm"/>
                            </td>
                            <td align=center>
                                <bean:write property="finishTime" name="approveList" format="yyyy-MM-dd HH:mm"/>
                            </td>
                            <%}%>
                        </tr>
                    </logic:iterate>
                </logic:present>
            </table>
                <%--<div style="width: 100%; height: 2px; border-bottom: 1px dotted #cccccc; margin-bottom: 8px;"></div>--%>
            <div style="width: 100%; height: 40px;">
                <div align="right" style="float: left;width: 15%; line-height: 40px; font-size: 14px;">
                    送阅人员:
                </div>
                <div align="left" style="float: left;width: 85%;">
                    <html:hidden property="copyIds"/>
                    <logic:notEmpty name="copyNames">
                        <bean:write name="copyNames"/>
                    </logic:notEmpty>
                </div>
            </div>
        </div>
        <%--<div style="width: 100%; height: 2px; border-bottom: 1px dotted #cccccc; margin-bottom: 8px;"></div>--%>
        <html:hidden property="wfId"/>
        <html:hidden property="wfTaskId"/>
        <html:hidden property="businessId"/>
        <html:hidden property="businessType"/>
        <html:hidden property="printUrl"/>
    </html:form>
    </body>
</html:html>
<%@ include file="/include/commonfooter.jsp" %>

希望能帮到你哦!

猜你喜欢

转载自blog.csdn.net/web_houzhanguo/article/details/110491695