url 2 pdf support, update test run, reduse imge size,

This commit is contained in:
oom 2025-02-25 19:50:21 +07:00
parent e921875bde
commit f6b68e4379
32 changed files with 3851 additions and 1108 deletions

View file

@ -1,28 +1,29 @@
import express from "express"
export const docxTemplateRoute = express.Router()
import { mimeToExtension, templateData } from "./report-template"
import { mimeToExtension, templateOption } from "./report-template"
import fs from "fs"
import { createReport } from "docx-templates"
const qrcode = require("yaqrcode")
const axios = require("axios")
import qrcode from "yaqrcode"
import axios from "axios"
// แก้ package.json ของ LibreOfficeFileConverter
// https://github.com/microsoft/TypeScript/issues/52363#issuecomment-1659179354
import { LibreOfficeFileConverter } from "libreoffice-file-converter"
const TEMPLATE_FOLDER_NAME = "templates/docx"
/**
* docxTemplate Uses docx-template to convert input data and template to output buffer.
* You have to handle exception throw by function
* template keep in folder templates
* @param {String} base base path of caller relate to template-docx foler (no trail slash)
* @param {templateData} tdata Template Information in JSON format
* @param {Buffer|String} t template in buffer format or path to file
* @param {templateOption} tdata Template Information in JSON format
* @param {String} outputMediaType output extension
* @return {Promise<Uint8Array>} output buffer after apply template.
*/
export async function docxTemplateX(template: Buffer, tdata: templateData, outputMediaType: string = "docx"): Promise<Uint8Array> {
export async function docxTemplateX(t: Buffer|String, tdata: templateOption, outputMediaType: string = "docx"): Promise<Uint8Array> {
try {
// let template = await fs.promises.readFile(`${base}/${TEMPLATE_FOLDER_NAME}/${tdata.template}.docx`)
const template = Buffer.isBuffer(t)?t: await fs.promises.readFile(String(t))
const buffer = await createReport({
template,
data: tdata.data,
@ -36,7 +37,6 @@ export async function docxTemplateX(template: Buffer, tdata: templateData, outpu
const response = await axios.get(imageUrl, { responseType: "arraybuffer" })
const imageData = Buffer.from(response.data).toString("base64") // Convert image to base64
const ext = ".png" // Assuming PNG format; adjust based on actual image type
return {
width,
height,
@ -48,12 +48,18 @@ export async function docxTemplateX(template: Buffer, tdata: templateData, outpu
},
})
if (outputMediaType === "docx") return buffer
const libreOfficeFileConverter = new LibreOfficeFileConverter({
childProcessOptions: {
timeout: 60 * 1000,
},
})
const lbuffer = await libreOfficeFileConverter.convertBuffer(Buffer.from(buffer), outputMediaType)
const lbuffer = await libreOfficeFileConverter.convert({
buffer:Buffer.from(buffer),
format: outputMediaType,
input: "buffer",
output: "buffer"
})
return lbuffer
} catch (e) {
throw e
@ -111,7 +117,7 @@ docxTemplateRoute.get("/", async function (req, res) {
* content:
* application/json:
* schema:
* $ref: '#/components/schemas/templateData'
* $ref: '#/components/schemas/templateOption'
* example:
* template: hello
* reportName: docx-report
@ -147,26 +153,28 @@ docxTemplateRoute.get("/", async function (req, res) {
docxTemplateRoute.post("/", async function (req, res) {
try {
if (!req.headers["content-type"] || !req.headers["accept"]) throw new Error("Require header content-type, accept")
let inputType = mimeToExtension(req.headers["content-type"])
let inputType = mimeToExtension(req.headers["content-type"]) // application/json
let outputMediaType = mimeToExtension(req.headers["accept"])
let template = null
// Save the converted file to disk
if (req.query["folder"]) {
template = await fs.promises.readFile(`./${TEMPLATE_FOLDER_NAME}/${req.query["folder"]}/${req.body.template}.docx`)
} else {
template = await fs.promises.readFile(`./${TEMPLATE_FOLDER_NAME}/${req.body.template}.docx`)
}
let buffer = await docxTemplateX(template, req.body, outputMediaType)
const include_folder= req.query["folder"]?"/"+req.query["folder"]:''
console.log(req.body)
let buffer = await docxTemplateX(`./${TEMPLATE_FOLDER_NAME}${include_folder}/${req.body.template}.docx`, req.body, outputMediaType)
res.statusCode = 201
res.setHeader("Content-Type", req.headers["accept"])
res.setHeader("Content-Disposition", `attachment;filename=${req.body.reportName}.${outputMediaType}`)
res.setHeader("Content-Length", buffer.length)
res.end(buffer)
} catch (ex) {
res.statusCode = 500
res.statusMessage = "Internal Server Error during get docx template list"
res.end(res.statusMessage)
console.error("Error during apply template: ", ex)
if(ex instanceof SyntaxError){
res.statusCode = 400
res.statusMessage = ex.message
res.end(res.statusMessage)
console.error("report-template/docx: ", ex)
}else{
res.statusCode = 500
res.statusMessage = "Internal Server Error during POST report-template/docx"
res.end(res.statusMessage)
console.error("report-template/docx: ", ex)
}
}
})
@ -202,7 +210,7 @@ docxTemplateRoute.post("/", async function (req, res) {
* 201:
* description: file was converted.
* content:
* application/octet-stream:
* application/vnd.openxmlformats-officedocument.wordprocessingml.document:
* schema:
* type: string
* format: binary
@ -210,6 +218,18 @@ docxTemplateRoute.post("/", async function (req, res) {
* schema:
* type: string
* format: binary
* application/pdf:
* schema:
* type: string
* format: binary
* image/png:
* schema:
* type: string
* format: binary
* image/jpeg:
* schema:
* type: string
* format: binary
* 400:
* description: Invalid format
* 500:
@ -269,7 +289,7 @@ docxTemplateRoute.post("/upload", async function (req, res) {
* content:
* application/json:
* schema:
* $ref: '#/components/schemas/templateData'
* $ref: '#/components/schemas/templateOption'
* example:
* template: docx-report
* responses: