思路是先转换成图片,再转换成PDF,转换过程中使用到了两个库:
https://github.com/niklasvh/html2canvas
https://github.com/MrRio/jsPDF
html2canvas官网例子:
html2canvas(document.querySelector("#capture")).then(canvas => {
document.body.appendChild(canvas)
});
jsPDF官网例子:
Then you're ready to start making your document:
// Default export is a4 paper, portrait, using milimeters for units
var doc = new jsPDF()
doc.text('Hello world!', 10, 10)
doc.save('a4.pdf')
If you want to change the paper size, orientation, or units, you can do:
// Landscape export, 2×4 inches
var doc = new jsPDF({
orientation: 'landscape',
unit: 'in',
format: [4, 2]
})
doc.text('Hello world!', 1, 1)
doc.save('two-by-four.pdf')
简单的demo:
<body>
<div id="capture" style="padding: 10px; background: #f5da55">
<h4 style="color: #000; ">Hello world!</h4>
</div>
<button id="capBtn">点击下载</button>
<script src="html2canvas.js" type="text/javascript" charset="utf-8"></script>
<script src="jspdf.min.js" type="text/javascript" charset="utf-8"></script>
<script>
document.querySelector('#capBtn').onclick = function(){
html2canvas(document.querySelector("#capture")).then(canvas => {
// document.body.appendChild(canvas);
var imgData = canvas.toDataURL('image/jpeg');
//初始化pdf,设置相应格式
var doc = new jsPDF("p", "mm", "a4");
//设置a4纸张尺寸
doc.addImage(imgData, 'JPEG', 0, 0,210,297);
doc.save('content.pdf');
});
}
</script>
</body>