參考文獻:
原理
- html轉成pdf,是要先通過html2canvas將遍歷頁面元素,並渲染生成canvas,然後將canvas圖片格式新增到jsPDF例項,生成pdf
一、html轉為canvas image
- 引入html2canvas
<script type="text/javascript" src="/js/html2canvas.js"></script>
複製程式碼
執行程式碼
html2canvas(document.body, {
onrendered:function(canvas) {
document.body.appendChild(canvas)
}
})
複製程式碼
二、html轉為高清圖
- 同時引入Canvas2image
<script type="text/javascript" src="/js/html2canvas.js"></script>
<script type="text/javascript" src="/js/canvas2image.js"></script>
複製程式碼
執行程式碼
<script type="text/javascript">
var dom = dom1; //需要截圖的包裹的(原生的)DOM 物件
var width = dom.offsetWidth;
var height = dom.offsetHeight;
var type = "png";
var scaleBy = 3; //縮放比例
var canvas = document.createElement("canvas");
canvas.width = width * scaleBy;
canvas.height = height * scaleBy;
canvas.style.width = width * scaleBy + "px";
canvas.style.height = height * scaleBy + "px";
var context = canvas.getContext("2d");
context.scale(scaleBy, scaleBy);
// 【重要】關閉抗鋸齒
context.mozImageSmoothingEnabled = false;
context.webkitImageSmoothingEnabled = false;
context.msImageSmoothingEnabled = false;
context.imageSmoothingEnabled = false;
// 獲取元素相對於視窗的偏移量
var rect = dom.getBoundingClientRect();
// 設定context位置, 值為相對於視窗的偏移量的負值, 實現圖片復位
context.translate(-rect.left,-rect.top);
html2canvas(dom, {
useCORS:true, // 【重要】開啟跨域配置,
canvas:canvas, //自定義 canvas
onrendered: function (canvas) {
var img = Canvas2Image.convertToImage(canvas,width* scaleBy,height* scaleBy,type);
document.body.appendChild(img); // 把生成的圖片放在相應位置
img.style.width = width + "px";
img.style.height = height + "px";
dom1.style.display = "none"; // 隱藏掉原有的模組
}
});
</script>
複製程式碼
三、html2canvas + jsPDF轉成PDF
- 同時引入html2canvas + jsPDF
<script type="text/javascript" src="/js/canvas2image.js"></script>
<script type="text/javascript" src="/js/jsPdf.debug.js"></script>
複製程式碼
執行程式碼:
html2canvas(document.body, {
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;
//a4紙的尺寸[595.28,841.89],html頁面生成的canvas在pdf中圖片的寬高
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('content.pdf');
}
})複製程式碼
注意事項
- 圖片跨域問題
- PDF分頁問題,由於這個PDF分頁是根據高度來判斷的,多頁時有可能在分頁的地方出現分割文字或圖片的情況,建議PDF只作為一頁的情況使用