js(vue)如何实现页面截图,向后端传递,生成PDF

2024-09-05 09:28

本文主要是介绍js(vue)如何实现页面截图,向后端传递,生成PDF,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

利用 htmm12canvas

首先引入

npm install express multer
# 或者
yarn add express multer

代码如下:

<template><!-- <div style="width:100%;height:100%;overflow-y: scroll"><img :src="svg" style="width: 100%;" /></div> --><div class="backScreen">中间代码省略</div>
</template><script setup>import { nextTick, ref, provide } from "vue";
import { useGetResizeBodySize } from '@/hooks/useGetScaleHeight'import EquConsumeSpareRank from './charts/EquConsumeSpareRank'
import EquPurchaseSpareRank from './charts/EquPurchaseSpareRank'
import SpareConsumeRank from './charts/SpareConsumeRank'
import SpareOverView from './charts/SpareOverView'
import StoreAvgDurationRank from './charts/StoreAvgDurationRank'
import StoreInactive from './charts/StoreInactive'import img169 from './imgs/dp_16.9.svg'
import img1610 from './imgs/dp_16.10.svg'
import html2canvas from 'html2canvas';const imageWidth = ref('100%')
const imageHeight = ref('100%')
const backImg = ref(img169)
const fullScreen = ref(false)
const margin = ref(0)provide('screenHeight', imageHeight)useGetResizeBodySize(e => {const { screenWidth, screenHeight } = eimageWidth.value = screenWidthimageHeight.value = screenHeightconsole.log('imageHeight.value', imageHeight.value)// 上下的marginmargin.value = imageHeight.value * 0.02// console.log('outer', window.outerWidth, window.outerHeight, screenWidth, screenHeight)const ratio = screenWidth/screenHeightif (ratio === 16/9 || ratio === 16/10) {fullScreen.value = true}if (ratio === 16/10) {backImg.value = img1610}else {backImg.value = img169}})// 定义截图和发送截图的方法   下面是关键代码
const captureScreen = async () => {return new Promise((resolve, reject) => {nextTick(() => {html2canvas(document.querySelector('.backScreen'), {logging: false,scale: 2,useCORS: true,}).then(canvas => {canvas.toBlob(blob => resolve(blob), 'image/png');}).catch(err => reject(err));});});
};const sendToServer = async (blob) => {try {const formData = new FormData();formData.append('image', blob, 'screenshot.png');console.log("发送图片给后台")const response = await fetch('http://127.0.0.1:8081/test/upload-image', {method: 'POST',body: formData,});if (!response.ok) {throw new Error(`HTTP error! Status: ${response.status}`);}const data = await response.json();console.log(data);} catch (error) {console.error('Failed to send screenshot:', error);}
};// 监听键盘事件
const handleKeyPress = (event) => {// 检查是否按下了 "O" 键if (event.key === 'o' || event.keyCode === 79) {console.log("O键被按下")event.preventDefault(); // 防止默认行为captureScreen().then(blob => {sendToServer(blob);}).catch(error => {console.error('Error capturing screen:', error);});}
};// 在组件挂载后添加键盘事件监听器
onMounted(() => {document.addEventListener('keydown', handleKeyPress);// 清除引用以防止内存泄漏onUnmounted(() => {document.removeEventListener('keydown', handleKeyPress);});
});</script><style lang="scss" scoped>
:deep .el-input__wrapper {height: 22px;font-size: 10px;background-color: #ABD6FF;// background-color: transparent;/* border: 0px !important; */box-shadow: none;
}
.chartRow {width: 100%;height: 400;display: flex;justify-content: space-between;
}
.backScreen {width: 100%;height: 100%;display: flex;justify-content: center;// align-items: center;position: relative;// overflow: auto;// background-color: lightgray;// background-image: url('./img/bk.svg');// background-size: cover;// background-clip: border-box;// background-repeat: no-repeat;.backImg {position: absolute;left: 0;top: 0;right: 0;bottom: 0;}.contentBack {// background-color: white;// margin: 11% 120px;margin-top: 6%;margin-left: 6%;margin-right: 6%;flex: 1;z-index: 10;height: 82%;.card {width: 430px;height: 100%;// height: 370px;background-size: 100% 100%;background-color: #0241A2;border-radius: 20px;overflow: hidden;display: flex;flex-direction: column;.card_title {width: 100%;height: 46px;background: linear-gradient(#1187FB, #0241A2);border-radius: 20px 20px 0 0;padding: 13px 0 0 24px;color: #30D9FF}}.cardMax {// height: 370px;height: 100%;background-size: 100% 100%;background-color: #0241A2;border-radius: 20px;display: flex;flex-direction: column;flex: 1;overflow: hidden;.cardMax_title {width: 100%;height: 46px;background: linear-gradient(#1187FB, #0241A2);border-radius: 20px 20px 0 0;padding: 13px 0 0 24px;color: #30D9FF}}}}
</style>

然后是后台很简单的实现,至于生成PDF再说


@RestController
@RequestMapping("test")
@Api(value = "ImageUploadController", tags = "截图导入接口")
public class ImageUploadController {@PostMapping("/upload-image")public ServiceResponse<String> handleFileUpload(@RequestParam("image") MultipartFile file) {if (file.isEmpty()) {throw new RuntimeException("文件为空");}ServiceResponse<String> response = new ServiceResponse<>();// 将图片保存到 D:\tu\ 目录下String filePath = "D:\\tu\\" + file.getOriginalFilename();try {file.transferTo(new File(filePath));response.setSucess("上传成功");} catch (Exception e) {response.setError("上传失败");}return response;}
}

如果是针对指定范围的

就在其div加上唯一id

<div id="inactive-store-div" class="chartRow" :style="{'marginTop': margin + 'px', height: (0.4 * imageHeight) + 'px'}"><div class="card"><div class="card_title"><span>设备采购备件排名</span></div><EquPurchaseSpareRank :width="'430'" :height="'260'" @equCountsMfrs="equCountsMfrs"></EquPurchaseSpareRank></div><div class="cardMax" :style="{'margin-left': margin + 'px', 'margin-right': margin + 'px'}"><div class="cardMax_title"><span>备件消耗量排名</span></div><SpareConsumeRank :width="'800'" :height="'260'" @equCountsMfrs="equCountsMfrs"></SpareConsumeRank></div><div class="card"><div class="card_title"><span>呆滞库存统计</span></div><StoreInactive :width="'455'" :height="'260'" @equCountsMfrs="equCountsMfrs"></StoreInactive></div></div>

然后这里js改成

const captureScreen = async () => {return new Promise((resolve, reject) => {nextTick(() => {// html2canvas(document.querySelector('.backScreen'), {   //针对全屏html2canvas(document.querySelector('#inactive-store-div'), {   //针对指定的范围logging: false,scale: 2,useCORS: true,}).then(canvas => {canvas.toBlob(blob => resolve(blob), 'image/png');}).catch(err => reject(err));});});
};

这篇关于js(vue)如何实现页面截图,向后端传递,生成PDF的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/1138570

相关文章

java中pdf模版填充表单踩坑实战记录(itextPdf、openPdf、pdfbox)

《java中pdf模版填充表单踩坑实战记录(itextPdf、openPdf、pdfbox)》:本文主要介绍java中pdf模版填充表单踩坑的相关资料,OpenPDF、iText、PDFBox是三... 目录准备Pdf模版方法1:itextpdf7填充表单(1)加入依赖(2)代码(3)遇到的问题方法2:pd

Python操作PDF文档的主流库使用指南

《Python操作PDF文档的主流库使用指南》PDF因其跨平台、格式固定的特性成为文档交换的标准,然而,由于其复杂的内部结构,程序化操作PDF一直是个挑战,本文主要为大家整理了Python操作PD... 目录一、 基础操作1.PyPDF2 (及其继任者 pypdf)2.PyMuPDF / fitz3.Fre

python设置环境变量路径实现过程

《python设置环境变量路径实现过程》本文介绍设置Python路径的多种方法:临时设置(Windows用`set`,Linux/macOS用`export`)、永久设置(系统属性或shell配置文件... 目录设置python路径的方法临时设置环境变量(适用于当前会话)永久设置环境变量(Windows系统

Python对接支付宝支付之使用AliPay实现的详细操作指南

《Python对接支付宝支付之使用AliPay实现的详细操作指南》支付宝没有提供PythonSDK,但是强大的github就有提供python-alipay-sdk,封装里很多复杂操作,使用这个我们就... 目录一、引言二、准备工作2.1 支付宝开放平台入驻与应用创建2.2 密钥生成与配置2.3 安装ali

Spring Security 单点登录与自动登录机制的实现原理

《SpringSecurity单点登录与自动登录机制的实现原理》本文探讨SpringSecurity实现单点登录(SSO)与自动登录机制,涵盖JWT跨系统认证、RememberMe持久化Token... 目录一、核心概念解析1.1 单点登录(SSO)1.2 自动登录(Remember Me)二、代码分析三、

PyCharm中配置PyQt的实现步骤

《PyCharm中配置PyQt的实现步骤》PyCharm是JetBrains推出的一款强大的PythonIDE,结合PyQt可以进行pythion高效开发桌面GUI应用程序,本文就来介绍一下PyCha... 目录1. 安装China编程PyQt1.PyQt 核心组件2. 基础 PyQt 应用程序结构3. 使用 Q

Python实现批量提取BLF文件时间戳

《Python实现批量提取BLF文件时间戳》BLF(BinaryLoggingFormat)作为Vector公司推出的CAN总线数据记录格式,被广泛用于存储车辆通信数据,本文将使用Python轻松提取... 目录一、为什么需要批量处理 BLF 文件二、核心代码解析:从文件遍历到数据导出1. 环境准备与依赖库

linux下shell脚本启动jar包实现过程

《linux下shell脚本启动jar包实现过程》确保APP_NAME和LOG_FILE位于目录内,首次启动前需手动创建log文件夹,否则报错,此为个人经验,供参考,欢迎支持脚本之家... 目录linux下shell脚本启动jar包样例1样例2总结linux下shell脚本启动jar包样例1#!/bin

go动态限制并发数量的实现示例

《go动态限制并发数量的实现示例》本文主要介绍了Go并发控制方法,通过带缓冲通道和第三方库实现并发数量限制,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面... 目录带有缓冲大小的通道使用第三方库其他控制并发的方法因为go从语言层面支持并发,所以面试百分百会问到

Go语言并发之通知退出机制的实现

《Go语言并发之通知退出机制的实现》本文主要介绍了Go语言并发之通知退出机制的实现,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧... 目录1、通知退出机制1.1 进程/main函数退出1.2 通过channel退出1.3 通过cont