-
[html to pdf] html 소스 pdf로 변환하기[프로그래밍 | 개발]/[java script or ts] 2021. 8. 26. 10:19
html2canvas, jsPDF 사용
const htmlToPdf = async() => { const printEl:any = document.getElementById('printEl'); await html2canvas(printEl) .then(canvas => { const imgData = canvas.toDataURL('image/jpeg'); // 확장자 변경가능 const imgWidth = 190; // A4 width 210에서 패딩 10, 10을 뺀 값 // 꼭 190 안맞춰도 되고 A4 비율에 따라 조정 const pageHeight = 190*1.414; const imgHeight = canvas.height * imgWidth/canvas.width; let position = 0; let heightLeft = imgHeight; const pdf = new jsPDF('p','mm','a4'); // 단위는 조정 가능 pdf.addImange(imgData, 'JPEG', 10, 10, imgWidth, imgHeight); heightLeft -= pageHeight; while (heightLeft >= 0) { position = heightLeft - imgHeight; pdf.addPage(); pdf.addImage(imgData, 'JPEG', 10, position, imgWidth, imgHeight); heightLeft -= pageHeight; } const iframe = document.createElement('iframe'); const pdfBlob = pdf.output('blob'); iframe.src = URL.createObjectURL(pdfBlob); iframe.width = '1200px'; iframe.height = '800px'; (원하는부모El).appendChild(iframe); }) }위 함수는 id 값이 'printEl'인 엘레멘트를 받아와서 pdf로 변환하는 구문이다.
변환된 이미지가 길어지면 페이지를 나누도록 되어있는데, 여기에는 늘어난 페이지 사이에 간격조정이 안된다는 치명적인 단점(라이브러리의 한계)이 있다.
개인적인 생각으로는,
1. canvas(HTMLCanvasElement)를 img로 변환하고
2. img 행렬에서 width height 비율을 계산해 행렬자체를 패딩 간격이 있는 페이지 단위로 분할한 다음
3. jsPDF 객체로 따로따로 생성하면 되지 않을까 예상.
추후에 테스트 할 예정.
그리고 iframe을 사용한 이유는 iframe 에서 미리보기와 인쇄(버튼) 기능을 제공하고 있어 편리하기 때문.