Web/JavaScript
[Javascript] html2canvas + jspdf 사용방법
93_seong.on2e
2021. 11. 5. 16:04
반응형
1. html2canvas + jspdf 사용하여 Html화면을 Pdf 파일로 출력하는방법
https://rawgit.com/MrRio/jsPDF/master/docs/jsPDF.html
jsPDF - Documentation
For compatibility reasons jsPDF offers two API modes which differ in the way they convert between the the usual screen coordinates and the PDF coordinate system. "compat": Offers full compatibility across all plugins but does not allow arbitrary transforms
rawgit.com
html2canvas.js: 현재 브라우저에 의해 렌더링된 화면을 canvas로 변환해준다.
jspdf.js: 객체를 PDF로 변환해준다.
<script src="/lib/pdfjs/jspdf.js"></script>
<script src="/lib/pdfjs/html2canvas.js"></script>
<script>
function pdfPrint(){
// 현재 document.body의 html을 A4 크기에 맞춰 PDF로 변환
html2canvas(document.body, {
onrendered: function (canvas) {
// 캔버스를 이미지로 변환
var imgData = canvas.toDataURL('image/png');
var imgWidth = 210; // 이미지 가로 길이(mm) A4 기준
var pageHeight = imgWidth * 1.414; // 출력 페이지 세로 길이 계산 A4 기준
var imgHeight = canvas.height * imgWidth / canvas.width;
var heightLeft = imgHeight;
var doc = new jsPDF('p', 'mm');
var position = 0;
// 첫 페이지 출력
doc.addImage(imgData, 'PNG', 0, position, imgWidth, imgHeight);
heightLeft -= pageHeight;
// 한 페이지 이상일 경우 루프 돌면서 출력
while (heightLeft >= 20) {
position = heightLeft - imgHeight;
doc.addPage();
doc.addImage(imgData, 'PNG', 0, position, imgWidth, imgHeight);
heightLeft -= pageHeight;
}
// 파일 저장
doc.save('sample.pdf');
//이미지로 표현
//document.write('<img src="'+imgData+'" />');
}
});
}
window.onload = function(){
pdfPrint();
}
</script>
참조:
728x90
반응형