需求:点击导出pdf按钮,弹出系统文件夹弹框,可以选择保存文件的位置。
经查询window.showSaveFilePicker可实现,但这个api处于实验阶段,且用下来确实和浏览器类型、浏览器版本、以及本身api就不稳定有关系。
代码见下:
<el-button @click="handleExportPdf">导出pdf</el-button>api.js接口文件:
// 获取PDF流
export function getHistoryCheckPdf(params) {return request({method: "post",url: `${baseUrlReportApp}docReport/gainReportPdf`,responseType: "arraybuffer",//指定响应流的类型data: params});
}
// node上传PDF文件流打印接口
export function nodePrintFile(data) {return request({baseURL: 'http://localhost:3080/printPdf', // 直接通过覆盖的方式data,method: 'post'})
}<script>
import { getHistoryCheckPdf,nodePrintFile } from "@/api";
export default {methods:{handleExportPdf(){this.fetchPDF();},async fetchPDF(isCloseReport) {getHistoryCheckPdf({stReportSoid: this.initializeInfo.stReportSoid,requestSoid: createListRequestSoid(this.initializeInfo)[0],}).then((res) => {if (res.byteLength < 10) {this.$message({message: "PDF未获取到,请稍后重试!",type: "warning",});return;}// 保存pdf到本地文件夹this.savePDF(res);// 打印pdf方法// this.handlerNodeResPrint(res, isCloseReport);});}}
},// 保存文件到指定位置async savePDF(res) {let curTime = moment().format("YYYY-MM-DD HH:mm:ss");let timeList = curTime.split(" ");let dateItem = timeList[0].split("-").join("");let timeItem = timeList[1].split(":").join("");let finaDate = dateItem + timeItem;let pdfName = finaDate + ".pdf";// ①保存文件到默认位置var blob = new Blob([res], { type: "application/octet-stream" });var url = window.URL.createObjectURL(blob);var link = document.createElement("a");link.href = url;link.download = pdfName;document.body.appendChild(link);link.click();document.body.removeChild(link);window.URL.revokeObjectURL(url);// ②保存文件到指定位置:不稳定,未使用// window.showSaveFilePicker此api尚在实验中,只支持https,且对浏览器有兼容// try {// const opts = {// types: [// {// description: "文件",// accept: {// "text/plain": [".txt"],// "application/pdf": [".pdf"],// "image/jpeg": [".jpg", ".jpeg"],// "image/png": [".png"],// },// },// ],// excludeAcceptAllOption: true,// suggestedName: pdfName,// };// const handle = await window.showSaveFilePicker(opts); // 打开保存文件对话框// const writable = await handle.createWritable(); // 创建可写入的文件对象// // 在这里写入文件内容// await writable.write(res);// await writable.close();// console.log("文件保存成功");// this.$message.success("文件保存成功");// } catch (error) {// console.error("文件保存失败:", error);// }},//打印方法handlerNodeResPrint(buffer, isCloseReport) {const formData = new FormData();formData.append("file", new Blob([buffer]));// formData.append("printName", "");formData.append("fileType", "pdf");formData.append("type", "server");formData.append("orientation", "landscape");formData.append("paperSize", "A5");// Node打印nodePrintFile(formData).then((res) => {if (res.code == 200) {this.$message.success("打印成功!!!");} else {this.$message.error(res.message);}});},},</script>