format with prettier

This commit is contained in:
oom 2025-02-28 11:43:17 +07:00
parent f7178d212a
commit 3c35c1e552
10 changed files with 540 additions and 466 deletions

View file

@ -1,22 +1,25 @@
// npx ts-node docx-template.ts
import * as readline from 'node:readline/promises'; // This uses the promise-based APIs
import { stdin as input, stdout as output } from 'node:process';
import { docxTemplateX} from '../libs/docx-templates-lib';
import {templateOption} from '../libs/report-template'
import fs from 'fs';
(async ()=>{
const rl = readline.createInterface({ input, output });
const e = await rl.question('Output extension(docx,pdf,odt,png,jpeg): ');
const ext =e?e:"docx"
const dpath = await rl.question('JSON data path(./docx.json): ');
const datapath = dpath?dpath:"./docx.json"
const data_raw = fs.readFileSync(datapath);
const tdata:templateOption = JSON.parse(data_raw.toString());
const bpath = await rl.question('templates path(../templates/docx): ');
const basepath = bpath?bpath:"../templates/docx"
//const template = await fs.promises.readFile(`${basepath}/${tdata.template}.docx`)
let buffer = await docxTemplateX(`${basepath}/${tdata.template}.docx`, tdata,ext)
fs.writeFileSync(".output/"+tdata.reportName+"."+ext, buffer);
rl.close();
import * as readline from "node:readline/promises" // This uses the promise-based APIs
import { stdin as input, stdout as output } from "node:process"
import { docxTemplateX } from "../libs/docx-templates-lib"
import { templateOption } from "../libs/report-template"
import fs from "fs"
(async () => {
const rl = readline.createInterface({ input, output })
const e = await rl.question("Output extension(docx,pdf,odt,png,jpeg): ")
const ext = e ? e : "docx"
const dpath = await rl.question("JSON data path(./docx.json): ")
const datapath = dpath ? dpath : "./docx.json"
const data_raw = fs.readFileSync(datapath)
const tdata: templateOption = JSON.parse(data_raw.toString())
const bpath = await rl.question("templates path(../templates/docx): ")
const basepath = bpath ? bpath : "../templates/docx"
//const template = await fs.promises.readFile(`${basepath}/${tdata.template}.docx`)
let buffer = await docxTemplateX(
`${basepath}/${tdata.template}.docx`,
tdata,
ext
)
fs.writeFileSync(".output/" + tdata.reportName + "." + ext, buffer)
rl.close()
})()

View file

@ -1,65 +1,65 @@
'use strict';
"use strict"
const puppeteer = require('puppeteer');
const puppeteer = require("puppeteer")
//const fetch = require('node-fetch');
const fs = require('fs');
const fs = require("fs")
console.log("Script grafana_pdf.js started...");
console.log("Script grafana_pdf.js started...")
/*
const url = process.argv[2];
const auth_string = process.argv[3];
let outfile = process.argv[4];
*/
const url = 'https://bma-dashboard.frappet.synology.me/d/5EwyjelSk/1408ef66-0081-5b3f-aa00-5e70aa9bdbf1?orgId=1&kiosk=true'
const auth_string = 'admin:xxx';
let outfile = "./url_gf.pdf";
const url =
"https://bma-dashboard.frappet.synology.me/d/5EwyjelSk/1408ef66-0081-5b3f-aa00-5e70aa9bdbf1?orgId=1&kiosk=true"
const auth_string = "admin:xxx"
let outfile = "./url_gf.pdf"
const width_px = parseInt(process.env.PDF_WIDTH_PX, 10) || 1200;
console.log("PDF width set to:", width_px);
const width_px = parseInt(process.env.PDF_WIDTH_PX, 10) || 1200
console.log("PDF width set to:", width_px)
const auth_header = 'Basic ' + Buffer.from(auth_string).toString('base64');
const auth_header = "Basic " + Buffer.from(auth_string).toString("base64")
(async () => {
try {
console.log("URL provided:", url);
console.log("Checking URL accessibility...");
const response = await fetch(url, {
method: 'GET',
headers: {'Authorization': auth_header}
});
;(async () => {
try {
console.log("URL provided:", url)
console.log("Checking URL accessibility...")
const response = await fetch(url, {
method: "GET",
headers: { Authorization: auth_header },
})
if (!response.ok) {
throw new Error(`Unable to access URL. HTTP status: ${response.status}`);
}
if (!response.ok) {
throw new Error(`Unable to access URL. HTTP status: ${response.status}`)
}
const contentType = response.headers.get('content-type');
if (!contentType || !contentType.includes('text/html')) {
throw new Error("The URL provided is not a valid Grafana instance.");
}
const contentType = response.headers.get("content-type")
if (!contentType || !contentType.includes("text/html")) {
throw new Error("The URL provided is not a valid Grafana instance.")
}
let finalUrl = url;
if(process.env.FORCE_KIOSK_MODE === 'true') {
console.log("Checking if kiosk mode is enabled.")
if (!finalUrl.includes('&kiosk')) {
console.log("Kiosk mode not enabled. Enabling it.")
finalUrl += '&kiosk=true';
}
console.log("Kiosk mode enabled.")
}
let finalUrl = url
if (process.env.FORCE_KIOSK_MODE === "true") {
console.log("Checking if kiosk mode is enabled.")
if (!finalUrl.includes("&kiosk")) {
console.log("Kiosk mode not enabled. Enabling it.")
finalUrl += "&kiosk=true"
}
console.log("Kiosk mode enabled.")
}
console.log("Starting browser...")
const browser = await puppeteer.launch({
executablePath: process.env.PUPPETEER_EXECUTABLE_PATH,
headless: true,
// args: ['--no-sandbox', '--disable-setuid-sandbox', '--disable-gpu']
})
console.log("Starting browser...");
const browser = await puppeteer.launch({
executablePath: process.env.PUPPETEER_EXECUTABLE_PATH,
headless: true,
// args: ['--no-sandbox', '--disable-setuid-sandbox', '--disable-gpu']
});
const page = await browser.newPage()
console.log("Browser started...")
const page = await browser.newPage();
console.log("Browser started...");
/*
/*
await page.setExtraHTTPHeaders({'Authorization': auth_header});
await page.setDefaultNavigationTimeout(process.env.PUPPETEER_NAVIGATION_TIMEOUT || 120000);
@ -70,10 +70,10 @@ const auth_header = 'Basic ' + Buffer.from(auth_string).toString('base64');
isMobile: false
});
*/
console.log("Navigating to URL...");
await page.goto(finalUrl, {waitUntil: 'networkidle0'});
console.log("Page loaded...");
/*
console.log("Navigating to URL...")
await page.goto(finalUrl, { waitUntil: "networkidle0" })
console.log("Page loaded...")
/*
await page.evaluate(() => {
let infoCorners = document.getElementsByClassName('panel-info-corner');
for (let el of infoCorners) {
@ -85,10 +85,10 @@ const auth_header = 'Basic ' + Buffer.from(auth_string).toString('base64');
}
});
*/
let dashboardName = 'output_grafana';
let date = new Date().toISOString().split('T')[0];
let addRandomStr = false;
/*
let dashboardName = "output_grafana"
let date = new Date().toISOString().split("T")[0]
let addRandomStr = false
/*
if (process.env.EXTRACT_DATE_AND_DASHBOARD_NAME_FROM_HTML_PANEL_ELEMENTS === 'true') {
console.log("Extracting dashboard name and date from the HTML page...");
let scrapedDashboardName = await page.evaluate(() => {
@ -207,61 +207,65 @@ const auth_header = 'Basic ' + Buffer.from(auth_string).toString('base64');
}
*/
const totalHeight = await page.evaluate(() => {
const scrollableSection = document.querySelector('.scrollbar-view');
return scrollableSection ? scrollableSection.firstElementChild.scrollHeight : null;
});
const totalHeight = await page.evaluate(() => {
const scrollableSection = document.querySelector(".scrollbar-view")
return scrollableSection
? scrollableSection.firstElementChild.scrollHeight
: null
})
if (!totalHeight) {
throw new Error("Unable to determine the page height. The selector '.scrollbar-view' might be incorrect or missing.");
} else {
console.log("Page height adjusted to:", totalHeight);
}
let x = await page.evaluate(async () => {
const scrollableSection = document.querySelector('.scrollbar-view');
if (scrollableSection) {
const childElement = scrollableSection.firstElementChild;
let scrollPosition = 0;
let viewportHeight = window.innerHeight;
while (scrollPosition < childElement.scrollHeight) {
scrollableSection.scrollBy(0, viewportHeight);
await new Promise(resolve => setTimeout(resolve, 500));
scrollPosition += viewportHeight;
}
return scrollPosition
}
return 0
});
console.log("scrollPosition="+x)
await page.setViewport({
width: width_px,
height: totalHeight,
deviceScaleFactor: 2,
isMobile: false
});
console.log("Generating PDF...");
await page.pdf({
path: outfile,
width: width_px + 'px',
height: totalHeight + 'px',
printBackground: true,
scale: 1,
displayHeaderFooter: false,
margin: {top: 0, right: 0, bottom: 0, left: 0}
});
console.log(`PDF generated: ${outfile}`);
await browser.close();
console.log("Browser closed.");
//process.send({ success: true, path: outfile });
} catch (error) {
console.error("Error during PDF generation:", error.message);
//process.send({ success: false, error: error.message });
process.exit(1);
if (!totalHeight) {
throw new Error(
"Unable to determine the page height. The selector '.scrollbar-view' might be incorrect or missing."
)
} else {
console.log("Page height adjusted to:", totalHeight)
}
})();
let x = await page.evaluate(async () => {
const scrollableSection = document.querySelector(".scrollbar-view")
if (scrollableSection) {
const childElement = scrollableSection.firstElementChild
let scrollPosition = 0
let viewportHeight = window.innerHeight
while (scrollPosition < childElement.scrollHeight) {
scrollableSection.scrollBy(0, viewportHeight)
await new Promise((resolve) => setTimeout(resolve, 500))
scrollPosition += viewportHeight
}
return scrollPosition
}
return 0
})
console.log("scrollPosition=" + x)
await page.setViewport({
width: width_px,
height: totalHeight,
deviceScaleFactor: 2,
isMobile: false,
})
console.log("Generating PDF...")
await page.pdf({
path: outfile,
width: width_px + "px",
height: totalHeight + "px",
printBackground: true,
scale: 1,
displayHeaderFooter: false,
margin: { top: 0, right: 0, bottom: 0, left: 0 },
})
console.log(`PDF generated: ${outfile}`)
await browser.close()
console.log("Browser closed.")
//process.send({ success: true, path: outfile });
} catch (error) {
console.error("Error during PDF generation:", error.message)
//process.send({ success: false, error: error.message });
process.exit(1)
}
})()

View file

@ -1,25 +1,26 @@
// npx ts-node html-templates.ts
import * as readline from 'node:readline/promises'; // This uses the promise-based APIs
import { stdin as input, stdout as output } from 'node:process';
import { htmlTemplateX} from '../libs/html-templates-lib';
import {templateOption} from '../libs/report-template'
import fs from 'fs';
(async ()=>{
const rl = readline.createInterface({ input, output });
const e = await rl.question('Output extension(pdf,png,jpeg): ');
const ext =e?e:"pdf"
const dpath = await rl.question('JSON data path(./html.json): ');
const datapath = dpath?dpath:"./html.json"
const data_raw = fs.readFileSync(datapath);
const tdata:templateOption = JSON.parse(data_raw.toString());
const bpath = await rl.question('templates path(../templates/html): ');
const basepath = bpath?bpath:"../templates/html"
// const template = await fs.promises.readFile(`${basepath}/${tdata.template}.docx`)
let url = "https://bma-dashboard.frappet.synology.me/d/ANtkJay4z/4Lic4Li54LmJ4Lie4Li04LiB4Liy4Lij?orgId=1&kiosk"
//let url = "https://pantip.com"
// let url = "https://google.com"
import * as readline from "node:readline/promises" // This uses the promise-based APIs
import { stdin as input, stdout as output } from "node:process"
import { htmlTemplateX } from "../libs/html-templates-lib"
import { templateOption } from "../libs/report-template"
import fs from "fs"
;(async () => {
const rl = readline.createInterface({ input, output })
const e = await rl.question("Output extension(pdf,png,jpeg): ")
const ext = e ? e : "pdf"
const dpath = await rl.question("JSON data path(./html.json): ")
const datapath = dpath ? dpath : "./html.json"
const data_raw = fs.readFileSync(datapath)
const tdata: templateOption = JSON.parse(data_raw.toString())
const bpath = await rl.question("templates path(../templates/html): ")
const basepath = bpath ? bpath : "../templates/html"
// const template = await fs.promises.readFile(`${basepath}/${tdata.template}.docx`)
let url =
"https://bma-dashboard.frappet.synology.me/d/ANtkJay4z/4Lic4Li54LmJ4Lie4Li04LiB4Liy4Lij?orgId=1&kiosk"
//let url = "https://pantip.com"
// let url = "https://google.com"
let buffer = await htmlTemplateX(url, tdata,ext)
fs.writeFileSync(".output/"+tdata.reportName+"."+ext, buffer);
rl.close();
})()
let buffer = await htmlTemplateX(url, tdata, ext)
fs.writeFileSync(".output/" + tdata.reportName + "." + ext, buffer)
rl.close()
})()

View file

@ -1,57 +1,62 @@
// ใช้เพื่อทดสอบ puppeteer
import puppeteer from 'puppeteer'
(async () => {
import puppeteer from "puppeteer"
;(async () => {
//const targetUrl = "https://bma-dashboard.frappet.synology.me/d/5EwyjelSk/1408ef66-0081-5b3f-aa00-5e70aa9bdbf1?orgId=1&kiosk=true"
//const targetUrl = "https://bma-dashboard.frappet.synology.me/d/OLZwQhPVz/4Liq4Lit4Lia4LmB4LiC4LmI4LiH4LiC4Lix4LiZ?orgId=1&kiosk"
const targetUrl = "https://blognone.com"
const width_px = Number(process.env.PDF_WIDTH_PX) || 1200;
const width_px = Number(process.env.PDF_WIDTH_PX) || 1200
const browser = await puppeteer.launch({
// executablePath: '/usr/bin/chromium',
headless: true,
//args: ['--no-sandbox', '--disable-setuid-sandbox', '--disable-gpu']
});
})
const page = await browser.newPage()
page.setDefaultNavigationTimeout(120000)
const page = await browser.newPage();
page.setDefaultNavigationTimeout(120000);
await page.setViewport({
width: width_px,
height: 800,
deviceScaleFactor: 2,
isMobile: false
});
await page.goto(targetUrl, { waitUntil: 'networkidle0' });
isMobile: false,
})
await page.goto(targetUrl, { waitUntil: "networkidle0" })
//console.log("Page loaded...");
let x = await page.evaluate(async () => {
const scrollableSection =
document.querySelector('.scrollbar-view')?document.querySelector('.scrollbar-view'):document.body
const scrollableSection = document.querySelector(".scrollbar-view")
? document.querySelector(".scrollbar-view")
: document.body
if (scrollableSection) {
const childElement = scrollableSection.firstElementChild;
let scrollPosition = 0;
let viewportHeight = window.innerHeight;
const childElement = scrollableSection.firstElementChild
let scrollPosition = 0
let viewportHeight = window.innerHeight
if (childElement)
while (scrollPosition < childElement.scrollHeight) {
scrollableSection.scrollBy(0, viewportHeight);
await new Promise(resolve => setTimeout(resolve, 500));
scrollPosition += viewportHeight;
scrollableSection.scrollBy(0, viewportHeight)
await new Promise((resolve) => setTimeout(resolve, 500))
scrollPosition += viewportHeight
}
return scrollPosition
}
return 0
});
})
console.log("scrollPosition=" + x)
const totalHeight = await page.evaluate(() => {
const scrollableSection = document.querySelector('.scrollbar-view');//only Grafana ?
return scrollableSection ? scrollableSection.firstElementChild?.scrollHeight : document.body.scrollHeight;
});
const scrollableSection = document.querySelector(".scrollbar-view") //only Grafana ?
return scrollableSection
? scrollableSection.firstElementChild?.scrollHeight
: document.body.scrollHeight
})
if (!totalHeight) {
throw new Error("Unable to determine the page height. The selector '.scrollbar-view' might be incorrect or missing.");
throw new Error(
"Unable to determine the page height. The selector '.scrollbar-view' might be incorrect or missing."
)
} else {
console.log("Page height adjusted to:", totalHeight);
console.log("Page height adjusted to:", totalHeight)
}
console.log("set viewport ")
@ -59,13 +64,13 @@ import puppeteer from 'puppeteer'
width: width_px,
height: totalHeight,
deviceScaleFactor: 2,
isMobile: false
});
isMobile: false,
})
await page.screenshot({
path: 'url_pup.png',
path: "url_pup.png",
fullPage: true,
type: 'png' // | 'jpeg' | 'webp'
type: "png", // | 'jpeg' | 'webp'
})
await page.pdf({
path: ".outputurl_prop.pdf",
@ -75,10 +80,7 @@ import puppeteer from 'puppeteer'
printBackground: true,
scale: 1,
displayHeaderFooter: false,
margin: { top: 0, right: 0, bottom: 0, left: 0 }
});
await browser.close();
})();
margin: { top: 0, right: 0, bottom: 0, left: 0 },
})
await browser.close()
})()

