hrms-user/src/plugins/genreport.ts

60 lines
2 KiB
TypeScript
Raw Normal View History

import axios from "axios";
2024-11-18 10:22:56 +07:00
import config from "@/app.config";
import { useCounterMixin } from "@/stores/mixin";
const mixin = useCounterMixin();
2025-06-06 10:38:41 +07:00
const { showLoader, hideLoader } = mixin;
2024-11-18 10:22:56 +07:00
async function genReport(data: any, fileName: string, type: string = "docx") {
showLoader();
await axios
2024-11-18 10:22:56 +07:00
.post(config.API.reportTemplate + `/docx`, data, {
2026-02-09 16:34:20 +07:00
headers: {
"content-Type": "application/json",
accept:
type === "docx"
? "application/vnd.openxmlformats-officedocument.wordprocessingml.document"
: "application/pdf",
},
responseType: "arraybuffer",
})
.then((res) => {
const data = res.data;
if (data) {
// สร้าง Blob จาก array buffer
const blob = new Blob([data], {
type: "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
});
// สร้าง URL สำหรับไฟล์ Blob
const url = URL.createObjectURL(blob);
2026-02-09 16:34:20 +07:00
// 1. ตัดนามสกุลเดิมที่ติดมากับ fileName ออก (ถ้ามี)
const baseName = fileName.replace(/\.[^/.]+$/, "");
// 2. กำหนดนามสกุลใหม่ตามเงื่อนไข
const extension = type === "docx" ? "docx" : "pdf";
// สร้างลิงก์เพื่อดาวน์โหลดไฟล์
const link = document.createElement("a");
link.href = url;
2026-02-09 16:34:20 +07:00
link.download = `${baseName}.${extension}`;
// link.download = `${fileName}.${type === "docx" ? "docx" : "pdf"}`; // กำหนดชื่อไฟล์ที่จะดาวน์โหลด
document.body.appendChild(link);
link.click();
// ลบ URL ที่สร้างขึ้นหลังจากใช้งาน
URL.revokeObjectURL(url);
}
})
.catch((err) => {
2025-06-06 10:38:41 +07:00
console.log(err);
})
.finally(() => {
hideLoader();
});
}
export default genReport;