-
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathemf-writer.ts
More file actions
1508 lines (1327 loc) · 55.2 KB
/
emf-writer.ts
File metadata and controls
1508 lines (1327 loc) · 55.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* EMF (Enhanced Metafile) Writer.
* Maps IR nodes to EMF binary records and produces an EMF file as Uint8Array.
*
* EMF is a Windows vector graphics format (GDI-based).
* This writer produces a standalone EMF file with polygons, polylines, text, and images.
*
* Reference: [MS-EMF] Enhanced Metafile Format specification.
*/
import type { Point, Quad, Style, Writer } from "../types.js";
import { normalizeWhitespaceAwareText } from "../shared/text-whitespace.js";
import { cssColorToColorRef } from "./shared/css-color.js";
import { getPointBounds, getQuadBounds, parseClipPathShape, type ClipPathBounds } from "./shared/clip-path.js";
import { getVisibleStroke, isAxisAlignedRect, parseAverageBorderRadius as parseBorderRadius } from "./shared/writer-utils.js";
import { roundedQuadPath } from "../geometry.js";
type RenderedOutline = {
color: number;
width: number;
style: string;
offset: number;
};
type ParsedBoxShadow = {
inset: boolean;
offsetX: number;
offsetY: number;
blur: number;
spread: number;
color: string;
};
function getVisibleOutline(style: Style): RenderedOutline | null {
if (!style.outlineWidth) return null;
const width = parseFloat(style.outlineWidth);
if (!Number.isFinite(width) || width <= 0) return null;
const outlineStyle = style.outlineStyle === "auto" ? "solid" : style.outlineStyle;
if (!outlineStyle || outlineStyle === "none") return null;
const color = cssColorToColorRef(style.outlineColor ?? style.color ?? style.stroke ?? style.fill);
if (color === null) return null;
const offset = style.outlineOffset ? parseFloat(style.outlineOffset) : 0;
return {
color,
width,
style: outlineStyle,
offset: Number.isFinite(offset) ? offset : 0,
};
}
function parseBoxShadow(boxShadow: string | undefined): ParsedBoxShadow[] {
if (!boxShadow || boxShadow === "none") return [];
const shadows: ParsedBoxShadow[] = [];
const parts: string[] = [];
let depth = 0;
let current = "";
for (const ch of boxShadow) {
if (ch === "(") depth += 1;
else if (ch === ")") depth -= 1;
else if (ch === "," && depth === 0) {
parts.push(current.trim());
current = "";
continue;
}
current += ch;
}
if (current.trim()) parts.push(current.trim());
for (const part of parts) {
const inset = /\binset\b/i.test(part);
const cleaned = part.replace(/\binset\b/gi, "").trim();
let color = "rgba(0,0,0,0.5)";
let numericPart = cleaned;
const rgbaMatch = cleaned.match(/rgba?\([^)]+\)/);
if (rgbaMatch) {
color = rgbaMatch[0];
numericPart = cleaned.replace(rgbaMatch[0], "").trim();
} else {
const hexMatch = cleaned.match(/#[0-9a-fA-F]{3,8}/);
if (hexMatch) {
color = hexMatch[0];
numericPart = cleaned.replace(hexMatch[0], "").trim();
}
}
const nums = numericPart.match(/-?[\d.]+px/g)?.map(value => Number.parseFloat(value)) ?? [];
if (nums.length >= 2) {
shadows.push({
inset,
offsetX: nums[0],
offsetY: nums[1],
blur: nums[2] ?? 0,
spread: nums[3] ?? 0,
color,
});
}
}
return shadows;
}
// ── Color helpers ───────────────────────────────────────────────────
// ── EMF Binary Helpers ──────────────────────────────────────────────
/** EMF record type constants. */
const EMR = {
HEADER: 0x0001,
POLYBEZIER: 0x0002,
POLYGON: 0x0003,
POLYLINE: 0x0004,
COMMENT: 0x0046,
SETWINDOWEXTEX: 0x0009,
SETWINDOWORGEX: 0x000A,
SAVEDC: 0x0021,
RESTOREDC: 0x0022,
EOF: 0x000E,
SETMAPMODE: 0x0011,
SETBKMODE: 0x0012,
SETPOLYFILLMODE: 0x0013,
SETTEXTALIGN: 0x0016,
SETTEXTCOLOR: 0x0018,
MOVETOEX: 0x001B,
LINETO: 0x0036,
SETWORLDTRANSFORM: 0x0023,
MODIFYWORLDTRANSFORM: 0x0024,
SELECTOBJECT: 0x0025,
CREATEPEN: 0x0026,
CREATEBRUSHINDIRECT: 0x0027,
DELETEOBJECT: 0x0028,
RECTANGLE: 0x002B,
ROUNDRECT: 0x002C,
ELLIPSE: 0x002E,
SELECTCLIPPATH: 0x0043,
BEGINPATH: 0x003B,
ENDPATH: 0x003C,
CLOSEFIGURE: 0x003D,
FILLPATH: 0x003E,
STROKEANDFILLPATH: 0x003F,
STROKEPATH: 0x0040,
EXTTEXTOUTW: 0x0054,
POLYGON16: 0x0056,
POLYLINE16: 0x0057,
POLYPOLYLINE16: 0x005A,
POLYPOLYGON16: 0x005B,
EXTCREATEFONTINDIRECTW: 0x0052,
STRETCHDIBITS: 0x0051,
INTERSECTCLIPRECT: 0x001E,
};
/** Brush styles. */
const BS_SOLID = 0x0000;
const BS_NULL = 0x0001;
/** Pen styles. */
const PS_SOLID = 0x0000;
const PS_DASH = 0x0001;
const PS_DOT = 0x0002;
const PS_DASHDOT = 0x0003;
const PS_NULL = 0x0005;
/** RGN_ modes for SELECTCLIPPATH. */
const RGN_AND = 0x0001;
const RGN_COPY = 0x0005;
/** Map mode: MM_TEXT (1 logical unit = 1 device pixel). */
const MM_TEXT = 0x0001;
/** Background mode: TRANSPARENT. */
const TRANSPARENT = 1;
/** Polygon fill modes. */
const ALTERNATE = 1;
const WINDING = 2;
/** Text alignment: TA_LEFT | TA_TOP. */
const TA_LEFT = 0;
const TA_TOP = 0;
const PX_TO_HUNDREDTH_MM = 2646 / 100;
const MAX_COMPAT_FRAME_HUNDREDTH_MM = 0xffff;
function getPageScaleHundredthMmPerPixel(width: number, height: number): { exScale: number; eyScale: number } {
const frameMetrics = getCompatibleFrameMetrics(width, height);
return {
exScale: frameMetrics.frameWidth / Math.max(width, 1),
eyScale: frameMetrics.frameHeight / Math.max(height, 1),
};
}
/**
* Low-level binary buffer for building EMF records.
*/
class EmfBuffer {
private chunks: Uint8Array[] = [];
private totalSize = 0;
private numRecords = 0;
/** Write a complete EMF record. */
writeRecord(type: number, data: Uint8Array | null): void {
const dataSize = data ? data.byteLength : 0;
const recordSize = 8 + dataSize;
// EMF records must be DWORD-aligned
const padded = (recordSize + 3) & ~3;
const buf = new Uint8Array(padded);
const view = new DataView(buf.buffer);
view.setUint32(0, type, true);
view.setUint32(4, padded, true);
if (data) buf.set(data, 8);
this.chunks.push(buf);
this.totalSize += padded;
this.numRecords++;
}
getNumRecords(): number { return this.numRecords; }
getTotalSize(): number { return this.totalSize; }
getChunks(): Uint8Array[] { return this.chunks; }
}
/** Build a Uint8Array from little-endian int32 values. */
function int32Array(...values: number[]): Uint8Array {
const buf = new Uint8Array(values.length * 4);
const view = new DataView(buf.buffer);
for (let i = 0; i < values.length; i++) {
view.setInt32(i * 4, values[i], true);
}
return buf;
}
/** Build a Uint8Array from little-endian uint32 values. */
function uint32Array(...values: number[]): Uint8Array {
const buf = new Uint8Array(values.length * 4);
const view = new DataView(buf.buffer);
for (let i = 0; i < values.length; i++) {
view.setUint32(i * 4, values[i], true);
}
return buf;
}
/** Build a Uint8Array from little-endian int16 values. */
function int16Array(...values: number[]): Uint8Array {
const buf = new Uint8Array(values.length * 2);
const view = new DataView(buf.buffer);
for (let i = 0; i < values.length; i++) {
view.setInt16(i * 2, values[i], true);
}
return buf;
}
/** Concatenate multiple Uint8Arrays. */
function concat(...arrays: Uint8Array[]): Uint8Array {
const total = arrays.reduce((s, a) => s + a.byteLength, 0);
const result = new Uint8Array(total);
let offset = 0;
for (const a of arrays) {
result.set(a, offset);
offset += a.byteLength;
}
return result;
}
/** Encode a string as UTF-16LE. */
function encodeUtf16LE(str: string): Uint8Array {
const buf = new Uint8Array(str.length * 2);
const view = new DataView(buf.buffer);
for (let i = 0; i < str.length; i++) {
view.setUint16(i * 2, str.charCodeAt(i), true);
}
return buf;
}
function getCompatibleFrameMetrics(width: number, height: number): {
frameWidth: number;
frameHeight: number;
millimeterWidth: number;
millimeterHeight: number;
micrometerWidth: number;
micrometerHeight: number;
} {
const rawFrameWidth = Math.max(1, Math.round(width * PX_TO_HUNDREDTH_MM));
const rawFrameHeight = Math.max(1, Math.round(height * PX_TO_HUNDREDTH_MM));
const scale = Math.min(1, MAX_COMPAT_FRAME_HUNDREDTH_MM / Math.max(rawFrameWidth, rawFrameHeight));
const frameWidth = Math.max(1, Math.round(rawFrameWidth * scale));
const frameHeight = Math.max(1, Math.round(rawFrameHeight * scale));
return {
frameWidth,
frameHeight,
millimeterWidth: Math.max(1, Math.round(frameWidth / 100)),
millimeterHeight: Math.max(1, Math.round(frameHeight / 100)),
micrometerWidth: frameWidth * 10,
micrometerHeight: frameHeight * 10,
};
}
// ── EMF Writer Options ──────────────────────────────────────────────
/** Options for the EMF writer. */
export type EMFWriterOptions = {
/** Viewport width in pixels. */
width: number;
/** Viewport height in pixels. */
height: number;
/** Scale factor. */
zoom?: number;
};
// ── EMF Writer Class ────────────────────────────────────────────────
export class EMFWriter implements Writer<Uint8Array> {
private width: number;
private height: number;
private emf!: EmfBuffer;
private records!: EmfBuffer;
private nextHandle = 0;
constructor(optionsOrWidth: EMFWriterOptions | number, height?: number, zoom?: number) {
if (typeof optionsOrWidth === "object") {
const z = optionsOrWidth.zoom ?? 1;
this.width = Math.round(optionsOrWidth.width * z);
this.height = Math.round(optionsOrWidth.height * z);
} else {
const z = zoom ?? 1;
this.width = Math.round(optionsOrWidth * z);
this.height = Math.round((height ?? 0) * z);
}
}
async begin(): Promise<void> {
this.records = new EmfBuffer();
this.nextHandle = 0;
// Set map mode to MM_TEXT (1:1 pixels)
this.records.writeRecord(EMR.SETMAPMODE, uint32Array(MM_TEXT));
// Set window origin and extents
this.records.writeRecord(EMR.SETWINDOWORGEX, int32Array(0, 0));
this.records.writeRecord(EMR.SETWINDOWEXTEX, int32Array(this.width, this.height));
// Set background mode to transparent (for text rendering)
this.records.writeRecord(EMR.SETBKMODE, uint32Array(TRANSPARENT));
// Set text alignment: left, top
this.records.writeRecord(EMR.SETTEXTALIGN, uint32Array(TA_LEFT | TA_TOP));
}
async drawPolygon(points: Quad, style: Style): Promise<void> {
// Skip fully transparent elements
if (style.opacity !== undefined && style.opacity <= 0) return;
const fillColor = cssColorToColorRef(style.fill);
const stroke = getVisibleStroke(style, cssColorToColorRef);
const outline = getVisibleOutline(style);
const clipBounds = getQuadBounds(points);
// Check for per-side borders
if (this.hasMixedBorders(style)) {
// Draw fill first, then per-side borders
if (fillColor !== null) {
this.saveState();
this.applyClip(style, clipBounds);
const brushHandle = this.createBrush(fillColor);
const penHandle = this.createPen(null);
this.selectObject(brushHandle);
this.selectObject(penHandle);
const bounds = this.computeBounds(points);
const ptData = int16Array(
...points.flatMap(p => [Math.round(p.x), Math.round(p.y)])
);
this.records.writeRecord(EMR.POLYGON16, concat(
int32Array(bounds.left, bounds.top, bounds.right, bounds.bottom),
uint32Array(4),
ptData
));
this.deleteObject(brushHandle);
this.deleteObject(penHandle);
this.restoreState();
}
this.drawPerSideBorders(points, style);
this.drawInsetBoxShadows(points, style);
return;
}
if (fillColor === null && !stroke && !outline) return;
this.saveState();
if (outline) this.drawOutline(points, style, outline);
this.applyClip(style, clipBounds);
const emfElW = Math.abs(points[1].x - points[0].x);
const emfElH = Math.abs(points[3].y - points[0].y);
const radius = parseBorderRadius(style.borderRadius, emfElW, emfElH);
// Rounded rectangle
if (radius > 0 && isAxisAlignedRect(points) && !style.cornerShapes) {
const x = Math.min(points[0].x, points[1].x, points[2].x, points[3].x);
const y = Math.min(points[0].y, points[1].y, points[2].y, points[3].y);
const w = Math.abs(points[1].x - points[0].x);
const h = Math.abs(points[3].y - points[0].y);
const r = Math.min(radius, w / 2, h / 2);
if (fillColor !== null || stroke) {
const brushHandle = this.createBrush(fillColor);
const penHandle = this.createPen(stroke);
this.selectObject(brushHandle);
this.selectObject(penHandle);
this.records.writeRecord(EMR.ROUNDRECT, int32Array(
Math.round(x), Math.round(y),
Math.round(x + w), Math.round(y + h),
Math.round(r * 2), Math.round(r * 2)
));
this.deleteObject(brushHandle);
this.deleteObject(penHandle);
}
this.drawInsetBoxShadows(points, style);
if (outline) this.drawOutline(points, style, outline);
this.restoreState();
return;
}
// Rounded quad (non-axis-aligned, or axis-aligned with corner-shape)
if (radius > 0 && (!isAxisAlignedRect(points) || style.cornerShapes)) {
const segs = roundedQuadPath(points, radius, style.cornerShapes);
const verts: { x: number; y: number }[] = [];
for (const s of segs) {
if (s.type === "M" || s.type === "L") {
verts.push({ x: s.x, y: s.y });
} else if (s.type === "Q") {
const prev = verts[verts.length - 1];
if (prev) {
for (let t = 0.25; t <= 1; t += 0.25) {
const u = 1 - t;
verts.push({
x: u * u * prev.x + 2 * u * t * s.cx + t * t * s.x,
y: u * u * prev.y + 2 * u * t * s.cy + t * t * s.y,
});
}
}
}
}
if (fillColor !== null || stroke) {
const brushHandle = this.createBrush(fillColor);
const penHandle = this.createPen(stroke);
this.selectObject(brushHandle);
this.selectObject(penHandle);
const emfBounds = this.computeBoundsFromPoints(verts);
const ptData = int16Array(
...verts.flatMap(p => [Math.round(p.x), Math.round(p.y)])
);
this.records.writeRecord(EMR.POLYGON16, concat(
int32Array(emfBounds.left, emfBounds.top, emfBounds.right, emfBounds.bottom),
uint32Array(verts.length),
ptData
));
this.deleteObject(brushHandle);
this.deleteObject(penHandle);
}
this.drawInsetBoxShadows(points, style);
if (outline) this.drawOutline(points, style, outline);
this.restoreState();
return;
}
// Regular polygon (quad)
if (fillColor !== null || stroke) {
const brushHandle = this.createBrush(fillColor);
const penHandle = this.createPen(stroke);
this.selectObject(brushHandle);
this.selectObject(penHandle);
const bounds = this.computeBounds(points);
const ptData = int16Array(
...points.flatMap(p => [Math.round(p.x), Math.round(p.y)])
);
this.records.writeRecord(EMR.POLYGON16, concat(
int32Array(bounds.left, bounds.top, bounds.right, bounds.bottom),
uint32Array(4),
ptData
));
this.deleteObject(brushHandle);
this.deleteObject(penHandle);
}
this.drawInsetBoxShadows(points, style);
if (outline) this.drawOutline(points, style, outline);
this.restoreState();
}
private drawInsetBoxShadows(points: Quad, style: Style): void {
if (!style.boxShadow || !isAxisAlignedRect(points) || style.cornerShapes) return;
const bounds = getQuadBounds(points);
const radius = parseBorderRadius(style.borderRadius, bounds.w, bounds.h);
const hasStyleClip = !!style.clipBounds || !!style.clipPath || !!style.clipQuads?.length;
for (const shadow of parseBoxShadow(style.boxShadow)) {
if (!shadow.inset || shadow.blur > 0) continue;
const color = cssColorToColorRef(shadow.color);
if (color === null) continue;
const innerX = bounds.x + shadow.spread + shadow.offsetX;
const innerY = bounds.y + shadow.spread + shadow.offsetY;
const innerW = bounds.w - shadow.spread * 2;
const innerH = bounds.h - shadow.spread * 2;
const pad = Math.max(Math.abs(shadow.spread) + Math.max(Math.abs(shadow.offsetX), Math.abs(shadow.offsetY)), 1) + 100;
const clipPoints = this.buildRoundedRectClipPoints(
bounds.x,
bounds.y,
bounds.w,
bounds.h,
radius,
radius,
);
const outerPoints = [
{ x: bounds.x - pad, y: bounds.y - pad },
{ x: bounds.x + bounds.w + pad, y: bounds.y - pad },
{ x: bounds.x + bounds.w + pad, y: bounds.y + bounds.h + pad },
{ x: bounds.x - pad, y: bounds.y + bounds.h + pad },
];
const innerPoints = innerW > 0 && innerH > 0
? this.buildRoundedRectClipPoints(
innerX,
innerY,
innerW,
innerH,
Math.min(radius, innerW / 2),
Math.min(radius, innerH / 2),
)
: [];
const brushHandle = this.createBrush(color);
const penHandle = this.createPen(null);
this.selectObject(brushHandle);
this.selectObject(penHandle);
this.records.writeRecord(EMR.SETPOLYFILLMODE, uint32Array(ALTERNATE));
this.applyPolygonClipPath(clipPoints, hasStyleClip ? RGN_AND : RGN_COPY);
this.records.writeRecord(EMR.BEGINPATH, null);
this.records.writeRecord(EMR.POLYGON16, concat(
int32Array(
Math.round(bounds.x - pad),
Math.round(bounds.y - pad),
Math.round(bounds.x + bounds.w + pad),
Math.round(bounds.y + bounds.h + pad),
),
uint32Array(outerPoints.length),
int16Array(...outerPoints.flatMap(point => [Math.round(point.x), Math.round(point.y)])),
));
if (innerPoints.length > 0) {
const innerBounds = this.computeBoundsFromPoints(innerPoints);
this.records.writeRecord(EMR.POLYGON16, concat(
int32Array(innerBounds.left, innerBounds.top, innerBounds.right, innerBounds.bottom),
uint32Array(innerPoints.length),
int16Array(...innerPoints.flatMap(point => [Math.round(point.x), Math.round(point.y)])),
));
}
this.records.writeRecord(EMR.ENDPATH, null);
this.records.writeRecord(EMR.FILLPATH, null);
this.deleteObject(brushHandle);
this.deleteObject(penHandle);
}
}
private drawOutline(points: Quad, style: Style, outline: RenderedOutline): void {
const penHandle = this.createPenStyled({ color: outline.color, width: outline.width }, undefined, outline.style);
const nullBrush = this.createBrush(null);
this.selectObject(nullBrush);
this.selectObject(penHandle);
if (isAxisAlignedRect(points) && !style.cornerShapes) {
const minX = Math.min(points[0].x, points[1].x, points[2].x, points[3].x);
const minY = Math.min(points[0].y, points[1].y, points[2].y, points[3].y);
const width = Math.abs(points[1].x - points[0].x);
const height = Math.abs(points[3].y - points[0].y);
const padding = outline.offset + outline.width / 2;
const radius = parseBorderRadius(style.borderRadius, width, height);
const outlineRadius = Math.min(Math.max(radius + padding, 0), (width + padding * 2) / 2, (height + padding * 2) / 2);
this.records.writeRecord(EMR.ROUNDRECT, int32Array(
Math.round(minX - padding),
Math.round(minY - padding),
Math.round(minX + width + padding),
Math.round(minY + height + padding),
Math.round(outlineRadius * 2),
Math.round(outlineRadius * 2)
));
} else {
const bounds = this.computeBounds(points);
const ptData = int16Array(...points.flatMap((point) => [Math.round(point.x), Math.round(point.y)]));
this.records.writeRecord(EMR.POLYGON16, concat(
int32Array(bounds.left, bounds.top, bounds.right, bounds.bottom),
uint32Array(4),
ptData
));
}
this.deleteObject(nullBrush);
this.deleteObject(penHandle);
}
async drawPolyline(points: Point[], closed: boolean, style: Style): Promise<void> {
if (points.length < 2) return;
if (style.opacity !== undefined && style.opacity <= 0) return;
const fillColor = cssColorToColorRef(style.fill);
const stroke = getVisibleStroke(style, cssColorToColorRef);
if (fillColor === null && !stroke) return;
this.saveState();
this.applyClip(style, getPointBounds(points));
if (style.pathSubpaths?.length) {
const drawableSubpaths = style.pathSubpaths.filter((subpath) => subpath.points.length >= 2);
const filledSubpaths = fillColor !== null
? drawableSubpaths.filter((subpath) => subpath.points.length >= 3)
: [];
const hasFilledSubpath = filledSubpaths.length > 0;
const strokeSubpaths = drawableSubpaths.filter((subpath) => !filledSubpaths.includes(subpath));
const brushHandle = this.createBrush(hasFilledSubpath ? fillColor : null);
const effectiveStroke = stroke ?? (!hasFilledSubpath && fillColor !== null ? { color: fillColor, width: 1 } : null);
const penHandle = this.createPenStyled(
effectiveStroke,
style.strokeDasharray,
);
this.selectObject(brushHandle);
this.selectObject(penHandle);
if (hasFilledSubpath) {
// Paint rejects EMR_FILLPATH-based painting here; classic POLYPOLYGON16
// output keeps compound fills importable while clip-path can still use paths.
this.records.writeRecord(
EMR.SETPOLYFILLMODE,
uint32Array(style.fillRule === "evenodd" ? ALTERNATE : WINDING),
);
this.writeMultiPolylineRecord(EMR.POLYPOLYGON16, filledSubpaths);
}
if (effectiveStroke && strokeSubpaths.length > 0) {
this.writeMultiPolylineRecord(EMR.POLYPOLYLINE16, strokeSubpaths);
}
this.deleteObject(brushHandle);
this.deleteObject(penHandle);
this.restoreState();
return;
}
if (closed && fillColor !== null && points.length >= 3) {
// Draw as filled polygon
const brushHandle = this.createBrush(fillColor);
const penHandle = this.createPenStyled(stroke, style.strokeDasharray);
this.selectObject(brushHandle);
this.selectObject(penHandle);
const bounds = this.computeBoundsFromPoints(points);
const ptData = int16Array(
...points.flatMap(p => [Math.round(p.x), Math.round(p.y)])
);
this.records.writeRecord(EMR.POLYGON16, concat(
int32Array(bounds.left, bounds.top, bounds.right, bounds.bottom),
uint32Array(points.length),
ptData
));
this.deleteObject(brushHandle);
this.deleteObject(penHandle);
} else {
// Draw as polyline (stroke only)
const penHandle = this.createPenStyled(
stroke ?? { color: fillColor ?? 0, width: 1 },
style.strokeDasharray
);
const nullBrush = this.createBrush(null);
this.selectObject(nullBrush);
this.selectObject(penHandle);
const bounds = this.computeBoundsFromPoints(points);
const ptData = int16Array(
...points.flatMap(p => [Math.round(p.x), Math.round(p.y)])
);
this.records.writeRecord(EMR.POLYLINE16, concat(
int32Array(bounds.left, bounds.top, bounds.right, bounds.bottom),
uint32Array(points.length),
ptData
));
this.deleteObject(nullBrush);
this.deleteObject(penHandle);
}
this.restoreState();
}
async drawText(quad: Quad, text: string, style: Style): Promise<void> {
const sanitized = normalizeWhitespaceAwareText(text, style);
if (sanitized.length === 0) return;
if (style.opacity !== undefined && style.opacity <= 0) return;
this.saveState();
this.applyClip(style, getQuadBounds(quad));
// Text color
const textColor = cssColorToColorRef(style.color) ?? cssColorToColorRef(style.fill) ?? 0x00000000;
this.records.writeRecord(EMR.SETTEXTCOLOR, uint32Array(textColor));
// Font metrics
const quadHeight = Math.sqrt(
(quad[3].x - quad[0].x) ** 2 + (quad[3].y - quad[0].y) ** 2
);
const styleFontSize = style.fontSize ? parseFloat(style.fontSize) : 12;
const fontSize = quadHeight > 0 ? Math.min(styleFontSize, quadHeight) : styleFontSize;
// Rotation from top edge
const dx = quad[1].x - quad[0].x;
const dy = quad[1].y - quad[0].y;
const angleRad = Math.atan2(dy, dx);
// EMF escapement/orientation in tenths of a degree, counter-clockwise
const angleTenths = Math.round(-angleRad * (1800 / Math.PI));
// Create font
const fontFamily = style.fontFamily?.split(",")[0]?.trim().replace(/['"]/g, "") || "Arial";
const isBold = style.fontWeight === "bold" || !!(style.fontWeight && parseInt(style.fontWeight) >= 700);
const isItalic = style.fontStyle === "italic" || style.fontStyle === "oblique";
const fontHandle = this.createFont(Math.round(fontSize), angleTenths, fontFamily, isBold, !!isItalic);
this.selectObject(fontHandle);
// Position: top-left of the text, offset by half-leading
const halfLeading = Math.max(0, (quadHeight - fontSize) / 2);
const t = quadHeight > 0 ? halfLeading / quadHeight : 0;
const x = Math.round(quad[0].x + (quad[3].x - quad[0].x) * t);
const y = Math.round(quad[0].y + (quad[3].y - quad[0].y) * t);
// EMR_EXTTEXTOUTW record
const textUtf16 = encodeUtf16LE(sanitized);
const nChars = sanitized.length;
// rclBounds (text bounding rect — approximate)
const bounds = this.computeBounds(quad);
// Build the EMRTEXT structure
// ptlReference: POINTL
// nChars: UINT32
// offString: UINT32 (offset from start of record data to string)
// fOptions: UINT32 (0 = no clipping/opaque)
// rcl: RECTL (optional clipping rect — set to same as bounds)
// offDx: UINT32 (offset to intercharacter spacing array, 0 = none)
// Record data layout after the 8-byte record header:
// [0..15] rclBounds (4 × int32)
// [16..19] iGraphicsMode (1 = GM_COMPATIBLE)
// [20..23] exScale (float, page scale in 0.01 mm per logical unit)
// [24..27] eyScale (float, page scale in 0.01 mm per logical unit)
// [28..35] EMRTEXT.ptlReference (2 × int32 = x, y)
// [36..39] EMRTEXT.nChars
// [40..43] EMRTEXT.offString (offset from record start)
// [44..47] EMRTEXT.fOptions
// [48..63] EMRTEXT.rcl (4 × int32 — clipping rect)
// [64..67] EMRTEXT.offDx (0 = no spacing array)
// [68..] string data (UTF-16LE)
const offString = 8 + 68; // record header (8) + data before string (68)
const recordData = new Uint8Array(68 + textUtf16.byteLength);
const dv = new DataView(recordData.buffer);
const pageScale = getPageScaleHundredthMmPerPixel(this.width, this.height);
// rclBounds
dv.setInt32(0, bounds.left, true);
dv.setInt32(4, bounds.top, true);
dv.setInt32(8, bounds.right, true);
dv.setInt32(12, bounds.bottom, true);
// iGraphicsMode = GM_COMPATIBLE (1)
dv.setUint32(16, 1, true);
// exScale/eyScale match the page's 0.01 mm per logical-pixel scale.
dv.setFloat32(20, pageScale.exScale, true);
dv.setFloat32(24, pageScale.eyScale, true);
// EMRTEXT
dv.setInt32(28, x, true); // ptlReference.x
dv.setInt32(32, y, true); // ptlReference.y
dv.setUint32(36, nChars, true); // nChars
dv.setUint32(40, offString, true); // offString
dv.setUint32(44, 0, true); // fOptions
// rcl
dv.setInt32(48, bounds.left, true);
dv.setInt32(52, bounds.top, true);
dv.setInt32(56, bounds.right, true);
dv.setInt32(60, bounds.bottom, true);
// offDx
dv.setUint32(64, 0, true);
// String data
recordData.set(textUtf16, 68);
this.records.writeRecord(EMR.EXTTEXTOUTW, recordData);
this.deleteObject(fontHandle);
this.restoreState();
}
async drawImage(quad: Quad, dataUrl: string, width: number, height: number, style: Style, rgbData?: number[]): Promise<void> {
if (!rgbData || rgbData.length === 0) return;
if (style.opacity !== undefined && style.opacity <= 0) return;
const dx = quad[1].x - quad[0].x;
const dy = quad[1].y - quad[0].y;
const displayW = Math.sqrt(dx * dx + dy * dy);
const ldx = quad[3].x - quad[0].x;
const ldy = quad[3].y - quad[0].y;
const displayH = Math.sqrt(ldx * ldx + ldy * ldy);
if (displayW <= 0 || displayH <= 0) return;
this.saveState();
this.applyClip(style, getQuadBounds(quad));
// Apply rotation via world transform if the quad is rotated
const angle = Math.atan2(dy, dx);
if (Math.abs(angle) > 0.01) {
const cosA = Math.cos(angle);
const sinA = Math.sin(angle);
const cx = quad[0].x;
const cy = quad[0].y;
// Rotation around (cx, cy): maps (cx, cy) → (cx, cy), (cx+w, cy) → rotated right edge
this.setWorldTransform(
cosA, sinA, -sinA, cosA,
cx * (1 - cosA) + cy * sinA,
cy * (1 - cosA) - cx * sinA
);
}
const x = Math.round(quad[0].x);
const y = Math.round(quad[0].y);
// Build a 24-bit uncompressed DIB from rgbData (RGB → BGR, row-padded)
const bmpHeaderSize = 40; // BITMAPINFOHEADER
const rowBytes = ((width * 3 + 3) & ~3); // rows padded to 4-byte boundary
const bmpDataSize = rowBytes * height;
const dib = new Uint8Array(bmpHeaderSize + bmpDataSize);
const dibView = new DataView(dib.buffer);
// BITMAPINFOHEADER
dibView.setUint32(0, 40, true); // biSize
dibView.setInt32(4, width, true); // biWidth
dibView.setInt32(8, height, true); // biHeight (positive = bottom-up for broader EMF compatibility)
dibView.setUint16(12, 1, true); // biPlanes
dibView.setUint16(14, 24, true); // biBitCount (24-bit RGB)
dibView.setUint32(16, 0, true); // biCompression (BI_RGB)
dibView.setUint32(20, bmpDataSize, true); // biSizeImage
dibView.setUint32(24, 0, true); // biXPelsPerMeter
dibView.setUint32(28, 0, true); // biYPelsPerMeter
dibView.setUint32(32, 0, true); // biClrUsed
dibView.setUint32(36, 0, true); // biClrImportant
// Convert RGB to BGR row data with padding.
// EMF consumers are more broadly compatible with bottom-up BI_RGB DIBs.
const pixelOffset = bmpHeaderSize;
for (let row = 0; row < height; row++) {
const srcRowStart = (height - 1 - row) * width * 3;
const dstRowStart = pixelOffset + row * rowBytes;
for (let col = 0; col < width; col++) {
const si = srcRowStart + col * 3;
const di = dstRowStart + col * 3;
dib[di] = rgbData[si + 2]; // B
dib[di + 1] = rgbData[si + 1]; // G
dib[di + 2] = rgbData[si]; // R
}
}
// Record data layout for EMR_STRETCHDIBITS:
// rclBounds (4 × int32)
// xDest, yDest (int32)
// xSrc, ySrc (int32)
// cxSrc, cySrc (int32)
// offBmiSrc (uint32) — offset from record start to BITMAPINFO
// cbBmiSrc (uint32) — size of BITMAPINFO
// offBitsSrc (uint32) — offset from record start to bitmap bits
// cbBitsSrc (uint32) — size of bitmap bits
// iUsageSrc (uint32) — DIB_RGB_COLORS = 0
// dwRop (uint32) — SRCCOPY = 0x00CC0020
// cxDest, cyDest (int32) — destination width/height
const headerDataSize = 72; // fixed EMRSTRETCHDIBITS fields before DIB data
const offBmi = 8 + headerDataSize; // offset from record start
const offBits = offBmi + bmpHeaderSize;
const recordData = new Uint8Array(headerDataSize + bmpHeaderSize + bmpDataSize);
const rv = new DataView(recordData.buffer);
const bounds = this.computeBounds(quad);
// rclBounds
rv.setInt32(0, bounds.left, true);
rv.setInt32(4, bounds.top, true);
rv.setInt32(8, bounds.right, true);
rv.setInt32(12, bounds.bottom, true);
// xDest, yDest
rv.setInt32(16, x, true);
rv.setInt32(20, y, true);
// xSrc, ySrc
rv.setInt32(24, 0, true);
rv.setInt32(28, 0, true);
// cxSrc, cySrc
rv.setInt32(32, width, true);
rv.setInt32(36, height, true);
// offBmiSrc
rv.setUint32(40, offBmi, true);
// cbBmiSrc
rv.setUint32(44, bmpHeaderSize, true);
// offBitsSrc
rv.setUint32(48, offBits, true);
// cbBitsSrc
rv.setUint32(52, bmpDataSize, true);
// iUsageSrc (DIB_RGB_COLORS)
rv.setUint32(56, 0, true);
// dwRop = SRCCOPY
rv.setUint32(60, 0x00CC0020, true);
// cxDest, cyDest
rv.setInt32(64, Math.round(displayW), true);
rv.setInt32(68, Math.round(displayH), true);
// Copy DIB header + pixel data
recordData.set(dib.subarray(0, bmpHeaderSize), headerDataSize);
recordData.set(dib.subarray(bmpHeaderSize), headerDataSize + bmpHeaderSize);
this.records.writeRecord(EMR.STRETCHDIBITS, recordData);
this.restoreState();
}
async end(): Promise<Uint8Array> {
// Write EOF record
this.records.writeRecord(EMR.EOF, uint32Array(0, 0, 20)); // nPalEntries=0, offPalEntries=0, nSizeLast=20
// Build the EMF header
const nRecords = this.records.getNumRecords() + 1; // +1 for the header record itself
const bodySize = this.records.getTotalSize();
// EMF header record data (beyond the 8-byte record type+size):
// rclBounds: RECTL (4 × int32) — inclusive-inclusive bounding rect in device units
// rclFrame: RECTL (4 × int32) — bounding rect in 0.01mm units
// dSignature: UINT32 = 0x464D4520 (' EMF')
// nVersion: UINT32 = 0x00010000
// nBytes: UINT32 — total file size
// nRecords: UINT32
// nHandles: UINT16
// sReserved: UINT16
// nDescription: UINT32
// offDescription: UINT32
// nPalEntries: UINT32
// szlDevice: SIZEL (2 × int32) — reference device size in pixels
// szlMillimeters: SIZEL (2 × int32) — reference device size in mm
// --- Extended header fields (improves viewer compatibility) ---
// cbPixelFormat: UINT32 — size of pixel format descriptor (0 = none)
// offPixelFormat: UINT32 — offset to pixel format descriptor (0 = none)
// bOpenGL: UINT32 — whether OpenGL commands present (0 = no)
// szlMicrometers: SIZEL (2 × int32) — device size in micrometers
const headerDataSize = 100; // extended header
const headerRecordSize = 8 + headerDataSize;
const totalSize = headerRecordSize + bodySize;
const headerData = new Uint8Array(headerDataSize);
const hv = new DataView(headerData.buffer);
// rclBounds (device units, inclusive)
hv.setInt32(0, 0, true); // left
hv.setInt32(4, 0, true); // top
hv.setInt32(8, this.width - 1, true); // right
hv.setInt32(12, this.height - 1, true); // bottom
// Some legacy EMF consumers fail once rclFrame exceeds 16-bit-sized dimensions.
// Keep the physical frame metadata within that range while preserving aspect ratio.
const frameMetrics = getCompatibleFrameMetrics(this.width, this.height);
hv.setInt32(16, 0, true);
hv.setInt32(20, 0, true);
hv.setInt32(24, frameMetrics.frameWidth, true);
hv.setInt32(28, frameMetrics.frameHeight, true);
// Signature: ' EMF' = 0x464D4520
hv.setUint32(32, 0x464D4520, true);
// Version
hv.setUint32(36, 0x00010000, true);
// Total file size
hv.setUint32(40, totalSize, true);
// Number of records
hv.setUint32(44, nRecords, true);
// Number of handles
hv.setUint16(48, this.nextHandle + 1, true);
// Reserved
hv.setUint16(50, 0, true);
// Description (none)