import xml2js from "xml2js" ; import { SourceImage } from "./helpers.js" ; import { logContext , Logger } from "./logger.js" ; export class SvgTool { #log : Logger ; constructor ( logger ) { this . #log = logContext ( logger , "svgtool" ) ; } async ensureSize ( svgSource , width , height ) { let svgWidth = svgSource . metadata . width ; let svgHeight = svgSource . metadata . height ; if ( svgWidth >= width && svgHeight >= height ) { return svgSource . data ; } else if ( width > height ) { svgHeight = Math . round ( svgHeight * ( width / svgWidth ) ) ; svgWidth = width ; } else { svgWidth = Math . round ( svgWidth * ( height / svgHeight ) ) ; svgHeight = height ; } this . #log ( "ensureSize" , `Resizing SVG to ${ svgWidth }x${ svgHeight }` ) ; return await this . resize ( svgSource . data , svgWidth , svgHeight ) ; } async resize ( svgFile , width , height ) { const xmlDoc = await xml2js . parseStringPromise ( svgFile ) ; xmlDoc . svg . $ . width = width ; xmlDoc . svg . $ . height = height ; const builder = new xml2js . Builder ( ) ; const modifiedSvg = builder . buildObject ( xmlDoc ) ; return Buffer . from ( modifiedSvg ) ; } }