DomPDF.js - HTML 转 PDF 生成器 --- DomPDF.js - HTML to PDF Generator
一个 JavaScript 库,可以将 HTML 转换为可编辑、非图片格式、高分辨率、轻量级且可打印的 PDF 文档
在线体验:在线体验
该脚本基于html2canvas和jspdf,与以往将 html 页面通过 html2canvas 渲染为图片,再通过 jspdf 将图片生成 pdf 文件不同,该脚本通过读取 DOM 和应用于元素的不同样式,改造了 html2canvas 的 canvas-renderer 文件,调用 jspdf 的方法生成 pdf 文件。 所以他有以下优势:
当然,它也有一些缺点:
| 功能 | 状态 | 说明 | 
|---|---|---|
| 文本渲染 | ✅ | 支持基础文本内容渲染,font-family,font-size,font-style,font-variant,color 等,支持文字描边,不支持文字阴影 | 
| 图片渲染 | ✅ | 支持网络图片,base64 图片,svg 图片 | 
| 边框 | ✅ | 支持 border-width,border-color,border-style,border-radius,暂时只实现了实线边框 | 
| 背景 | ✅ | 支持背景颜色,背景图片,背景渐变 | 
| canvas | ✅ | 支持渲染 canvas | 
| svg | ✅ | 支持渲染 svg | 
| 阴影渲染 | ✅ | 使用 foreignObjectRendering,支持边框阴影渲染 | 
| 渐变渲染 | ✅ | 使用 foreignObjectRendering,支持背景渐变渲染 | 
| iframe | ❌ | 支持渲染 iframe | 
在 dom 十分复杂,或者 pdf 无法绘制的情况(比如:复杂的表格,边框阴影,渐变等),可以考虑使用 foreignObjectRendering。 给要渲染的元素添加 foreignObjectRendering 属性,就可以通过 svg 的 foreignObject 将它渲染成一张背景图插入到 pdf 文件中。
但是,由于 foreignObject 元素的渲染依赖于浏览器的实现,因此在不同的浏览器中可能会有不同的表现。 所以,在使用 foreignObjectRendering 时,需要注意以下事项:
示例
<div style="width: 100px;height: 100px;" foreignObjectRendering>
    <div
        style="width: 50px;height: 50px;border: 1px solid #000;box-shadow: 2px 2px 5px rgba(0,0,0,0.3);background: linear-gradient(45deg, #ff6b6b, #4ecdc4);"
    >
        这是一个div元素
    </div>
</div>
该库应该可以在以下浏览器上正常工作(需要 Promise polyfill):
dompdf 库使用 Promise 并期望它们在全局上下文中可用。如果您希望支持不原生支持 Promise 的较旧浏览器,请在引入 dompdf 之前包含一个 polyfill,比如 es6-promise。
安装:
 npm install dompdf.js --save
CDN 引入:
<script src="https://cdn.jsdelivr.net/npm/dompdf.js@1.0.4/dist/dompdf.min.js"></script>   
import dompdf from 'dompdf.js';
dompdf(document.querySelector("#capture"), {
    useCORS: true //是否允许跨域
    })
    .then(function (blob) {
        const url = URL.createObjectURL(blob);
        const a = document.createElement('a');
        a.href = url;
        a.download = 'example.pdf';
        document.body.appendChild(a);
        a.click();
    })
    .catch(function (err) {
        console.log(err, 'err');
    });
由于jspdf只支持英文,所以其他语言会出现乱码的问题,需要导入对应的字体文件来解决,如果需要自定义字体,在这里将字体 tff 文件转化成 base64 格式的 js 文件,中文字体推荐使用思源黑体,体积较小。 在代码中引入该文件即可。
    <script type="text/javascript" src="./SourceHanSansSC-Normal-Min-normal.js"></script>
    dompdf(document.querySelector("#capture"), {
    useCORS: true, //是否允许跨域
    fontConfig: {
                    fontFamily: 'SourceHanSansSC-Normal-Min',
                    fontBase64: window.fontBase64,
                },
    })
    .then(function (blob) {
        const url = URL.createObjectURL(blob);
        const a = document.createElement('a');
        a.href = url;
        a.download = 'example.pdf';
        document.body.appendChild(a);
        a.click();
    })
    .catch(function (err) {
        console.log(err, 'err');
    });
克隆 git 仓库:
$ git clone git@github.com:lmn1919/dompdf.js.git
安装依赖:
$ npm install
构建浏览器包:
$ npm run build