vue使用html2canvas和jspdf将html转成pdf

目录
  • A4尺寸
  • 安装插件html2canvas和jspdf
  • 在项目中引入
  • 遇到的问题
    • 多行省略号
    • 图片跨域Tainedcanvasesmaynotbeexported
    • base64DataURLscheme支持的类型:
  • 总结

A4尺寸

A4纸的尺寸是210mm×297mm。

分辨率是72像素/英寸时,A4纸的尺寸的图像的像素是595×842(推荐用这个大小比例)。

分辨率是150像素/英寸时,A4纸的尺寸的图像的像素是1240×1754。

分辨率是300像素/英寸时,A4纸的尺寸的图像的像素是2479×3508。

选择不同的分辨率图像像素大小也会随之变化

安装插件html2canvas和jspdf

npm install html2canvas--save
npm install jspdf --save

html2canvas可以通过获取HTML的某个元素,然后生成Canvas,能让用户保存为图片。

jsPDF 是一个基于 HTML5 的客户端解决方案,用于生成各种用途的 PDF 文档。

在项目中引入

在utils 中 新建htmltopdf.js

htmlToPdf.js

// 导出页面为PDF格式
import html2Canvas from 'html2canvas'
import JsPDF from 'jspdf'
export default{
  install (Vue, options) {
    Vue.prototype.getPdf = function () {
      var pdfTitle = this.pdfTitle  //pdf的名称
      var pdfDom = document.querySelector('#pdfDom')
      html2Canvas(pdfDom, {
        allowTaint: true
      }).then(function (canvas) {
        console.log(canvas)
        const marginBottom = 34    // 项目页面显示微处理 以下用到的地方 可以忽略
        let canvasWidth = canvas.width 	//页面生成canvas宽度
        let canvasHeight = canvas.height + marginBottom //页面生成canvas高度
        let pageHeight = canvasWidth / 592.28 * 841.89 + marginBottom   //分页 每页的高度
        let allPageHeight = canvasHeight  // 所有页面的高度
        let position = 0 //偏移量
        let imgWidth = 595.28 //生成canvas 图片的宽度
        let imgHeight = 592.28 / canvasWidth * canvasHeight //生成canvas 图片的高度
        let pageData = canvas.toDataURL('image/jpeg', 3.0)
        // console.log(canvasWidth)
        // console.log(canvasHeight)
        // console.log(pageHeight)
        // console.log(allPageHeight)
        // console.log(position)
        // console.log(imgWidth)
        // console.log(imgHeight)
        // console.log(pageData)
        let PDF = new JsPDF('', 'pt', 'a4')
        if (allPageHeight < pageHeight) {
          PDF.addImage(pageData, 'JPEG', 0, 0, imgWidth, imgHeight)
        } else {
          // 循环生成分页
          while (allPageHeight > 0) {
            PDF.addImage(pageData, 'JPEG', 0, position, imgWidth, imgHeight)
            allPageHeight = allPageHeight - pageHeight - marginBottom
            position = position - 841.89 - marginBottom
            if (allPageHeight > 0) {
              PDF.addPage() //添加新的一页
            }
          }
        }
        PDF.save(pdfTitle + '.pdf')  //保存pdf
      })
    }
  }
}

在main.ts 中 全局引入

main.ts

// The Vue build version to load with the `import` command
// (runtime-only or standalone) has been set in webpack.base.conf with an alias.
import 'babel-polyfill'
import Vue from 'vue'
import App from './App.vue'
import router from './router/index.ts'
import store from './store/index.js'
import * as ElementUI from 'element-ui'
import 'element-ui/lib/theme-chalk/index.css'
import htmlToPdf from '@/utils/htmlToPdf.js'
// 使用Vue.use()方法就会调用工具方法中的install方法
Vue.use(htmlToPdf)
// import 'swiper/dist/css/swiper.css'
// import * as VueAwesomeSwiper from 'vue-awesome-swiper'
// Vue.use(VueAwesomeSwiper)
Vue.config.productionTip = false
Vue.use(ElementUI)
/* eslint-disable no-new */
new Vue({
  el: '#app',
  router,
  store,
  components: { App },
  template: '<App/>'
})

