Skip to content

Commit 36bb1b5

Browse files
Add support for viewbox transformations for intrinsic raster image dimensions (#314)
* add computeViewBoxTransform for img * update references to match viewbox transformations for raster images --------- Co-authored-by: Lukas Hollaender <[email protected]>
1 parent c1f4082 commit 36bb1b5

File tree

8 files changed

+34
-4
lines changed

8 files changed

+34
-4
lines changed

src/nodes/image.ts

Lines changed: 29 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@ import { GraphicsNode } from './graphicsnode'
88
import { Rect } from '../utils/geometry'
99
import { Matrix } from 'jspdf'
1010
import { Viewport } from '../context/viewport'
11+
import { computeViewBoxTransform } from '../utils/transform'
1112

1213
// groups: 1: mime-type (+ charset), 2: mime-type (w/o charset), 3: charset, 4: base64?, 5: body
1314
export const dataUriRegex = /^\s*data:(([^/,;]+\/[^/,;]+)(?:;([^,;=]+=[^,;=]+))?)?(?:;(base64))?,((?:.|\s)*)$/i
@@ -76,13 +77,26 @@ export class ImageNode extends GraphicsNode {
7677
} else {
7778
const dataUri = `data:image/${format};base64,${btoa(data)}`
7879
try {
79-
context.pdf.addImage(
80-
dataUri,
81-
'', // will be ignored anyways if imageUrl is a data url
80+
const [imgWidth, imgHeight] = await ImageNode.getImageDimensions(dataUri)
81+
const viewBox = [0, 0, imgWidth, imgHeight]
82+
const transform = computeViewBoxTransform(
83+
this.element,
84+
viewBox,
8285
x,
8386
y,
8487
width,
85-
height
88+
height,
89+
context
90+
)
91+
context.pdf.setCurrentTransformationMatrix(transform)
92+
93+
context.pdf.addImage(
94+
dataUri,
95+
'', // will be ignored anyways if imageUrl is a data url
96+
0,
97+
0,
98+
imgWidth,
99+
imgHeight
86100
)
87101
} catch (e) {
88102
typeof console === 'object' &&
@@ -171,4 +185,15 @@ export class ImageNode extends GraphicsNode {
171185
return `image/${format}`
172186
}
173187
}
188+
189+
static getImageDimensions(src: string): Promise<[number, number]> {
190+
return new Promise((resolve, reject) => {
191+
const img = new Image()
192+
img.onload = () => {
193+
resolve([img.width, img.height])
194+
}
195+
img.onerror = reject
196+
img.src = src
197+
})
198+
}
174199
}

test/common/tests.js

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,7 @@ window.tests = [
3131
'gradient-units',
3232
'gradients-and-patterns-mixed',
3333
'hidden-clippath',
34+
'image-aspect-ratio',
3435
'image-data-urls-base64-spaces',
3536
'image-svg-urls',
3637
'line-default-coordinates',
105 Bytes
Binary file not shown.
5.67 KB
Binary file not shown.
Lines changed: 4 additions & 0 deletions
Loading
19 Bytes
Binary file not shown.
35 Bytes
Binary file not shown.
48 Bytes
Binary file not shown.

0 commit comments

Comments
 (0)