javascript,HTML,CSS
[javascript] HTML를 pdf로 변환하기 / how to render html to pdf
코린이예요
2020. 2. 20. 18:28
반응형
HTML
- Prerequisites
<body
<!-- your code goes here -->
<script src="https://html2canvas.hertzen.com/dist/html2canvas.min.js"></script>
<script src="https://unpkg.com/jspdf@latest/dist/jspdf.min.js"></script>
</body
- html2canvas.min.js : 현재 화면을 canvas이미지로 추출한다.
- jspdf.min.js : canvas 이미지를 PDF로 저장한다.
js
html2canvas($('#your_html')[0]).then(function (canvas) {
var filename = 'FILENAME_' + Date.now() + '.pdf';
var doc = new jsPDF('p', 'mm', 'a4');
var imgData = canvas.toDataURL('image/png');
doc.addImage(imgData, 'PNG', 0, 0);
doc.save(filename);
});
- line 1: 렌더링할 element와 option을 설정한다. (html2canvas(element, options)) * option에 대한설명은 링크 참조
(여기서 elemnts를 array처럼 가져왔는데 이는 $('#your_html').get(0)과 같은 의미임.)
- line 3: jsPDF(orientation, unit, format, compress) : jspdf 객체를 생성한다.
- orientation - The default value for orientation is "portrait". We can set it to "landscape" if we want a different page orientation.
- unit - We can tell jsPDF in which units we want to work. Use one of the following: "pt" (points), "mm" (default), "cm", "in".
- format - It's default page format. It can be "a3", "a4" (default), "a5", "letter", "legal".
- line 4 : canvas.toDataURL('image/png') : 캔버스를 이미지로 변환한다.
- line 5 : 이미지를 pdf로 생성한다.
Reference
HTML2CANVAS doc : https://html2canvas.hertzen.com/documentation
jsPDF doc : https://developer.tizen.org/community/tip-tech/creating-pdf-documents-jspdf?langredirect=1
반응형