使用vue3导出pdf
首先下载依赖包 npm i vue3-html2pdf
在.vue文件中引入Vue3Html2pdf组件
import Vue3Html2pdf from 'vue3-html2pdf'
使用Vue3Html2pdf组件
<Vue3Html2pdf
:show-layout="false"
:float-layout="true"
:enable-download="false"
:preview-modal="true"
:paginate-elements-by-height="2500"
filename="hee hee"
:pdf-quality="2"
:manual-pagination="false"
pdf-format="a4"
pdf-orientation="landscape"
pdf-content-width="800px"
ref="html2Pdf"
>
<!--插槽内容就是需要导出的pdf内容-->
<template v-slot:pdf-content>
<vxe-table
ref="tableRef"
:row-config="{ isHover: true }"
:export-config="{}"
border
:data="newsPageList"
>
<!-- <vxe-column type="checkbox" width="60"></vxe-column> -->
<vxe-column
type="seq"
width="80"
title="序号"
align="center"
></vxe-column>
<vxe-column
width="80"
title="新闻类型"
align="center"
field="category"
></vxe-column>
<vxe-column
width="80"
title="新闻作者"
align="center"
field="author"
></vxe-column>
<vxe-column
title="新闻标题"
align="center"
field="title"
></vxe-column>
<vxe-column title="新闻图片" align="center" width="150">
<template #default="{ row }">
<!-- 在导出这些图片时,出现了跨域问题,用getProxyImage的方法,传入图片地址,用本地搭建的服务器进行转发,解决跨域
/> -->
<img
:src="getProxyImage(row.image)"
alt=""
style="width: 100px"
/>
</template>
</vxe-column>
</vxe-table>
</template>
</Vue3Html2pdf>
随便创建一个点击事件,导出pdf,需要用上生成pdf的方法generatePdf()
// 点击事件里导出pdf
const exportPDF = () => {
//调用导出方法
//html2pdf是ref对象需要自己创建
html2Pdf.value?.generatePdf()
}
getProxyImage函数将图片请求转发到代理服务器
const getProxyImage = (imageUrl) => {
// 将图片请求转发到代理服务器
const proxyUrl = `http://localhost:3000/proxy?url=${encodeURIComponent(
imageUrl,
)}`
/* const proxyUrl = `http:localhost:3000/proxy?url=${
imageUrl,
}` */
console.log(proxyUrl);
return proxyUrl
}
搭建一个本地服务器,在运行项目之前需要将本地服务器先跑起来
const express = require('express');
const axios = require('axios');
const cors = require('cors');
const app = express();
const port = 3000;
app.use(cors());
// 处理代理请求
app.get('/proxy', async (req, res) => {
try {
// 获取传入的原始图片URL参数
const imageUrl = req.query.url;
console.log(imageUrl);
// 发起对原始图片URL的请求
const response = await axios.get(imageUrl, {
responseType: 'arraybuffer', // 以二进制形式接收响应数据
});
// 设置响应头,将响应数据返回给客户端
res.set('Content-Type', response.headers['content-type']);
res.send(response.data);
} catch (error) {
console.error('代理请求出错:', error);
res.status(500).send('代理请求出错');
}
});
app.listen(port, () => {
console.log(`代理服务器已启动,监听端口 ${port}`);
});
注意:需要下载依赖包 npm i express axios cors