hrms-mgt/src/plugins/genreport.ts

61 lines
1.8 KiB
TypeScript
Raw Normal View History

2023-12-14 15:21:35 +07:00
import axios from "axios";
import { useQuasar } from "quasar";
import { useCounterMixin } from "@/stores/mixin";
const $q = useQuasar();
const mixin = useCounterMixin();
const { showLoader, hideLoader, messageError } = mixin;
const apiGenReport =
"https://report-server.frappet.synology.me/api/v1/report-template/docx";
2023-12-20 16:30:38 +07:00
async function genReport(data: any, fileName: string, type: string = "docx") {
2023-12-14 15:21:35 +07:00
showLoader();
await axios
.post(apiGenReport, data, {
2023-12-20 16:30:38 +07:00
headers:
type == "docx"
? {
accept:
"application/vnd.openxmlformats-officedocument.wordprocessingml.document",
"content-Type": "application/json",
}
: {
accept: "application/pdf",
"content-Type": "application/json",
},
2023-12-14 15:21:35 +07:00
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);
// สร้างลิงก์เพื่อดาวน์โหลดไฟล์
const link = document.createElement("a");
link.href = url;
link.download = `${fileName}.docx`; // กำหนดชื่อไฟล์ที่จะดาวน์โหลด
document.body.appendChild(link);
link.click();
// ลบ URL ที่สร้างขึ้นหลังจากใช้งาน
URL.revokeObjectURL(url);
}
})
.catch((err) => {
messageError($q, err);
})
.finally(() => {
hideLoader();
});
}
export default genReport;