vue导出当前页面为pdf,然后保存到后端

前端

  1. 安装html2canvas和jspdf依赖
	npm install html2canvas --save
	npm install jspdf --save  
(如果jspdf 报错,则在index.js中引入
<scriptsrc="https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.3.2/jspdf.debug.js"></script>
  1. 在utils中创建htmlToPdf.js文件,并复制以下代码
	// 导出页面为PDF格式
import html2Canvas from 'html2canvas'
//import JsPDF from 'jspdf'
export default{
  install (Vue, options) {
    Vue.prototype.getPdf = function () {
      var title = "测评报告"; //pdf名称
      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    //575.28
        let imgHeight = 592.28 / contentWidth * contentHeight //582.28
        let pageData = canvas.toDataURL('image/jpeg', 1.0)
        let PDF = new jsPDF('', 'pt', 'a4')   //jsPDF要小写,因为是cdn引入,可以打开链接看源码
        if (leftHeight < pageHeight) {
         //(pageData, 'JPEG', 左边距 ,上边距,宽,高)
          PDF.addImage(pageData, 'JPEG', 0, 0, imgWidth, imgHeight) //10 20
        } else {
          while (leftHeight > 0) {
            PDF.addImage(pageData, 'JPEG', 0, position, imgWidth, imgHeight) //10
            leftHeight -= pageHeight
            position -= 841.89
            if (leftHeight > 0) {
              PDF.addPage()
            }
          }
        }
        PDF.save(title + '.pdf')
      }
      )
    }
  }
}
  1. main.js中引入上面那个htmlToPdf文件
import htmlToPdf from '@/components/Utils/htmlToPdf'
Vue.use(htmlToPdf)
  1. 在vue页面中调用
	 <div id="pdfDom">
 	//这里是要导出的html内容
    <el-button @click="getPdf()">保存为PDF</el-button>
 </div>
  1. 后端
 @PostMapping("test")
    @ApiOperation("测试")
    public R test(@RequestParam("file") MultipartFile file){
		System.out.println(file);
		String fileName = file.getOriginalFilename();
		if(fileName.indexOf("\\") != -1){
			fileName = fileName.substring(fileName.lastIndexOf("\\"));
		}
		String filePath = "src/main/resources/static/files/";
		File targetFile = new File(filePath);
		if(!targetFile.exists()){
			targetFile.mkdirs();
		}
		FileOutputStream out = null;
		try {
			out = new FileOutputStream(filePath+fileName);
			out.write(file.getBytes());
			out.flush();
			out.close();
		} catch (Exception e) {
			e.printStackTrace();
			return R.error();
		}
		return R.ok();
 
 
	}

注意:如果要导出的文件内容超出了当前页面,会导致导出的内容不全。需要在htmlToPdf中加入两句话: height: document.getElementById('pdfDom').scrollHeight, windowHeight: document.getElementById('pdfDom').scrollHeight
修改后的文件:

// 导出页面为PDF格式
import html2Canvas from 'html2canvas'
import JsPDF from 'jspdf'
export default{
  install (Vue, options) {
    Vue.prototype.getPdf = function () {
      var title = this.htmlTitle
      html2Canvas(document.querySelector('#pdfDom'), {
        allowTaint: true,
        taintTest: false,
        useCORS: true,
        dpi: window.devicePixelRatio * 6, //将分辨率提高到特定的DPI 提高四倍
        scale: 6, //按比例增加分辨率
        height: document.getElementById('pdfDom').scrollHeight,
        windowHeight: document.getElementById('pdfDom').scrollHeight
      }).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')
      }
      )
    }
  }
}

参考链接:https://blog.csdn.net/qq_36802726/article/details/110624402

Logo

魔乐社区(Modelers.cn) 是一个中立、公益的人工智能社区,提供人工智能工具、模型、数据的托管、展示与应用协同服务,为人工智能开发及爱好者搭建开放的学习交流平台。社区通过理事会方式运作,由全产业链共同建设、共同运营、共同享有,推动国产AI生态繁荣发展。

更多推荐