Copy and paste text with its colors, weights, decorations and lists, between text blocks and from other apps.
Text blocks read and write their formatted content as HTML. engine.block.getTextAsHTML() returns a range of a text block as HTML with inline CSS. The HTML states the color, background color, weight, italic, decorations, script style, case, font size, letter spacing and typeface of each run. It also states the list style, list level, alignment and line height of each paragraph. engine.block.replaceTextWithHTML() replaces a range with the text and formatting of HTML. On a server, use them to move formatted text between blocks and scenes, or to insert rich text that your app received as HTML.
This guide covers copying formatted text between blocks, inserting HTML from other apps, handling HTML without text, and exporting the result.
Initialize the Engine#
We initialize the headless engine. The license line stays commented out, so the engine runs in evaluation mode.
// Initialize the headless Creative Engineconst engine = await CreativeEngine.init({ baseURL: process.env.IMGLY_LOCAL_ASSETS_URL // license: process.env.CESDK_LICENSE});Create the Text Blocks#
We create text blocks that use a typeface with bold and italic fonts, and we format ranges of the first block. The ranges are UTF-16 indices [from, to).
// Create text blocks that use a typeface with bold and italic fontsconst createTextBlock = (y: number): DesignBlockId => { const block = engine.block.create('text'); engine.block.appendChild(page, block); engine.block.setPositionX(block, 50); engine.block.setPositionY(block, y); engine.block.setWidth(block, 700); engine.block.setHeightMode(block, 'Auto'); engine.block.setFont( block, ROBOTO_TYPEFACE.fonts[0].uri, ROBOTO_TYPEFACE ); engine.block.setTextFontSize(block, 36, { unit: 'Pixel' }); return block;};const source = createTextBlock(40);const copy = createTextBlock(140);const pasted = createTextBlock(240);
// Format ranges of the source block, using UTF-16 indicesengine.block.replaceText(source, 'Bold, italic and red text');engine.block.setTextFontWeight(source, 'bold', 0, 4);engine.block.setTextFontStyle(source, 'italic', 6, 12);engine.block.setTextColor(source, { r: 1, g: 0, b: 0, a: 1 }, 17, 20);engine.block.toggleTextDecorationUnderline(source, 21, 25);Copy Formatted Text Between Blocks#
We read the source block as HTML with engine.block.getTextAsHTML() and write it to the second block with engine.block.replaceTextWithHTML(). HTML from getTextAsHTML() sets every format it carries, the typeface and the font size included. The typeface applies only when a typeface of the scene holds its font file. Otherwise the text keeps the typeface at the insert position, with the weight and style of the source. Without a range, both calls use the whole text.
// Read the whole source block as HTML and replace the text of the copy.// HTML from getTextAsHTML() restores every format, typeface and font size included.const html = engine.block.getTextAsHTML(source);engine.block.replaceTextWithHTML(copy, html);console.log('HTML of the source block:', html);Copy a Range#
We pass from and to to copy a part of a block. To insert without replacing text, we pass the same index twice, here the length of the text. An empty range returns an empty string.
// Copy only " red" and insert it at the end of the copy.// The same index for `from` and `to` inserts without replacing.const redHtml = engine.block.getTextAsHTML(source, 16, 20);const end = engine.block.getString(copy, 'text/text').length;engine.block.replaceTextWithHTML(copy, redHtml, end, end);Insert HTML From Other Apps#
We pass HTML from any source to engine.block.replaceTextWithHTML(). HTML from apps such as Google Docs, Word, a web page or an Apple app sets weight, italic, decorations, script style and case. It also sets the text color, background color, font size, letter spacing, line height, lists and alignment. Markup that is not supported keeps only its text.
// HTML from another app sets weight, italic, decorations, colors, lists, the font size,// the letter spacing and the line height. Its font family applies when a typeface of the// asset sources has that family. Otherwise the text keeps the typeface of the block.engine.block.replaceTextWithHTML( pasted, '<p style="line-height:1.5"><b style="font-size:24px">Bold</b> and ' + '<span style="color:#ff0000">red</span></p><ul><li>item</li></ul>');console.log('Pasted text:', engine.block.getString(pasted, 'text/text'));The inserted text takes the first font family of the HTML that a typeface of the asset sources has. Without such a typeface, it keeps the typeface of the block. A CSS px is one pixel of a scene whose font size unit is the pixel, so the size reads as in the source app. A gray, black or white that covers the largest part of the inserted text is the default color of the source app. It does not replace the color of the block, and the same rule applies to the background color. An inserted paragraph without a list keeps the list of the target paragraph.
Insert Plain Text in the Style of the Block#
To insert text as Paste and Match Style does in an editor, pass the plain text to engine.block.replaceText(). The text takes the style at the insert position.
Handle HTML Without Text#
When the HTML holds no text, replaceTextWithHTML() throws an engine error with the code BLOCK.TEXT_HTML_HAS_NO_TEXT and changes nothing. We read the code of the error and insert the plain text with engine.block.replaceText() instead. Other errors are thrown again. The Error Catalog lists every error code.
// HTML without text, such as a copied image, makes the engine throw and// change nothing, so insert the plain text instead. @cesdk/node exports// no isEngineError() helper, so read the `code` of the error.const pasteHTMLOrText = ( block: DesignBlockId, htmlToPaste: string, plainText: string): void => { try { engine.block.replaceTextWithHTML(block, htmlToPaste); } catch (error) { const { code } = error as { code?: string }; if (code === 'BLOCK.TEXT_HTML_HAS_NO_TEXT') { engine.block.replaceText(block, plainText); } else { throw error; } }};
const fallback = createTextBlock(400);pasteHTMLOrText( fallback, '<p><img src="https://img.ly/static/ubq_samples/sample_1.jpg"></p>', 'Plain text instead of an image');Export the Result#
We export the page to a PNG file to check the formatting.
// Export the page to PNGconst blob = await engine.block.export(page, { mimeType: 'image/png' });const buffer = Buffer.from(await blob.arrayBuffer());if (!existsSync('output')) { mkdirSync('output');}writeFileSync('output/text-copy-paste.png', buffer);console.log('Exported the page to output/text-copy-paste.png');Clean Up#
We dispose of the engine in a finally block, so its resources are freed also when a step fails.
// Always dispose of the engine to free resourcesengine.dispose();Scopes#
Without the text/character scope, replaceTextWithHTML() inserts only the text, with the style at the insert position. Without the fill/change scope, or when the text color is bound to a variable, no color is applied. When the font size or the typeface of the block is bound to a variable, it is not applied. See Lock Design to set scopes.
API Reference#
| Method | Purpose |
|---|---|
engine.block.getTextAsHTML() |
Get a UTF-16 range of a text block as HTML with its formatting |
engine.block.replaceTextWithHTML() |
Replace a range with the text and formatting of HTML |
engine.block.replaceText() |
Insert plain text, for HTML without text |
engine.block.getString() |
Read the plain text with 'text/text', for example to find the end index |
Troubleshooting#
Inserted text has a different typeface than in the source app: No typeface of the asset sources has the font family of the source app, so the text keeps the typeface of the block. Add that typeface to an asset source. See Text Styling.
Inserted text is much smaller or larger than the block: The insert keeps the font size of the source app. Insert the plain text with engine.block.replaceText() to keep the style of the block.
Bold or italic text does not show: The typeface of the block has no bold or italic font. Use a typeface that has these fonts.
The insert throws an error: The HTML holds no text, and the error code is BLOCK.TEXT_HTML_HAS_NO_TEXT. Insert the plain text instead.
The text color of the HTML is not used: A gray, black or white that covers the largest part of the inserted text does not change the color of the block. The same rule applies to the background color. Other colors are used, unless the block does not allow the fill/change scope or its text color is bound to a variable.
Next Steps#
- Edit Text: replace, remove and format text with range-based APIs.
- Text Decorations: add underline, strikethrough and overline to text ranges.