From 4b85b263858602740f80f666b812dbd8168fe85f Mon Sep 17 00:00:00 2001 From: Mike Mellor Date: Fri, 20 Jan 2023 10:04:16 +0000 Subject: [PATCH] feat: new puppeteer implementation of fit code --- index.js | 47 ++++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 46 insertions(+), 1 deletion(-) diff --git a/index.js b/index.js index 5ecd929..6020d81 100644 --- a/index.js +++ b/index.js @@ -1 +1,46 @@ -console.log("ASDF"); \ No newline at end of file +import fs from "fs-extra"; +import puppeteer from "puppeteer-core"; +import path from "path"; + +export async function fit(inputs, outputs){ + let dest = outputs; + let input = inputs; + + const browser = await puppeteer.launch({ + executablePath: "/Applications/Google\ Chrome.app/Contents/MacOS/Google\ Chrome", + args: ['--headless', '--no-sandbox', '--disable-gpu', '--disable-dev-shm-usage'], + }); + + try{ + const page = await browser.newPage(); + + let svg = fs.readFileSync(input, {encoding: 'utf8'}); + + await page.setContent(svg); + + const result = await (await page.waitForSelector("svg")).evaluate((el) => { + let { x, y, width, height } = el.getBBox(); + + el.setAttribute('viewBox', `${x} ${y} ${width} ${height}`); + + if(el.hasAttribute('width')){ + el.setAttribute('width', width); + } + + if(el.hasAttribute('height')){ + el.setAttribute('height', height); + } + + return el.outerHTML; + }); + + fs.mkdirpSync(dest); + fs.writeFileSync(`${dest}/${path.basename(input)}`, result); + } catch(e){console.log(e);} + + await browser.close(); +} + +export default { + fit +}; \ No newline at end of file