hrms-report-template/test-run/url_pup2pdf.ts
2025-02-28 11:43:17 +07:00

86 lines
2.6 KiB
TypeScript

// ใช้เพื่อทดสอบ puppeteer
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 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)
await page.setViewport({
width: width_px,
height: 800,
deviceScaleFactor: 2,
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
if (scrollableSection) {
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
}
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
})
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)
}
console.log("set viewport ")
await page.setViewport({
width: width_px,
height: totalHeight,
deviceScaleFactor: 2,
isMobile: false,
})
await page.screenshot({
path: "url_pup.png",
fullPage: true,
type: "png", // | 'jpeg' | 'webp'
})
await page.pdf({
path: ".outputurl_prop.pdf",
// format:"A4",
width: width_px,
height: totalHeight,
printBackground: true,
scale: 1,
displayHeaderFooter: false,
margin: { top: 0, right: 0, bottom: 0, left: 0 },
})
await browser.close()
})()