View file

@ -1,22 +1,25 @@
// npx ts-node xlsx-template.ts
import * as readline from 'node:readline/promises'; // This uses the promise-based APIs
import { stdin as input, stdout as output } from 'node:process';
import {xlsxTemplateX} from '../libs/xlsx-template-lib'
import {templateOption} from '../libs/report-template'
import fs from 'fs';
(async ()=>{
const rl = readline.createInterface({ input, output });
const e = await rl.question('Output extension(xlsx,pdf,ods,png,jpeg): ');
const ext =e?e:"xlsx"
const dpath = await rl.question('JSON data path(./xlsx.json): ');
const datapath = dpath?dpath:"./xlsx.json"
const data_raw = fs.readFileSync(datapath);
const tdata:templateOption = JSON.parse(data_raw.toString());
const bpath = await rl.question('template path(../templates/xlsx): ');
const basepath = bpath?bpath:"../templates/xlsx"
// const template = await fs.promises.readFile(`${basepath}/${tdata.template}.xlsx`)
let buffer = await xlsxTemplateX(`${basepath}/${tdata.template}.xlsx`,tdata,ext)
fs.writeFileSync(tdata.reportName+"."+ext, buffer);
rl.close();
import * as readline from "node:readline/promises" // This uses the promise-based APIs
import { stdin as input, stdout as output } from "node:process"
import { xlsxTemplateX } from "../libs/xlsx-template-lib"
import { templateOption } from "../libs/report-template"
import fs from "fs"
;(async () => {
const rl = readline.createInterface({ input, output })
const e = await rl.question("Output extension(xlsx,pdf,ods,png,jpeg): ")
const ext = e ? e : "xlsx"
const dpath = await rl.question("JSON data path(./xlsx.json): ")
const datapath = dpath ? dpath : "./xlsx.json"
const data_raw = fs.readFileSync(datapath)
const tdata: templateOption = JSON.parse(data_raw.toString())
const bpath = await rl.question("template path(../templates/xlsx): ")
const basepath = bpath ? bpath : "../templates/xlsx"
// const template = await fs.promises.readFile(`${basepath}/${tdata.template}.xlsx`)
let buffer = await xlsxTemplateX(
`${basepath}/${tdata.template}.xlsx`,
tdata,
ext
)
fs.writeFileSync(tdata.reportName + "." + ext, buffer)
rl.close()
})()