[jspdf, html2canvas]_그려진 html 화면 pdf 출력하기

2023. 10. 18. 13:40[오픈소스_라이브러리]/[jspdf, html2canvas]

728x90
반응형

환경

Framework : spring

javascript : ES6 환경

목적

도표 등 그려진 화면을 pdf 로 저장 혹은 출력하는 요구사항 반영

 

문서

https://html2canvas.hertzen.com/

 

html2canvas - Screenshots with JavaScript

Try out html2canvas Test out html2canvas by rendering the viewport from the current page. Capture

html2canvas.hertzen.com

https://artskydj.github.io/jsPDF/docs/jsPDF.html

 

jsPDF - Documentation

Fill the current path using the nonzero winding number rule. If a pattern is provided, the path will be filled with this pattern, otherwise with the current fill color. Equivalent to the PDF "f" operator. The identity matrix (equivalent to new Matrix(1, 0,

artskydj.github.io

js 파일

html2canvas.min.js
0.19MB
jspdf.min.js
0.29MB

예시 화면

 

html

PDF 화면


소스

 

html

 

<div id="testDiv">
    <div id="screen"></div>
    <div>
      <div>평균 시간ms</div>
      <button>리셋</button>
    </div>
    <input/>
    <button id="pdfBtn">PDF 다운</button>
  </div>

 

script

<script src="/resources/web/js/html2canvas.min.js"></script>
<script src="/resources/web/js/jspdf.min.js"></script>


<script type="text/javascript">
	$(document).ready(function () {
    	
        let element = document.querySelector("#testDiv");
        let pdfBtn = document.querySelector("#pdfBtn");
        
        pdfBtn.addEventListener('click', pdfClick);
        
        
        function pdfClick () {
          console.log('click');
            
          html2canvas(element).then(function(canvas){
          let imgData = canvas.toDataURL('image/png');

          let margin = 10; // 출력 페이지 여백설정
          let imgWidth = 210 - (10 * 2); // 이미지 가로 길이(mm) A4 기준
          let pageHeight = imgWidth * 1.414;  // 출력 페이지 세로 길이 계산 A4 기준
          let imgHeight = canvas.height * imgWidth / canvas.width;
          let heightLeft = imgHeight;

          let doc = new jsPDF('p', 'mm');
          let position = margin;

          // 첫 페이지 출력
          doc.addImage(imgData, 'PNG', margin, position, imgWidth, imgHeight);
          heightLeft -= pageHeight;

          // 한 페이지 이상일 경우 루프 돌면서 출력
          while (heightLeft >= 20) {
            position = heightLeft - imgHeight;
            doc.addImage(imgData, 'PNG', 0, position, imgWidth, imgHeight);
            doc.addPage();
            heightLeft -= pageHeight;
          }

          // 파일 저장
          doc.save('sample.pdf');
        })
        
        }
    
    });

</script>

 

참고 블로그

https://devlink.tistory.com/242

 

자바스크립트에서 pdf 출력하기 (html2canvas + jspdf)

https://rawgit.com/MrRio/jsPDF/master/docs/jsPDF.html jsPDF - Documentation The identity matrix (equivalent to new Matrix(1, 0, 0, 1, 0, 0)). Starts a new pdf form object, which means that all consequent draw calls target a new independent object until end

devlink.tistory.com

 

728x90
반응형