jspdf를 활용한 PDF 생성

jspdf란?

웹 페이지에서 동적으로 PDF 문서를 생성할 수 있게 도와주는 라이브러리.

 

jspdf

PDF Document creation from JavaScript. Latest version: 2.5.1, last published: 2 years ago. Start using jspdf in your project by running `npm i jspdf`. There are 1343 other projects in the npm registry using jspdf.

www.npmjs.com

 

 

GitHub - parallax/jsPDF: Client-side JavaScript PDF generation for everyone.

Client-side JavaScript PDF generation for everyone. - GitHub - parallax/jsPDF: Client-side JavaScript PDF generation for everyone.

github.com

 

설치

npm 패키지

npm install jspdf

CDN 사용

<script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/2.5.1/jspdf.umd.min.js"></script>

 

사용

jspdf는 pdf를 직접 생성하는 방식과 html을 pdf로 변환하는 방식 모두 지원한다.

pdf 직접 생성

var doc = new jsPDF();
doc.text(20, 20, 'Hello world!');
doc.text(20, 30, 'This is client-side Javascript, pumping out a PDF.');
doc.addPage();
doc.text(20, 20, 'Do you like that?');

doc.save('output.pdf');

html → pdf

<div id="content">
    <h1>Hello, World!</h1>
    <p>This is a simple example of converting HTML to PDF using jsPDF.</p>
</div>

<button onclick="generatePDF()">Generate PDF</button>

<script>
    function generatePDF() {
        var pdf = new jsPDF();
        var content = document.getElementById('content');

        pdf.html(content, {
            callback: function (pdf) {
                pdf.save('output.pdf');
            }
        });
    }
</script>