html转pdf,是先把html截成图片,在把图片转成pdf。
需要引入html2canvas.js和jspdf.debug.js两个文件,因为分页的话,会出现很丑的分割线,所有这个例子是不分页的,直接看个demo吧。(主要scale和dpi来提高清晰度)
移动端html转pdf
.main{
min-width: 320px;
max-width: 750px;
width: 100%;
margin: 0 auto;
position: relative;
}
img{
width: 24.5rem;
height: 13rem;
margin: 0 auto;
display: block;
}
点击下载pdf
移动端html转pdf
$(function() {
// 获取像素比
function getDPR() {
if(window.devicePixelRatio && window.devicePixelRatio > 1) { //返回当前显示设备的物理像素分辨率与 CSS 像素分辨率的比率
return window.devicePixelRatio;
}
return 1;
}
var template = document.getElementById(‘main’);
function scaleCanvas() {
var dom = template;
const box = window.getComputedStyle(dom);
const width = box.width.replace(‘px’, ”);
const height = box.height.replace(‘px’, ”);
const scaleBy = getDPR();
const canvas = document.createElement(‘canvas’);
// 设定 canvas 元素属性宽高为 DOM 节点宽高 * 像素比
canvas.width = width * scaleBy;
canvas.height = height * scaleBy;
// 设定 canvas css宽高为 DOM 节点宽高
canvas.style.width = `${width}px`;
canvas.style.height = `${height}px`;
// 获取画笔
const context = canvas.getContext(‘2d’);
// 将所有绘制内容放大像素比倍
context.scale(scaleBy, scaleBy);
var rect = template.getBoundingClientRect(); //获取元素相对于视察的偏移量
context.translate(-rect.left, -rect.top); //设置context位置,值为相对于视窗的偏移量负值,让图片复位
html2canvas(template, {
canvas, //将放大的cnavas作为参数传进去
scale: 2, //缩放比例
dpi: 300, //将分辨率提高到特定的DPI(每英寸点数),DPI的值越高,扫码的清晰度越高
background: ‘#FFFFFF’, //背景颜色
onrendered: function(imgCanvas) {
var contentWidth = canvas.width;
var contentHeight = canvas.height;
var position = 0;
var pageData = canvas.toDataURL(‘image/jpeg’, 1.0);
// 设置pdf的尺寸,pdf要使用pt单位 已知 1pt/1px = 0.75 pt = (px/scale)* 0.75
// 2为上面的scale 缩放了2倍
var pdfX = (contentWidth + 10) / 2 * 0.75;
var pdfY = (contentHeight + 200) / 2 * 0.75; //200为底部留白
var imgX = pdfX;
var imgY = (contentHeight / 2 * 0.75);
var pdf = new jsPDF(”, ‘pt’, [pdfX, pdfY]);
pdf.addImage(pageData, ‘JPEG’, 0, 0, imgX, imgY);
pdf.save(“html转pdf的demo.pdf”);
},
useCORS: true, //貌似与跨域有关,但和allowTaint不能共存
allowTaint: false, //允许跨域
});
}
$(“#downPdf”).click(function() {
scaleCanvas();
})
})
效果图如下:
b80d825e5622543a51caaef71cc183f.png