vue3实现把html页面转为图片


首先我们要把页面连接放在ifram中,利用html2canvas和Canvas2Image对页面进行转换

<template>

<div style="height: 90vh;"><iframe src="XXX.html" frameborder="0" height="90%" id="frameid" width="100%"></iframe></div>
<div id="img" v-html="html"></div>
<button @click="toPic">下载图片</button>

script

import html2canvas from 'html2canvas'
import Canvas2Image from './canvas2image/index'

const toPic = () => {
  const ifram: any = document.getElementById('frameid')
  const testbody: any = ifram.contentWindow.document.getElementById('testbody'); // textbody为XXX.html的body的id名称
  let canvas2 = document.createElement("canvas");
  let w = parseInt(window.getComputedStyle(testbody).width);
  let h = parseInt(window.getComputedStyle(testbody).height);
  let context =  canvas2.getContext("2d");
  context?.scale(1,1);
  canvas2.width = w;
  canvas2.height = h;
  html2canvas(testbody, {canvas: canvas2}).then((canvas: any) => {
  const data = document.getElementById('img');
  let img:any = Canvas2Image.convertToImage(canvas, w , h)
  data?.appendChild(img)
  // console.log(state.html)
  })
  }

Canvas2Image 下载地址 https://github.com/randreucetti/canvas2image
html2canvas 可以直接用npm安装: npm install html2canvas -S

pdf转图片同样适用


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM