나의 개발 일지

자바스크립트로 PDF 다운로드, 프린트 기능 구현하기

designer DK 2025. 1. 28. 11:19
728x90

개인 프로젝트를 구축하면서 영수증 발행 기능을 구현했고

그 과정에서 유저가 영수증을 보관할 수 있게 하기 위해 PDF다운로드와 프린트 기능을 추가했다.

 

pdf다운로드의 경우 라이브러리 스크립트를 사용하면 매우 쉽게 구현할 수 있다.

먼저 html에 이 스크립트를 추가.

 

 

// PDF 다운로드 이벤트 리스너 추가
const downloadButton = document.getElementById('download-receipt');
if (downloadButton) {
downloadButton.addEventListener('click', () => {
console.log('Download button clicked');
const receiptContent = document.getElementById('receipt-content');
 
const opt = {
margin: 1,
filename: 'receipt.pdf',
image: { type: 'jpeg', quality: 0.98 },
html2canvas: { scale: 2 },
jsPDF: { unit: 'in', format: 'letter', orientation: 'portrait' }
};

html2pdf().set(opt).from(receiptContent).save();
});
}

 

그러고나서 이렇게 이벤트리스너에 코드를 넣어주면 pdf 다운로드를 할 수 있다.

 

 

프린트 기능은 더~ 쉽게 구현할 수 있다.

// 프린트 이벤트 리스너 추가
const printButton = document.getElementById('print-receipt');
if (printButton) {
printButton.addEventListener('click', () => {
console.log('Print button clicked');
window.print();
});
}

 

이렇게 코드를 넣어주면 이벤트 발생시 프린트가 진행된다.