vue导出pdf文件(汇总)

方法一:vue-print-nb插件

官网地址

npm安装
npm install vue-print-nb --save
main.js全局注册
import Print from 'vue-print-nb'

Vue.use(Print);
组件使用
<template>
  <div class="home">
    <button v-print="printObj">导出pdf</button>
    <div id="printMe" style="background:red;">
      <p style="color:green;">评标区</p>
      <h1 style="font-size:20px;color:blue;">标题</h1>
      <img alt="Vue logo" src="../assets/logo.png" />
      <HelloWorld msg="Welcome to Your Vue.js App" />
    </div>
  </div>
</template>
<script>
import HelloWorld from '@/components/HelloWorld.vue'

export default {
  name: 'Home',
  components: {
    HelloWorld,
  },
  data() {
    return {
      printObj: {
        id: 'printMe',
        popTitle: '打印标题控制'
      },
    }
  },
}
</script>
<style lang="scss" scoped>
#printMe {
  p {
    text-align: center;
    font-size: 100px;
  }
}
</style>
效果图

在这里插入图片描述

总结

优点:使用简单方便
缺点:组件的css样式未呈现,写在当前vue文件下的样式,如行内样式以及嵌入css样式均可呈现。

方法二:window.print()方法

<template>
  <div class="home">
    <button @click="handleWindowPrint('#printMe', '测试标题')">导出pdf</button>
    <div id="printMe" style="background:red;">
      <p style="color:green;">评标区</p>
      <h1 style="font-size:20px;color:blue;">标题</h1>
      <img alt="Vue logo" src="../assets/logo.png" />
      <img src="https://p0.ssl.img.360kuai.com/t01aa74816148bbc24a.webp" />
      <HelloWorld msg="Welcome to Your Vue.js App" />
    </div>
  </div>
</template>
<script>
import HelloWorld from '@/components/HelloWorld.vue'

export default {
  name: 'Home',
  components: {
    HelloWorld,
  },
  data() {
    return {}
  },
  methods: {
    handleWindowPrint(ele, fileName) {
      var oIframe = document.createElement('iframe')
      var oScript = document.createElement('script')
      document.body.appendChild(oIframe)
      var titleText = document.head.getElementsByTagName('title')[0].innerText
      document.head.getElementsByTagName('title')[0].innerText = `${fileName}`
      oIframe.contentDocument.head.innerHTML = `<meta charset="utf-8">
                                              <title>${fileName}</title>
                                              <meta name="format-detection" content="telephone=no">
                                              <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
                                              <meta name="viewport" content="width=device-width,initial-scale=1.0">`
      oIframe.contentDocument.body.innerHTML = document.querySelector(
        ele
      ).outerHTML
      oScript.innerHTML = 'window.print();'
      oIframe.contentDocument.body.appendChild(oScript)
      document.body.removeChild(oIframe)
      document.head.getElementsByTagName('title')[0].innerText = titleText
    },
  },
}
</script>
<style lang="scss" scoped>
#printMe {
  p {
    text-align: center;
    font-size: 100px;
  }
}
</style>
总结(不推荐使用)

优点:不需要依赖
缺点:只有行内样式可呈现,不合适。此外,本地图片会丢失,因为使用的是iframe方式,图片只能使用网络连接才能访问。不推荐使用

参考详情

方法三:html2canvas+jspdf

npm安装
第一个.将页面html转换成图片
npm install --save html2canvas 
第二个.将图片生成pdf
npm install jspdf --save
定义全局函数

创建一个htmlToPdf.js文件在指定位置。我个人习惯放在src/components/utils/htmlToPdf