vue 页面

<template>
  <div class="transcript-container clearfix transcript-detail" @mouseenter.stop="pdfFlag = false">
    <div class="creat-pdf clearfix" @click.stop="pdfFlag = true;getPdf('#pdfDom')">下载pdf</div>
    <div id="pdfDom" class="clearfix" style="width: 210mm;margin: auto;"> </div>
  </div>
</template>
<script lang="ts">
import { Vue, Component } from 'vue-property-decorator'
import { Getter, Action } from 'vuex-class'
@Component
export default class cousrseActivity extends Vue {
  @Getter commonData
  @Action transcriptDetail
  $refs: {
    onePage: HTMLElement,
    twoPage: HTMLElement
  }
  pdfTitle: string = ''
}
</script>
//对打印 做的 兼容
<style media="print" type="text/css">
  @page {
    size: auto;
    margin: 0mm;
  }
  /* 在chrome下可以使用background属性 */
  body {
    -webkit-print-color-adjust: exact;
  }
  @media print {
    .transcript-container.transcript-detail .transcript-wrap {
      margin-bottom: 0;
    }
  }
</style>

遇到的问题

多行省略号

多行省略号 在html2canvas 时 由于不能解析 display: -webkit-box; 会导致生成的图片 错误

.ellipsis{
  overflow : hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 2;      /* 可以显示的行数,超出部分用...表示*/
  -webkit-box-orient: vertical;
 }

目前 我这边正常显示时 使用多行省略号 在打印时 将 display: -webkit-box;改成display:blcok 就能正常显示了

图片模糊 生成的pdf 不清楚

解决办法: 将canvas的属性width和height属性放大为2倍,也就是,先将canvas高分辨率输出,再来压缩导出打印

// 导出页面为PDF格式
import html2Canvas from 'html2canvas'
import JsPDF from 'jspdf'
export default{
  install (Vue, options) {
    Vue.prototype.getPdf = function () {
      var pdfTitle = this.pdfTitle
      var pdfDom = document.querySelector('#pdfDom')
      var c = document.createElement('canvas')
      html2Canvas(pdfDom, {
        useCORS: true,
        scale: 2,
        canvas: c,
        logging: true,
        width: pdfDom.width,
        height: pdfDom.height
      // allowTaint: true
      }).then(function (canvas) {
        console.log(canvas)
        const marginBottom = 34
        let canvasWidth = canvas.width
        let canvasHeight = canvas.height + marginBottom * 2
        console.log(canvasWidth)
        console.log(canvasHeight)
        let pageHeight = canvasWidth / 592.28 * 841.89 + marginBottom * 2
        let allPageHeight = canvasHeight
        let position = 0
        let imgWidth = 595.28
        let imgHeight = 592.28 / canvasWidth * canvasHeight
        let pageData = canvas.toDataURL('image/jpeg', 3.0)
        // console.log(canvasWidth)
        // console.log(canvasHeight)
        // console.log(pageHeight)
        // console.log(allPageHeight)
        // console.log(position)
        // console.log(imgWidth)
        // console.log(imgHeight)
        // console.log(pageData)
        let PDF = new JsPDF('', 'pt', 'a4')
        if (allPageHeight < pageHeight) {
          PDF.addImage(pageData, 'JPEG', 0, 0, imgWidth, imgHeight)
        } else {
          while (allPageHeight > 0) {
            PDF.addImage(pageData, 'JPEG', 0, position, imgWidth, imgHeight)
            allPageHeight = allPageHeight - pageHeight - marginBottom
            position = position - 841.89 - marginBottom
            if (allPageHeight > 0) {
              PDF.addPage()
            }
          }
        }
        PDF.save(pdfTitle + '.pdf')
      })
    }
  }
}

处理过的图片 能清晰一点 但是生成的pdf 也大了一倍

图片跨域 Tained canvases may not be exported

在test 服务器上 一点问题都没有 可以正常下载 一大包到线上 就开始报跨域的错误

百度了一下 基本都是一样的 复制来 复制去 给的办法 还是没发处理跨域的问题

看了一下html2canvas api 发现了 一个属性 proxy 代理完的图片 但是还是报跨域的问题 生成的pdf 还是没有图片

最后发现 页面里边的图片可以正产显示 只有外域的图片不能显示 本域的图片用base64显示的 外域的图片是不是也能用base64显示

base64 Data URL scheme 支持的类型:

  • data:,文本数据
  • data:text/plain,文本数据
  • data:text/html,HTML代码
  • data:text/html;base64,base64编码的HTML代码
  • data:text/css,CSS代码
  • data:text/css;base64,base64编码的CSS代码
  • data:text/JavaScript,Javascript代码
  • data:text/javascript;base64,base64编码的Javascript代码
  • data:image/gif;base64,base64编码的gif图片数据
  • data:image/png;base64,base64编码的png图片数据
  • data:image/jpeg;base64,base64编码的jpeg图片数据

将外域 的图片弄成base64 后 生成的pdf里边的图片 可以正常显示了 也不报跨域的问题了

总结

到此这篇关于vue使用html2canvas和jspdf将html转成pdf的文章就介绍到这了,更多相关html2canvas jspdf将html转pdf内容请搜索我们以前的文章或继续浏览下面的相关文章希望大家以后多多支持我们!

(0)

