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())
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
import { describe, it, expect, vi } from 'vitest'
|
||||
import { rasterizeSvg } from '@/pdf/render/svgToPng'
|
||||
|
||||
vi.mock('canvg', () => ({
|
||||
Canvg: { from: vi.fn(async () => ({ render: vi.fn(async () => {}) })) },
|
||||
}))
|
||||
|
||||
describe('rasterizeSvg', () => {
|
||||
it('returns a Uint8Array', async () => {
|
||||
const canvas = document.createElement('canvas')
|
||||
canvas.getContext = (() => ({})) as unknown as HTMLCanvasElement['getContext']
|
||||
canvas.toBlob = ((cb: BlobCallback) => {
|
||||
cb(new Blob([new Uint8Array([1, 2, 3])], { type: 'image/png' }))
|
||||
}) as HTMLCanvasElement['toBlob']
|
||||
vi.spyOn(document, 'createElement').mockImplementationOnce(() => canvas)
|
||||
|
||||
const out = await rasterizeSvg('<svg xmlns="http://www.w3.org/2000/svg" width="10" height="10" viewBox="0 0 10 10"/>', 2)
|
||||
expect(out).toBeInstanceOf(Uint8Array)
|
||||
expect(out.length).toBeGreaterThan(0)
|
||||
})
|
||||
})
|
||||
Reference in new issue
Block a user