Turn SVG markup into editable shapes that keep their paths, colors, gradients and strokes.
engine.block.createFromSVG() reads SVG markup, such as the content of an SVG file or the SVG code that Adobe Illustrator copies to the clipboard, and creates graphic blocks from it. On a server, this lets you turn uploaded vector artwork into a scene whose shapes stay editable, then save or export it. To place an SVG file as one flat image instead, see Insert Images.
This guide covers what the import creates, how to add the result to a page and fit it, how SVG units map to the scene’s design unit, how to edit the imported shapes, how to handle import errors, and how to export the result.
Initializing the Engine#
We initialize the headless engine from @cesdk/node. The license is optional, because the engine runs in trial mode without one.
const engine = await CreativeEngine.init({ baseURL: process.env.IMGLY_LOCAL_ASSETS_URL // license: process.env.CESDK_LICENSE, // Optional (trial mode available)});Importing the SVG Markup#
We use SVG markup for a badge: a circle with a radial gradient, a star with a stroke, and a dashed line. On a server, the markup usually comes from a file, which you read with readFileSync(path, 'utf8') from Node’s fs module.
// A badge with a radial gradient, a stroked star and a dashed line.// On a server, the markup often comes from a file: readFileSync('badge.svg', 'utf8').const badgeSVG = `<svg xmlns="http://www.w3.org/2000/svg" width="240" height="240" viewBox="0 0 240 240"> <defs> <radialGradient id="glow" cx="120" cy="120" r="110" gradientUnits="userSpaceOnUse"> <stop offset="0" stop-color="#ffd166"/> <stop offset="1" stop-color="#ef476f"/> </radialGradient> </defs> <circle cx="120" cy="120" r="110" fill="url(#glow)"/> <polygon points="120,40 143,97 205,97 155,133 174,192 120,156 66,192 85,133 35,97 97,97" fill="#ffffff" stroke="#073b4c" stroke-width="6" stroke-linejoin="round"/> <path d="M60 212 H180" fill="none" stroke="#073b4c" stroke-width="4" stroke-dasharray="12 6" stroke-linecap="round"/></svg>`;We pass the markup to engine.block.createFromSVG(svg). The created blocks have no parent, so we append the returned block to the page with engine.block.appendChild(). Until then, the blocks are not part of the page and do not appear in an export.
const badge = engine.block.createFromSVG(badgeSVG);engine.block.appendChild(page, badge);Understanding What the Import Creates#
Each SVG shape (path, rect, circle, ellipse, line, polyline and polygon) becomes a graphic block with a vector_path shape. The block keeps the shape’s fill color or its linear or radial gradient, and its stroke with color, width, joins, caps and dashes. A shape with fill="none" gets its fill disabled and keeps its stroke.
When the SVG has one shape, the call returns that graphic block. When it has more, the call returns a group. The group holds the shapes in paint order, so the first child is the bottom-most shape.
// Three shapes give a group. Its children are in paint order.console.log(engine.block.getType(badge)); // '//ly.img.ubq/group'const [circle, star, line] = engine.block.getChildren(badge);for (const child of [circle, star, line]) { const shape = engine.block.getShape(child); console.log(engine.block.getType(shape)); // '//ly.img.ubq/shape/vector_path'}Mapping SVG Units to the Design Unit#
The import reads one SVG user unit as one pixel in a scene that uses pixels. In a scene that uses millimeters or inches, one user unit is one point (1/72 inch), as Adobe Illustrator writes it. An SVG whose width and height are given in mm or in keeps its physical size. We read the scene’s unit with engine.scene.getDesignUnit(). See Design Units to change it.
// One SVG user unit is one pixel in this scene.console.log(engine.scene.getDesignUnit()); // 'Pixel'Fitting the Design on the Page#
The position and size of the returned block are readable right after the import. We compute a factor that makes the badge fill 80% of the page, and apply it with engine.block.scale(). This call scales the children and their stroke widths and dashes too, so the design keeps its proportions. Then we center the block with engine.block.setPositionX() and engine.block.setPositionY().
// The group's size is readable right after the import.const pageWidth = engine.block.getWidth(page);const pageHeight = engine.block.getHeight(page);const factor = 0.8 * Math.min( pageWidth / engine.block.getWidth(badge), pageHeight / engine.block.getHeight(badge) );// scale() also scales the stroke widths and dashes.engine.block.scale(badge, factor);engine.block.setPositionX( badge, (pageWidth - engine.block.getWidth(badge)) / 2);engine.block.setPositionY( badge, (pageHeight - engine.block.getHeight(badge)) / 2);Editing the Imported Shapes#
The imported shapes are ordinary graphic blocks. We change the star’s fill color with engine.block.getFill() and engine.block.setColor(), and make the dashed line thicker with engine.block.setStrokeWidth(). To work with the shapes as separate blocks, dissolve the group with engine.block.ungroup(). See Grouping.
// Imported shapes are graphic blocks with ordinary fills and strokes.const starFill = engine.block.getFill(star);engine.block.setColor(starFill, 'fill/color/value', { r: 0.02, g: 0.84, b: 0.63, a: 1});engine.block.setStrokeWidth(line, 12);Handling Import Errors#
When the import fails, the call throws an error and creates no block. @cesdk/node puts the catalog code on the thrown Error, so we check for a code property and read it:
BLOCK.SVG_NOT_READABLE: the markup has no<svg>root element.BLOCK.SVG_EMPTY: the SVG has no size, or draws nothing inside its viewport.BLOCK.SVG_TOO_MANY_PARTS: the SVG has more than 5000 parts.BLOCK.SVG_PART_NOT_RENDERED: the server had too little memory to draw a part without a shape as an image.
// @cesdk/node puts the catalog code on the thrown Error.try { engine.block.createFromSVG('<html><body>No SVG here</body></html>');} catch (error) { if (error instanceof Error && 'code' in error) { console.log(error.code); // 'BLOCK.SVG_NOT_READABLE' } else { throw error; }}Exporting the Result#
We export the page with engine.block.export() and write the PNG to the output folder to check the result.
const outputDir = './output';if (!existsSync(outputDir)) { mkdirSync(outputDir, { recursive: true });}const blob = await engine.block.export(page, { mimeType: 'image/png' });writeFileSync( `${outputDir}/imported-svg.png`, Buffer.from(await blob.arrayBuffer()));console.log('Exported the page to output/imported-svg.png');Cleaning Up#
We dispose the engine in a finally block, so its resources are freed also when a step fails.
engine.dispose();Troubleshooting#
- The export does not show the imported design: the created blocks have no parent. Append the returned block to a page with
engine.block.appendChild(). - The design is much larger or smaller than expected: check the scene’s design unit. The same SVG has a different size in a pixel scene and in a millimeter scene. Fit the block to the page with
engine.block.scale()after the import. - Some parts cannot be edited as paths: text, embedded images, filters, masks and patterns become image fills. Recreate text with a text block if it must stay editable.
- Text in the SVG is missing or draws in another font: the import turns each text into an image at once, with the fonts that are loaded at that moment. Text draws in a font of its family when the scene or a font asset source has one and that font is already loaded, and in the default font otherwise. Text that needs the default font is left out for good when the default font is not loaded yet. Emoji and other characters that need a fallback font draw as the missing-character mark when that fallback font is not loaded yet, because the import does not wait for it. Convert the text to outlines before you export the SVG, so that the import shows it in every case.
- The import fails with an SVG that has content (
BLOCK.SVG_EMPTY): give the SVG aviewBox, or awidthandheight, and check that its shapes are inside the viewport. - A large illustration fails to import (
BLOCK.SVG_TOO_MANY_PARTS): merge shapes of one color into compound paths in the design tool, or add the SVG as an image.
API Reference#
| Method | Category | Purpose |
|---|---|---|
engine.block.createFromSVG(svg) |
Block | Create editable graphic blocks from SVG markup. Returns the group, or the only block |
engine.block.appendChild(parent, child) |
Block | Add the imported block to a page |
engine.block.getType(id) |
Block | Tell a group from a single graphic block |
engine.block.getChildren(id) |
Block | List the shapes of the group in paint order |
engine.block.getShape(id) |
Block | Read the vector_path shape of an imported block |
engine.block.getWidth(id) / getHeight(id) |
Block | Read the size of the imported block and the page |
engine.block.scale(id, scale, anchorX, anchorY) |
Block | Scale a block, its children and their strokes |
engine.block.setPositionX(id, value) / setPositionY(id, value) |
Block | Center the block on the page |
engine.block.getFill(id) |
Block | Read the fill of an imported shape |
engine.block.setColor(id, property, value) |
Block | Change a fill color |
engine.block.setStrokeWidth(id, width) |
Block | Change a stroke width |
engine.block.ungroup(id) |
Block | Dissolve the group into separate blocks |
engine.scene.getDesignUnit() |
Scene | Read the unit that SVG user units map to |
engine.block.export(id, options) |
Block | Export the page to check the result |
Next Steps#
- Combine Shapes to merge or cut imported shapes.
- Grouping to work with the group the import creates.
- Design Units to choose the unit that SVG sizes map to.