如何打印页面中的数据,输出内容到 PDF

将页面中的文本,图片,表格等数据打印到本地。

方法概述

使用 HTML 进行布局,并把数据填充到代码的布局中,然后转换成 Blob 对象打开该链接。

操作步骤

  1. 编辑需要输出的样式,以文本为例。

    <!DOCTYPE html>
    <html lang="en">
    <head>
    <meta charset="UTF-8">
    <title>print</title>
    </head>
    <body>
    <!-- 需要输出的内容 -->
    <script> 
        window.onload = function() {window.print();}
        window.onafterprint = function () { window.close();}
    </script>
    </body>
    </html>
  2. 给列表添加点击操作。

    image

完整代码

function printCode(msg) {
    // htmlContent 这里的文本就是第一步中根据自己的需求定义的输出模板
    const htmlContent = `
        <!DOCTYPE html>
        <html lang="en">
        <head>
        <meta charset="UTF-8">
        <title>print</title>
        </head>
        <body>
        ${msg}
        <script> 
            window.onload = function() {window.print();}
            window.onafterprint = function () { window.close();}
        </script>
        </body>
        </html>
    `;
    const blob = new Blob([htmlContent],{
        type: 'text/html'
    });
    // 创建一个URL对象
    const blobUrl = URL.createObjectURL(blob);
    // 在新标签页中打开Blob URL
    window.open(blobUrl, '_blank');
}
//currentItem.description 当前列表的详情字段
printCode(currentItem.description);