在vue中将隐藏的div转换为pdf

Converting hidden div to pdf in vue

经过几个小时的研究,找到了一些将divs的内容导出为pdf的方法,包括所有样式。根据页面,vue-html2pdf不能正常工作,所以我使用了html2pdf。取一个div和ref转成pdf,同时下载:

<div ref="printable">Hello</div>
<button @click="export()">Export to PDF</button
export() {
    html2pdf(this.$refs.document, {
        margin: 1,
        filename: 'document.pdf',
        image: { type: 'jpeg', quality: 0.98 },
        html2canvas: { dpi: 192, letterRendering: true },
        jsPDF: { unit: 'in', format: 'letter', orientation: 'landscape' }
    })
},

问题是它包含所有样式,我无法导出隐藏的 div。有什么合适的方法可以做到这一点吗?

你可以使用CSS来避免它

HTML:

<div class="noPrint">
    Div which needs to be hidden when printing
</div>
<div class="showOnPrint" style="display:none">
    Hidden div which needs to be visible when printing
</div>

CSS:

@media print{
   .noPrint{
       display:none !important;
   }
   .showOnPrint{
       display:block !important;
   }
}

您可以为隐藏元素设置一个ref,并在p​​df生成之前移除隐藏属性,并在调用生成的函数后立即重新设置它。这里我编辑 sandbox. You can see a heading in the pdf which is hidden in the page.

<template>
      <div id="app" ref="document">
        <img width="200" src="./assets/logo.png">
        <router-view></router-view>
        <h1 ref="hide" hidden>This is shown in pdf</h1>
        <button @click="exportToPDF">Export to PDF</button>
      </div>
    </template>

<script>
  import html2pdf from "html2pdf.js";

  export default {
    name: "app",
    methods: {
      exportToPDF() {
        let data = Object.assign({}, this.$refs);
        data.hide.removeAttribute("hidden");
        html2pdf(data.document, {
          margin: 1,
          filename: "document.pdf",
          image: {
            type: "jpeg",
            quality: 0.98
          },
          html2canvas: {
            dpi: 192,
            letterRendering: true
          },
          jsPDF: {
            unit: "in",
            format: "letter",
            orientation: "landscape"
          }
        });
        data.hide.setAttribute("hidden", "hidden");
      }
    }
  };
</script>

<style>
  #app {
    font-family: "Avenir", Helvetica, Arial, sans-serif;
    -webkit-font-smoothing: antialiased;
    -moz-osx-font-smoothing: grayscale;
    text-align: center;
    color: #2c3e50;
    margin-top: 60px;
  }
</style>

从“html2pdf.js”导入 html2pdf; 上面的评论和它的所有者是 tuhin47 它有效,但它是 的版本 https://cdnjs.cloudflare.com/ajax/libs/html2pdf.js/0.8.2/html2pdf.js 它对我有用