// 导出页面为PDF格式
import html2Canvas from 'html2canvas'
import JsPDF from 'jspdf'
export default{
  install (Vue) {
    Vue.prototype.getPdf = function () {
      var title = this.htmlTitle
      html2Canvas(document.querySelector('#pdfDom'), {
        allowTaint: true
      }).then(function (canvas) {
        let contentWidth = canvas.width
        let contentHeight = canvas.height
        let pageHeight = contentWidth / 592.28 * 841.89
        let leftHeight = contentHeight
        let position = 0
        let imgWidth = 595.28
        let imgHeight = 592.28 / contentWidth * contentHeight
        let pageData = canvas.toDataURL('image/jpeg', 1.0)
        let PDF = new JsPDF('', 'pt', 'a4')
        if (leftHeight < pageHeight) {
          PDF.addImage(pageData, 'JPEG', 0, 0, imgWidth, imgHeight)
        } else {
          while (leftHeight > 0) {
            PDF.addImage(pageData, 'JPEG', 0, position, imgWidth, imgHeight)
            leftHeight -= pageHeight
            position -= 841.89
            if (leftHeight > 0) {
              PDF.addPage()
            }
          }
        }
        PDF.save(title + '.pdf')
      }
      )
    }
  }
}
在main.js中使用我们定义的函数文件
import htmlToPdf from '@/components/utils/htmlToPdf'
Vue.use(htmlToPdf)
在main.js中使用我们定义的函数文件
import htmlToPdf from '@/components/utils/htmlToPdf'
Vue.use(htmlToPdf)
在需要的导出的页面…调用我们的getPdf方法即可
<template>
  <div class="home">
    <button type="button" class="btn btn-primary" v-on:click="getPdf()">
      导出PDF
    </button>
    <div id="pdfDom" style="background:red;">
      <p style="color:green;">评标区</p>
      <h1 style="font-size:20px;color:blue;">标题</h1>
      <img alt="Vue logo" src="../assets/logo.png" />
      <!-- <img src="https://p0.ssl.img.360kuai.com/t01aa74816148bbc24a.webp" /> -->
      <HelloWorld msg="Welcome to Your Vue.js App" />
    </div>
  </div>
</template>

直接在data中写入htmlTitle即可

export default {
  name: 'Home',
  components: {
    HelloWorld,
  },
  data() {
    return {
      htmlTitle: '页面导出PDF文件名',
    }
  }
}
效果图

在这里插入图片描述

总结(强烈推荐使用)

优点:完美的呈现页面样式效果,无论是外联css还是组件内部的css均有效果。
缺点:外链图片不能使用,会报错;不够清晰
参考详情01
参考详情02

  • 11
    点赞
  • 72
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
可以使用jsPDF和html2canvas两个库来实现在Vue导出PDF文件。使用html2canvas将要导出的HTML元素转为Canvas,使用jsPDF将Canvas转换为PDF文件进行下载或预览。以下是一个简单的示例代码: 1. 安装jsPDF和html2canvas库 ``` npm install jspdf html2canvas ``` 2. 在Vue组件中引入jsPDF和html2canvas ```js import jsPDF from 'jspdf' import html2canvas from 'html2canvas' ``` 3. 在Vue组件中定义导出PDF的方法 ```js export default { data() { return { // 定义要导出PDF的HTML元素选择器 selector: '#pdf-content' } }, methods: { // 导出PDF方法 exportPDF() { // 获取要导出PDF的HTML元素 const pdfContent = document.querySelector(this.selector) // 调用html2canvas将HTML元素转换为Canvas html2canvas(pdfContent).then(canvas => { // 创建jsPDF实例 const pdf = new jsPDF('p', 'pt', 'a4') // 获取Canvas的宽高 const canvasWidth = canvas.width const canvasHeight = canvas.height // 将Canvas转换为PNG图片 const imgData = canvas.toDataURL('image/png') // 添加图片到PDF并设置图片宽高为Canvas的宽高 pdf.addImage(imgData, 'PNG', 0, 0, canvasWidth, canvasHeight) // 保存或预览PDF文件 pdf.save('export.pdf') // 或者打开一个新窗口显示PDF文件 // const pdfWindow = window.open('') // pdfWindow.document.write('<iframe width="100%" height="100%" src="' + pdf.output('datauristring') + '"></iframe>') }) } } } ``` 4. 在HTML模板中添加要导出PDF的HTML元素以及导出按钮 ```html <template> <div> <!-- 要导出PDF的HTML元素 --> <div id="pdf-content"> ... </div> <!-- 导出按钮 --> <button @click="exportPDF()">导出PDF</button> </div> </template> ``` 需要注意的是,导出PDF的HTML元素必须符合jsPDF和html2canvas库的要求,例如样式必须在HTML中定义,不能使用外部CSS,否则可能导致导出PDF样式不正确。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值