Spaces:
Running
on
CPU Upgrade
Running
on
CPU Upgrade
File size: 1,730 Bytes
2cae2a9 46fcec6 2cae2a9 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 |
import { promises as fs } from "node:fs"
import os from "node:os"
import path from "node:path"
import { v4 as uuidv4 } from "uuid"
import puppeteer from "puppeteer"
export async function htmlToBase64Png({
outputImagePath,
html,
width = 800,
height = 600,
}: {
outputImagePath?: string
html?: string
width?: number
height: number
}): Promise<{
filePath: string
buffer: Buffer
}> {
// If no output path is provided, create a temporary file for output
if (!outputImagePath) {
const tempDir = await fs.mkdtemp(path.join(os.tmpdir(), uuidv4()))
outputImagePath = path.join(tempDir, `${uuidv4()}.png`)
}
const browser = await puppeteer.launch({
headless: true,
// apparently we need those, see:
// https://unix.stackexchange.com/questions/694734/puppeteer-in-alpine-docker-with-chromium-headless-dosent-seems-to-work
executablePath: '/usr/bin/chromium-browser',
args: [
'--no-sandbox',
'--headless',
'--disable-gpu',
'--disable-dev-shm-usage'
]
})
const page = await browser.newPage()
page.setViewport({
width,
height,
})
try {
await page.setContent(html)
const content = await page.$("body")
const buffer = await content.screenshot({
path: outputImagePath,
omitBackground: true,
captureBeyondViewport: false,
// we must keep PNG here, if we want transparent backgrounds
type: "png",
// we should leave it to binary (the default value) if we save to a file
// encoding: "binary", // "base64",
})
return {
filePath: outputImagePath,
buffer
}
} catch (err) {
throw err
} finally {
await page.close()
await browser.close()
}
}; |