Vue中转换HTML为PDF
    		       		warning:
    		            这篇文章距离上次修改已过435天,其中的内容可能已经有所变动。
    		        
        		                
                在Vue中将HTML转换为PDF可以使用html2canvas和jspdf库。以下是一个简单的例子:
- 安装依赖库:
npm install html2canvas jspdf- 在Vue组件中使用这些库:
<template>
  <div>
    <div id="content">
      <!-- 这里是你想要转换成PDF的HTML内容 -->
      <h1>Hello World</h1>
      <p>这是一个PDF转换示例。</p>
    </div>
    <button @click="convertToPDF">转换为PDF</button>
  </div>
</template>
 
<script>
import html2canvas from 'html2canvas';
import jsPDF from 'jspdf';
 
export default {
  methods: {
    convertToPDF() {
      const content = this.$refs.content;
      html2canvas(content).then(canvas => {
        const imgData = canvas.toDataURL('image/png');
        const pdf = new jsPDF({
          orientation: 'portrait',
          unit: 'px',
          format: 'a4'
        });
        const imgProps= pdf.getImageProperties(imgData);
        const pdfWidth = pdf.internal.pageSize.getWidth();
        const pdfHeight = (imgProps.height * pdfWidth) / imgProps.width;
        pdf.addImage(imgData, 'PNG', 0, 0, pdfWidth, pdfHeight);
        pdf.save('download.pdf');
      });
    }
  }
};
</script>在这个例子中,我们定义了一个convertToPDF方法,它会在用户点击按钮时被调用。这个方法首先使用html2canvas库将指定DOM元素转换为canvas,然后使用jspdf库创建PDF文档,并将canvas的内容作为图片添加到PDF中。最后,使用save方法保存PDF文件。
评论已关闭