相关推荐

  • Javascript保存网页为图片借助于html2canvas库实现

    第一步,把网页保存为Canvas画布,借助于html2canvas库,http://html2canvas.hertzen.com/ html2canvas(document.getElementById("id1"), { onrendered: function(canvas) { document.getElementById("id2").appendChild(canvas);//生成画布后如何处理,当然可以在新标签打开,在浮层展示等等 }, canvas

  • js使用html2canvas实现屏幕截取的示例代码

    整理文档,搜刮出一个js使用html2canvas实现屏幕截取的示例代码,稍微整理精简一下做下分享. <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=no"> <

  • html2canvas属性和使用方法以及如何使用html2canvas将HTML内容写入Canvas生成图片

    如何使用JS截取HTML页面为图片呢,下面为大家介绍一款JS截图插件html2canvas.js html2canvas.js 能够实现在用户浏览器端直接对整个或部分页面进行截屏. html2canvas.js可以将当页面渲染成一个Canvas图片,通过读取DOM并将不同的样式应用到这些元素上实现. 它不需要来自服务器任何渲染,整张图片都是在客户端浏览器创建.当 浏览器不支持Canvas时,将采用Flashcanvas或ExplorerCanvas技术代替实现. 以下浏览器能够很好的支持该脚本:

  • vue 使用html2canvas将DOM转化为图片的方法

    一.前言 我发现将DOM转化为图片是一个非常常见的需求,而自己手动转是非常麻烦的,于是找到了html2canvas这个插件,既是用得比较多的也是维护得比较好的一个插件. 注意:版本比较多,这里介绍最新版 二.代码 1. 安装 npm install html2canvas --save 现在最新的版本应该是1.0.0,另外还有一个比较经典的版本是0.5.0,网上有许多关于这个版本的bug说明. 2. 使用 <div class="imageWrapper" ref="i

  • jsPDF生成pdf后在网页展示实例

    复制代码 代码如下: <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=GBK"> <title>jsPDF</title> <script type="text/javascript" src="jspdf.js"></script> <s

  • jsPDF导出pdf示例

    jsPDF貌似不支持中文 复制代码 代码如下: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en&q

  • vue使用html2canvas和jspdf将html转成pdf

    目录 A4尺寸 安装插件html2canvas和jspdf 在项目中引入 遇到的问题 多行省略号 图片跨域Tainedcanvasesmaynotbeexported base64DataURLscheme支持的类型: 总结 A4尺寸 A4纸的尺寸是210mm×297mm. 分辨率是72像素/英寸时,A4纸的尺寸的图像的像素是595×842(推荐用这个大小比例). 分辨率是150像素/英寸时,A4纸的尺寸的图像的像素是1240×1754. 分辨率是300像素/英寸时,A4纸的尺寸的图像的像素是2

  • vue中将网页打印成pdf实例代码

    整理文档,搜刮出一个vue中将网页打印成pdf的代码,稍微整理精简一下做下分享. <template> <div class="pdf-wrap" id="pdfWrap"> <button v-on:click="getPdf">点击下载PDF</button> <div class="pdf-dom" id="pdfDom"></div&

  • Vue如何将页面导出成PDF文件

    本文实例为大家分享了Vue将页面导出成PDF文件的具体代码,供大家参考,具体内容如下 我在前端岗位上要实现个可视化图表页的PDF文件导出,在这里给大家分享下使用jsPDF和html2canvas包将Vue页面导出成PDF的方法. 1. 下载npm包 npm install html2canvas npm install jspdf 2. 创建插件.js文件 Vue-cli项目的话是在./utils文件夹下,我在这里使用的nuxt框架,所以是在./plugins文件夹下. import html2

  • vue打包的时候自动将px转成rem的操作方法

    px2rem-loader 需要与 flexible 配合使用,不然px2rem仅仅只是转成rem却不会设置rem的信息 安装 flexible npm i lib-flexible -S 然后在main.js中引入 import 'lib-flexible/flexible' 直接引入的文件需要有优先与引用的组件 安装px2rem-loader npm i px2rem-loader -D 在build的utils.js中找到cssLoader添加一下代码 const px2remLoader

  • vue项目或网页上实现文字转换成语音播放功能

    一.在网页上实现文字转换成语音 方式一: 摘要:语音合成:也被称为文本转换技术(TTS),它是将计算机自己产生的.或外部输入的文字信息转变为可以听得懂的.流利的口语输出的技术. 1. 使用百度的接口: http://tts.baidu.com/text2audio?lan=zh&ie=UTF-8&spd=2&text=你要转换的文字 2.参数说明: lan=zh:语言是中文,如果改为lan=en,则语言是英文. ie=UTF-8:文字格式. spd=2:语速,可以是1-9的数字,数

  • Vue网页html转换PDF(最低兼容ie10)的思路详解

    HTML转PDF: 1.页面底层实现--Vue:最低兼容ie10 2.实现思路: 1> 使用html2canvas.js将网页转换为图片 2> 使用jsPdf.debug.js将canvas生成的图片转换为pdf文件 具体实现: 要这样实现首先要引入两个插件: html2canvas.js jsPdf.debug.js 注: 因为ie10在canvas截图时候会出现部分样式丢失的情况,所以在代码中有部分修改了页面的样式 所以建议在做截图的时候,将页面代码复制一份到隐藏域,在隐藏域里面做修改,这

  • vue导出html、word和pdf的实现代码

    导出的页面组件如下: <template> <div id="resumeId"> <resumeHtml ref="resume" @on-download="download"/> </div> </template> 1.导出html 方法: 1)获取要导出的组件页面的css把它设置成js变量一文本并通过export导出 2)获取要导出组件页面的html的dom标签代码,通过thi

  • Vue将页面导出为图片或者PDF

    本文实例为大家分享了Vue导出页面为PDF格式的具体代码,供大家参考,具体内容如下 导出为图片 1.将页面html转换成图片 npm install html2canvas --save 2.在需要导出的页面引入 import html2canvas from 'html2canvas'; 在 methods 中添加方法 dataURLToBlob(dataurl) {//ie 图片转格式 var arr = dataurl.split(','), mime = arr[0].match(/:(

  • vue实现pdf导出解决生成canvas模糊等问题(推荐)

    最近公司项目需要,利用vue实现pdf导出,从而保存到本地打印出来,说起来好像也很容易,具体要怎么实现呢? 1  .我们要添加两个模块 1 第一个.将页面html转换成图片 2 npm install --save html2canvas 3 第二个.将图片生成pdf 4 npm install jspdf --save 2 .定义全局函数 .. 创建一个htmlToPdf .js 文件在指定位置 . 我个人习惯放在 ( ' src /utils/htmlToPdf' ) // 导出页面为PDF

随机推荐