feat(pdf): rasterize SVG via canvg → PNG bytes
This commit is contained in:
1 parent
3ea8f522c0
commit
55d9c32076
2 files changed
+45
-10
No files matched your search
+24
-10
@@ -1,11 +1,25 @@
|
||||
/**
|
||||
* Rasterizes an SVG string to a PNG Uint8Array using canvg.
|
||||
* Scale factor 2 = A4 print quality.
|
||||
* Returns raw PNG bytes suitable for pdf-lib embedPng().
|
||||
*/
|
||||
export async function rasterizeSvg(
|
||||
_svgString: string,
|
||||
_scale: number,
|
||||
): Promise<Uint8Array> {
|
||||
throw new Error('not implemented')
|
||||
import { Canvg } from 'canvg'
|
||||
|
||||
const TARGET_WIDTH = 1200
|
||||
|
||||
export async function rasterizeSvg(svgString: string, scale: number): Promise<Uint8Array> {
|
||||
const tmp = new DOMParser().parseFromString(svgString, 'image/svg+xml')
|
||||
const root = tmp.documentElement
|
||||
const vb = (root.getAttribute('viewBox') ?? '0 0 1000 600').split(/\s+/).map(Number)
|
||||
const widthPx = Math.round(TARGET_WIDTH * Math.max(1, scale) * 0.5)
|
||||
const heightPx = Math.round((vb[3] / vb[2]) * widthPx)
|
||||
|
||||
const canvas = document.createElement('canvas')
|
||||
canvas.width = widthPx
|
||||
canvas.height = heightPx
|
||||
const ctx = canvas.getContext('2d')
|
||||
if (!ctx) throw new Error('Canvas 2D context unavailable')
|
||||
|
||||
const canv = await Canvg.from(ctx, svgString)
|
||||
await canv.render()
|
||||
|
||||
const blob: Blob = await new Promise((resolve, reject) => {
|
||||
canvas.toBlob((b) => (b ? resolve(b) : reject(new Error('toBlob returned null'))), 'image/png')
|
||||
})
|
||||
return new Uint8Array(await blob.arrayBuffer())
|
||||
}
|
||||
Reference in new issue
Block a user