기본 콘텐츠로 건너뛰기

웹페이지에서 화면을 pdf로 다운로드 하기, 바로 출력 시 - javascript

웹페이지에서 화면을 pdf로 다운로드 하거나 바로 출력하기


html 부분

<section ref="pdfRef">
  <div class="winpop">
    <section id="first-section">
      ...
    </section>
    ...
  </div>
</section>

스크립트 부분

import { ref } from "vue";
import html2canvas from "html2canvas";
import { jsPDF } from "jspdf";

const pdfRef = ref(null);

// pdf 다운로드
const generatePDF = () => {
  const winpop = document.querySelector(".winpop");
  winpop.style.height = "auto";
  //loading.value = true;
  html2canvas(pdfRef.value, {
    scrollX: 0,
    scrollY: 0,
    scale: 3,
    logging: false,
    // useCORS:true
  }).then(canvas => {
    let image = canvas.toDataURL("image/jpg");
    const doc = new jsPDF("p", "mm", "a4", true);
    winpop.style.scroll = "auto";

    const section = document.querySelector("#first-section");

    let resolution = 3.833333;
    let imgWidth = section.offsetWidth / resolution;
    let pageHeight = (imgWidth * 1.414285714285); // 1.414
    let imgHeight = (canvas.height * imgWidth / canvas.width);
    let heightLeft = imgHeight;
    let position = 0;
    
    doc.addImage(image, "jpg", 0, position, imgWidth, imgHeight, "", "FAST");
    heightLeft -= pageHeight;

    while (heightLeft >= 20) {
      position = heightLeft - imgHeight;
      doc.addPage();
      doc.addImage(image, "jpg", 0, position, imgWidth, imgHeight, "", "FAST");
      heightLeft -= pageHeight;
    }

    doc.save(`${info.value.pdfname}_정보.pdf`);
    //loading.value = false;

    // window.open(doc.output("bloburl"));
    winpop.style.height = "100vh";
  })
}

// 바로 출력하기
const print = () => {
  const winpop = document.querySelector(".winpop");
  winpop.style.height = "auto";
  //loading.value = true;
  html2canvas(pdfRef.value, {
    scrollX: 0,
    scrollY: 0,
    scale: 3,
    logging: false,
    useCORS:true
  }).then(canvas => {
    let image = canvas.toDataURL("image/png");
    winpop.style.scroll = "auto";

    let link = document.createElement("a");
    document.body.appendChild(link);

    const width = 805;
    const height = width * 1.414;
    let win = window.open("", "_blank", `width=${width}; height=${height};`);
    win.document.write(`
    <html>
      <head>
        <link href="" rel="stylesheet">
      </head>
      <body>
        <img src="${image}" frameborder="0" style="border:0; top:0px; left:0px; bottom:0px; right:0px; width:${width}px; height:${height}px;"/>
      </body>
    </html>`);
    let style = win.document.createElement("style");
    style.innerHTML = "@page {size: A4;margin: 0;@media print {html, body {width: 210mm;height: 297mm;}";
    win.document.head.append(style);

    setTimeout(() => {
      win.print();
      win.close();
    })

    winpop.style.height = "100vh";
    //loading.value = false;
  })
}

굳이 웹 화면을 pdf로 저장할 때 사용할 수 있다.


끝.