add prettier
This commit is contained in:
parent
c33e0653af
commit
f7178d212a
5 changed files with 339 additions and 267 deletions
|
|
@ -11,7 +11,6 @@ import axios from "axios"
|
|||
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
|
||||
|
|
@ -21,49 +20,68 @@ const TEMPLATE_FOLDER_NAME = "templates/docx"
|
|||
* @param {String} outputMediaType output extension
|
||||
* @return {Promise<Uint8Array>} output buffer after apply template.
|
||||
*/
|
||||
export async function docxTemplateX(t: Buffer|String, tdata: templateOption, outputMediaType: string = "docx"): Promise<Uint8Array> {
|
||||
try {
|
||||
const template = Buffer.isBuffer(t)?t: await fs.promises.readFile(String(t))
|
||||
const buffer = await createReport({
|
||||
template,
|
||||
data: tdata.data,
|
||||
additionalJsContext: {
|
||||
qrCode: (contents: string, caption: string, size: number, width: number, height: number) => {
|
||||
const dataUrl = qrcode(contents, { size: size })
|
||||
const data = dataUrl.slice("data:image/gif;base64,".length)
|
||||
return { width, height, data, extension: ".gif", caption }
|
||||
},
|
||||
addImageByUrl: async (imageUrl: string, width: number, height: number, caption: string) => {
|
||||
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,
|
||||
data: imageData,
|
||||
extension: ext,
|
||||
caption,
|
||||
}
|
||||
},
|
||||
},
|
||||
})
|
||||
if (outputMediaType === "docx") return buffer
|
||||
export async function docxTemplateX(
|
||||
t: Buffer | String,
|
||||
tdata: templateOption,
|
||||
outputMediaType: string = "docx"
|
||||
): Promise<Uint8Array> {
|
||||
try {
|
||||
const template = Buffer.isBuffer(t)
|
||||
? t
|
||||
: await fs.promises.readFile(String(t))
|
||||
const buffer = await createReport({
|
||||
template,
|
||||
data: tdata.data,
|
||||
additionalJsContext: {
|
||||
qrCode: (
|
||||
contents: string,
|
||||
caption: string,
|
||||
size: number,
|
||||
width: number,
|
||||
height: number
|
||||
) => {
|
||||
const dataUrl = qrcode(contents, { size: size })
|
||||
const data = dataUrl.slice("data:image/gif;base64,".length)
|
||||
return { width, height, data, extension: ".gif", caption }
|
||||
},
|
||||
addImageByUrl: async (
|
||||
imageUrl: string,
|
||||
width: number,
|
||||
height: number,
|
||||
caption: string
|
||||
) => {
|
||||
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,
|
||||
data: imageData,
|
||||
extension: ext,
|
||||
caption,
|
||||
}
|
||||
},
|
||||
},
|
||||
})
|
||||
if (outputMediaType === "docx") return buffer
|
||||
|
||||
const libreOfficeFileConverter = new LibreOfficeFileConverter({
|
||||
childProcessOptions: {
|
||||
timeout: 60 * 1000,
|
||||
},
|
||||
})
|
||||
const lbuffer = await libreOfficeFileConverter.convert({
|
||||
buffer:Buffer.from(buffer),
|
||||
format: outputMediaType,
|
||||
input: "buffer",
|
||||
output: "buffer"
|
||||
})
|
||||
return lbuffer
|
||||
} catch (e) {
|
||||
throw e
|
||||
}
|
||||
const libreOfficeFileConverter = new LibreOfficeFileConverter({
|
||||
childProcessOptions: {
|
||||
timeout: 60 * 1000,
|
||||
},
|
||||
})
|
||||
const lbuffer = await libreOfficeFileConverter.convert({
|
||||
buffer: Buffer.from(buffer),
|
||||
format: outputMediaType,
|
||||
input: "buffer",
|
||||
output: "buffer",
|
||||
})
|
||||
return lbuffer
|
||||
} catch (e) {
|
||||
throw e
|
||||
}
|
||||
}
|
||||
|
||||
/** javascript-obfuscator:disable
|
||||
|
|
@ -86,16 +104,16 @@ export async function docxTemplateX(t: Buffer|String, tdata: templateOption, out
|
|||
* description: Server error
|
||||
*/
|
||||
docxTemplateRoute.get("/", async function (req, res) {
|
||||
try {
|
||||
const fileList = await fs.promises.readdir(`./${TEMPLATE_FOLDER_NAME}`)
|
||||
const templateList = fileList.map(f => f.split(".docx")[0])
|
||||
res.send(templateList)
|
||||
} catch (ex) {
|
||||
res.statusCode = 500
|
||||
res.statusMessage = "Internal Server Error"
|
||||
res.end(res.statusMessage)
|
||||
console.error("Error during get template list: ", ex)
|
||||
}
|
||||
try {
|
||||
const fileList = await fs.promises.readdir(`./${TEMPLATE_FOLDER_NAME}`)
|
||||
const templateList = fileList.map((f) => f.split(".docx")[0])
|
||||
res.send(templateList)
|
||||
} catch (ex) {
|
||||
res.statusCode = 500
|
||||
res.statusMessage = "Internal Server Error"
|
||||
res.end(res.statusMessage)
|
||||
console.error("Error during get template list: ", ex)
|
||||
}
|
||||
})
|
||||
|
||||
/** javascript-obfuscator:disable
|
||||
|
|
@ -151,31 +169,40 @@ 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"]) // application/json
|
||||
let outputMediaType = mimeToExtension(req.headers["accept"])
|
||||
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) {
|
||||
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)
|
||||
}
|
||||
}
|
||||
try {
|
||||
if (!req.headers["content-type"] || !req.headers["accept"])
|
||||
throw new Error("Require header content-type, accept")
|
||||
let inputType = mimeToExtension(req.headers["content-type"]) // application/json
|
||||
let outputMediaType = mimeToExtension(req.headers["accept"])
|
||||
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) {
|
||||
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)
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
/** javascript-obfuscator:disable
|
||||
|
|
@ -237,37 +264,51 @@ docxTemplateRoute.post("/", async function (req, res) {
|
|||
*
|
||||
*/
|
||||
docxTemplateRoute.post("/upload", async function (req, res) {
|
||||
try {
|
||||
if (!req.headers["content-type"] || !req.headers["accept"] || !req.query["report_name"] || req.headers["content-type"] !== "application/octet-stream") {
|
||||
res.statusCode = 400
|
||||
res.statusMessage = "Require header: content-type(application/octet-stream) accept"
|
||||
res.end(res.statusMessage)
|
||||
return
|
||||
}
|
||||
// Determine the output media type and report name from headers
|
||||
let outputMediaType = mimeToExtension(req.headers["accept"])
|
||||
let reportName = req.query["report_name"]
|
||||
try {
|
||||
if (
|
||||
!req.headers["content-type"] ||
|
||||
!req.headers["accept"] ||
|
||||
!req.query["report_name"] ||
|
||||
req.headers["content-type"] !== "application/octet-stream"
|
||||
) {
|
||||
res.statusCode = 400
|
||||
res.statusMessage =
|
||||
"Require header: content-type(application/octet-stream) accept"
|
||||
res.end(res.statusMessage)
|
||||
return
|
||||
}
|
||||
// Determine the output media type and report name from headers
|
||||
let outputMediaType = mimeToExtension(req.headers["accept"])
|
||||
let reportName = req.query["report_name"]
|
||||
|
||||
// Save the converted file to disk
|
||||
if (req.query["folder"]) {
|
||||
// Ensure the template folder exists
|
||||
await fs.promises.mkdir(`TEMPLATE_FOLDER_NAME/${req.query["folder"]}`, { recursive: true })
|
||||
await fs.promises.writeFile(`./${TEMPLATE_FOLDER_NAME}/${req.query["folder"]}/${reportName}.docx`, req.body)
|
||||
} else {
|
||||
// Ensure the template folder exists
|
||||
await fs.promises.mkdir(TEMPLATE_FOLDER_NAME, { recursive: true })
|
||||
await fs.promises.writeFile(`./${TEMPLATE_FOLDER_NAME}/${reportName}.docx`, req.body)
|
||||
}
|
||||
// Save the converted file to disk
|
||||
if (req.query["folder"]) {
|
||||
// Ensure the template folder exists
|
||||
await fs.promises.mkdir(`TEMPLATE_FOLDER_NAME/${req.query["folder"]}`, {
|
||||
recursive: true,
|
||||
})
|
||||
await fs.promises.writeFile(
|
||||
`./${TEMPLATE_FOLDER_NAME}/${req.query["folder"]}/${reportName}.docx`,
|
||||
req.body
|
||||
)
|
||||
} else {
|
||||
// Ensure the template folder exists
|
||||
await fs.promises.mkdir(TEMPLATE_FOLDER_NAME, { recursive: true })
|
||||
await fs.promises.writeFile(
|
||||
`./${TEMPLATE_FOLDER_NAME}/${reportName}.docx`,
|
||||
req.body
|
||||
)
|
||||
}
|
||||
|
||||
// Send a response to the client
|
||||
res.statusCode = 201
|
||||
res.json({ message: "File converted and saved successfully" })
|
||||
} catch (ex) {
|
||||
res.statusCode = 500
|
||||
res.statusMessage = "Internal Server Error"
|
||||
res.end(res.statusMessage)
|
||||
console.error(`Error during convert with soffice:`, ex)
|
||||
}
|
||||
// Send a response to the client
|
||||
res.statusCode = 201
|
||||
res.json({ message: "File converted and saved successfully" })
|
||||
} catch (ex) {
|
||||
res.statusCode = 500
|
||||
res.statusMessage = "Internal Server Error"
|
||||
res.end(res.statusMessage)
|
||||
console.error(`Error during convert with soffice:`, ex)
|
||||
}
|
||||
})
|
||||
|
||||
/** javascript-obfuscator:disable
|
||||
|
|
@ -309,25 +350,37 @@ docxTemplateRoute.post("/upload", async function (req, res) {
|
|||
*
|
||||
*/
|
||||
docxTemplateRoute.post("/download", async function (req, res) {
|
||||
try {
|
||||
if (!req.headers["content-type"] || !req.headers["accept"] || !req.body.template) throw new Error("Require header content-type, accept")
|
||||
let inputType = mimeToExtension(req.headers["content-type"])
|
||||
let outputMediaType = mimeToExtension(req.headers["accept"])
|
||||
let buffer = null
|
||||
if (req.query["folder"]) {
|
||||
buffer = await fs.promises.readFile(`./${TEMPLATE_FOLDER_NAME}/${req.query["folder"]}/${req.body.template}.docx`)
|
||||
} else {
|
||||
buffer = await fs.promises.readFile(`./${TEMPLATE_FOLDER_NAME}/${req.body.template}.docx`)
|
||||
}
|
||||
res.statusCode = 201
|
||||
res.setHeader("Content-Type", req.headers["accept"])
|
||||
res.setHeader("Content-Disposition", `attachment;filename=${req.body.template}.${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)
|
||||
}
|
||||
try {
|
||||
if (
|
||||
!req.headers["content-type"] ||
|
||||
!req.headers["accept"] ||
|
||||
!req.body.template
|
||||
)
|
||||
throw new Error("Require header content-type, accept")
|
||||
let inputType = mimeToExtension(req.headers["content-type"])
|
||||
let outputMediaType = mimeToExtension(req.headers["accept"])
|
||||
let buffer = null
|
||||
if (req.query["folder"]) {
|
||||
buffer = await fs.promises.readFile(
|
||||
`./${TEMPLATE_FOLDER_NAME}/${req.query["folder"]}/${req.body.template}.docx`
|
||||
)
|
||||
} else {
|
||||
buffer = await fs.promises.readFile(
|
||||
`./${TEMPLATE_FOLDER_NAME}/${req.body.template}.docx`
|
||||
)
|
||||
}
|
||||
res.statusCode = 201
|
||||
res.setHeader("Content-Type", req.headers["accept"])
|
||||
res.setHeader(
|
||||
"Content-Disposition",
|
||||
`attachment;filename=${req.body.template}.${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)
|
||||
}
|
||||
})
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue