Skip to content

Commit ecedc6a

Browse files
committed
Preserve partially clipped SVG images as vectors in PDF
Rectangular overflow clipping rasterized SVG image elements even when a PDF writer could apply the clip to their vector paths. Small icons then appeared pixelated when zoomed. Add the opt-in vectorizeClippedSvgImages extraction option. Intersect the image viewport with the overflow rectangle and attach the clip to the converted paths. Preserve the existing raster fallback for rounded clips, compositing effects, and source crops. Cover enclosed, partially clipped, and rounded SVG images in Chromium and Firefox. Verify that all 83 chain icons in the FA13 PDF export remain vector geometry, including the 76 that previously rendered as 14 by 14 pixel bitmaps.
1 parent 971e9db commit ecedc6a

5 files changed

Lines changed: 82 additions & 10 deletions

File tree

‎README.md‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -226,6 +226,7 @@ Main entry point. Traverses the DOM tree under `root`, builds a stacking context
226226
| `zoom` | `number` | `1` | Scale factor applied to all extracted coordinates. Useful when the source DOM is rendered at a different zoom level |
227227
| `imageScale` | `number` | `1` | Scale factor for rasterizing embedded images. Higher values (e.g. `2`) produce sharper images when zooming in on the exported file. Max pixel dimension is capped at 4096 |
228228
| `svgToVector` | `boolean` | `false` | When true, embedded SVG images (in `<img>` tags and CSS `background-image`) are always converted to vector IR nodes (polygon, polyline, text) instead of being rasterized to bitmap image nodes. This produces resolution-independent output but may not accurately render SVGs that use fill-rule:evenodd with complex multi-subpath paths. |
229+
| `vectorizeClippedSvgImages` | `boolean` | `false` | Preserves SVG `<img>` geometry when an axis-aligned rectangular overflow clip partially covers the image in the normal scroll viewport. Enable for writers that honor rectangular vector clips, such as PDFWriter. |
229230
| `convertFormControls` | `boolean` | `false` | When true, native form controls are converted into synthetic IR nodes that preserve visible values and states across writers. Supported controls include checkbox, radio, range, file, text-like inputs (including date/time variants), textarea, select, progress, and meter. |
230231
| `includePseudoElements` | `boolean` | `true` | When true, `::before` and `::after` pseudo-elements with generated content are extracted into the IR as polygon and text nodes. Be careful, this option modifies original DOM cause it need to create real elements for them in DOM. CSS `counter()`, `counters()`, `attr()`, `open-quote`/`close-quote`, and string literals are resolved. Best results with Firefox (native `getBoxQuads` on pseudo replacement elements). |
231232

@@ -708,7 +709,7 @@ import {
708709
Enable with `includeImages: true`. All image preloading and embedding is now **automatic** and handled internally by `extractIR` (no need to call any preload function). For custom pipelines, the async image helpers can also fetch/decode what they need on demand; `preloadImages()` is only an optimization. The DOM is **not mutated** during preloading.
709710

710711
- **All images** (including `<img>` and CSS `background-image: url()`, even in Shadow DOM) are embedded as data URLs in all output formats (DXF, PDF, PNG, SVG, HTML).
711-
- **SVG images** (`data:image/svg+xml`, `.svg` URLs): automatically converted to vector geometry (polygons, polylines, text) — no rasterization.
712+
- **SVG images** (`data:image/svg+xml`, `.svg` URLs): converted to vector geometry when the image needs no raster effects or cropping. An enclosing rectangular overflow clip preserves the vector output. The `vectorizeClippedSvgImages` option also preserves vector `<img>` content under partial rectangular clipping for PDF.
712713
- **Raster images** (PNG, JPEG, GIF, WebP, data URLs, remote URLs): extracted as `image` IR nodes with embedded data URL.
713714
- **Video elements**: enable with `includeVideos: true` to rasterize each `<video>` into an `image` IR node using its first decoded frame. `imageScale` also applies to video frame rasterization.
714715
- **CSS `background-image: url()`**: SVG URLs are vector-converted; raster URLs are extracted as image nodes.

‎memories/htmlConverter-image-extractor-notes.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@
1313
- Low-level image helpers (`extractImageGeometry`, `extractBackgroundImage`, and the masked-image path) are now async and must not depend on `preloadImages()` for correctness; direct custom-pipeline calls should work on remote SVG/CSS image URLs without an explicit preload step.
1414
- Page-side remote image preloads should not use `credentials: "include"`; cross-origin SVG/image fetches in the browser context need default/same-origin credentials or ACAO `*` routes start failing and remote SVG fallback tests regress.
1515
- Asset waits must be bounded: image decode/fetch and video readiness can otherwise stall extraction indefinitely on ad-heavy pages. Prefer timeouts that skip the bad asset over waiting forever.
16+
- For PDF, `vectorizeClippedSvgImages` preserves eligible SVG image paths by intersecting the rectangular overflow clip with the image viewport. Keep it opt-in for writers that support clips on vector geometry.
1617

1718

1819
- Pixelated or tiny raster CSS background images need two protections in `renderBackgroundImage()`: disable canvas smoothing for the draw, and keep the output as PNG instead of JPEG. Nearest-neighbor drawing alone is not enough because JPEG re-encoding reintroduces blur at hard pixel edges.

‎src/extractors/image-extractor.ts‎

Lines changed: 39 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1337,14 +1337,35 @@ function isVisibleCssColor(color: string | undefined): color is string {
13371337
return true;
13381338
}
13391339

1340-
function requiresRasterSvgImage(style: Style): boolean {
1340+
function requiresRasterSvgImage(style: Style, imageQuad?: Quad, vectorClip?: Style["clipBounds"]): boolean {
13411341
if (style.filter && style.filter !== "none") return true;
13421342
if (style.mixBlendMode && style.mixBlendMode !== "normal") return true;
13431343
if (style.mask && style.mask !== "none") return true;
13441344
if (style.clipPath && style.clipPath !== "none") return true;
1345-
if (style.clipBounds) return true;
13461345
if (style.clipQuads?.length) return true;
1347-
return false;
1346+
const clip = style.clipBounds;
1347+
if (!clip) return false;
1348+
if (vectorClip) return false;
1349+
// An enclosing rectangular overflow clip leaves the image untouched.
1350+
return !imageQuad || clip.radius !== 0 || (style.opacity ?? 1) !== 1
1351+
|| !imageQuad.every(({ x, y }) =>
1352+
x >= clip.x && x <= clip.x + clip.w && y >= clip.y && y <= clip.y + clip.h);
1353+
}
1354+
1355+
function getSvgImageVectorClip(style: Style, quad: Quad): Style["clipBounds"] {
1356+
const clip = style.clipBounds;
1357+
if (!clip || clip.radius !== 0 || (style.opacity ?? 1) !== 1) return;
1358+
1359+
const [topLeft, topRight, bottomRight, bottomLeft] = quad;
1360+
if (topLeft.y !== topRight.y || bottomLeft.y !== bottomRight.y ||
1361+
topLeft.x !== bottomLeft.x || topRight.x !== bottomRight.x) return;
1362+
1363+
// SVG images have their own viewport clip, so intersect it with the overflow clip.
1364+
const x = Math.max(clip.x, Math.min(topLeft.x, bottomRight.x));
1365+
const y = Math.max(clip.y, Math.min(topLeft.y, bottomRight.y));
1366+
const right = Math.min(clip.x + clip.w, Math.max(topLeft.x, bottomRight.x));
1367+
const bottom = Math.min(clip.y + clip.h, Math.max(topLeft.y, bottomRight.y));
1368+
if (right > x && bottom > y) return { x, y, w: right - x, h: bottom - y, radius: 0 };
13481369
}
13491370

13501371
/**
@@ -1384,13 +1405,22 @@ export async function extractImageGeometry(
13841405

13851406
// Keep SVG <img> elements as image layers when CSS effects or clipping need to
13861407
// apply to the image as a single composited unit.
1387-
if (isSvgSource(src) && !objectFitPlan.sourceRect && !requiresRasterSvgImage(style)) {
1388-
const svgContent = extractSvgContent(src);
1389-
if (svgContent) {
1390-
const svgNodes = convertSvgToGeometry(svgContent, el, adjustedQuad, globalIndex, options);
1391-
if (svgNodes.length > 0) return svgNodes;
1408+
if (isSvgSource(src) && !objectFitPlan.sourceRect) {
1409+
const vectorClip = options.vectorizeClippedSvgImages && options.rootScrollBehavior !== "expand"
1410+
? getSvgImageVectorClip(style, adjustedQuad)
1411+
: undefined;
1412+
if (!requiresRasterSvgImage(style, adjustedQuad, vectorClip)) {
1413+
const svgContent = extractSvgContent(src);
1414+
if (svgContent) {
1415+
const svgNodes = convertSvgToGeometry(svgContent, el, adjustedQuad, globalIndex, options);
1416+
if (svgNodes.length > 0) {
1417+
if (vectorClip) {
1418+
for (const node of svgNodes) node.style.clipBounds = vectorClip;
1419+
}
1420+
return svgNodes;
1421+
}
1422+
}
13921423
}
1393-
// Fallback: rasterize SVG via canvas (below)
13941424
}
13951425

13961426
// Raster image: render to canvas at display size (scaled by imageScale) for consistent output

‎src/types.ts‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -217,6 +217,12 @@ export type Options = {
217217
* Defaults to false (SVGs with evenodd multi-subpath paths are rasterized).
218218
*/
219219
svgToVector?: boolean;
220+
/**
221+
* Preserve SVG <img> geometry under a rectangular overflow clip in the normal scroll viewport.
222+
* Enable only for writers that honor rectangular clips on vector nodes, such as PDFWriter.
223+
* Defaults to false.
224+
*/
225+
vectorizeClippedSvgImages?: boolean;
220226
/**
221227
* When true, native form controls are converted to synthetic IR nodes that
222228
* preserve their visible state or value (for example checkbox/radio state,

‎tests/unit/image-extractor.test.ts‎

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -399,6 +399,40 @@ test.describe("Image Extraction", () => {
399399
expect(imageNodes.length).toBe(0);
400400
});
401401

402+
test("preserves partially clipped SVG images as vectors when rectangular clipping is enabled", async ({ page }) => {
403+
await setupPage(page, `
404+
<div style="overflow:hidden;width:120px;height:80px">
405+
<img id="inside" src="${SVG_RECT_DATA_URL}" style="display:block;width:60px;height:30px">
406+
<img id="cropped" src="${SVG_RECT_DATA_URL}" style="display:block;margin-left:90px;width:60px;height:30px">
407+
</div>
408+
<div style="overflow:hidden;border-radius:20px;width:120px;height:80px">
409+
<img id="rounded" src="${SVG_RECT_DATA_URL}" style="display:block;width:60px;height:30px">
410+
</div>`);
411+
412+
const extractImages = (vectorizeClippedSvgImages?: boolean) => page.evaluate(async (vectorizeClippedSvgImages) => {
413+
const ir = await (window as any).__HC.extractIR(document.body, {
414+
includeImages: true,
415+
includeSourceMetadata: true,
416+
vectorizeClippedSvgImages,
417+
});
418+
return ir.filter((node: any) => node.source?.originalType === "img");
419+
}, vectorizeClippedSvgImages);
420+
421+
const byId = (images: any[], id: string) => images.find(node => node.source.id === id);
422+
const defaults = await extractImages();
423+
expect(byId(defaults, "inside")?.type).toBe("polygon");
424+
expect(byId(defaults, "cropped")?.type).toBe("image");
425+
expect(byId(defaults, "rounded")?.type).toBe("image");
426+
427+
const clipped = await extractImages(true);
428+
expect(byId(clipped, "inside")?.type).toBe("polygon");
429+
expect(byId(clipped, "cropped")).toMatchObject({
430+
type: "polygon",
431+
style: { clipBounds: { x: 90, y: 30, w: 30, h: 30, radius: 0 } },
432+
});
433+
expect(byId(clipped, "rounded")?.type).toBe("image");
434+
});
435+
402436
test("remaps compound SVG path subpaths into the image quad", async ({ page }) => {
403437
const SVG_COMPOUND_DATA_URL = "data:image/svg+xml," + encodeURIComponent(
404438
'<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 20"><path fill="red" d="M5 5H25V15H5Z M40 5H60V15H40Z"/></svg>'

0 commit comments

Comments
 (0)