Convert PowerPoint presentations into CE.SDK scene archives in Node.js, one page per slide, for a template library or a conversion pipeline.
The @imgly/pptx-importer package converts a .pptx file into CE.SDK blocks: one page per slide, with the slide’s text, shapes and images as editable blocks. In Node.js it runs without a user interface, so it fits a build step that turns a folder of presentations into templates, or a server that converts uploads before the editor opens them. For imports in the editor, see the browser guide.
This guide covers how to parse a presentation with a headless engine, read the importer’s warnings, write an archive, a preview image and a scene string with stable URLs, and convert a whole directory.
Install the Packages#
Install the Node.js SDK and the PowerPoint importer. The importer has its own version numbers, so we do not pin it to the CE.SDK version.
npm install @cesdk/node@1.87.0 @imgly/pptx-importer dotenvUsing the native Node.js package? Install @cesdk/node-native@1.87.0 instead of @cesdk/node. The engine API is identical.
Convert Your First Presentation#
A presentation becomes an archive in a few calls: read the file, create a parser on the engine, parse and save.
import CreativeEngine from '@cesdk/node';import { PPTXParser } from '@imgly/pptx-importer';import { readFile, writeFile } from 'node:fs/promises';
const engine = await CreativeEngine.init({ license: 'YOUR_CESDK_LICENSE_KEY'});
const bytes = await readFile('./presentation.pptx');const buffer = bytes.buffer.slice( bytes.byteOffset, bytes.byteOffset + bytes.byteLength);
const parser = await PPTXParser.fromFile(engine, buffer);await parser.parse();
const archive = await engine.scene.saveToArchive();await writeFile('./presentation.imgly', Buffer.from(await archive.arrayBuffer()));
engine.dispose();The archive loads in the browser and in Node.js. The sections below add warnings, a preview image, stable URLs and batch conversion.
Supported Elements#
The importer keeps these slide elements:
- Text: font family, size and color, bold and italic, character spacing, line height, several runs with different formatting in one block, vertical alignment
- Shapes: rectangles with corner radius, ellipses, custom shapes as vector paths, solid and theme-color fills, strokes
- Images: embedded PNG, JPEG, GIF, BMP and WebP images, with their size and position
- Backgrounds: solid colors, linear or radial gradients, and images
- Layout: absolute positions, rotation, z-order, groups, and the decorative elements a slide inherits from its layout and master
Path and rectangular gradients import as radial gradients, and inner shadows as outer shadows. Both log a warning. Bullets and numbering import with basic formatting.
Initialize the Engine#
We load the environment, create one headless engine for the whole run and create the output directory.
config();const engine = await CreativeEngine.init({ // license: process.env.CESDK_LICENSE, baseURL: process.env.IMGLY_LOCAL_ASSETS_URL});
// The importer matches slide fonts against the Google Fonts asset library.// `PPTXParser.fromFile()` registers it on the first import; registering it// here makes a failed fetch stop the run before the first file.await addGfontsAssetLibrary(engine);
const outputDirectory = new URL('./output/', import.meta.url);await mkdir(outputDirectory, { recursive: true });The importer matches each slide font against the Google Fonts catalog, which PPTXParser.fromFile() registers on the engine the first time it runs. We register it with addGfontsAssetLibrary() before the first file, so a failed fetch stops the run at startup instead of in the first conversion. The catalog comes from the IMG.LY CDN, so the run needs a network connection.
Parse the Presentation#
parse() adds pages to the current scene, so each conversion starts with a new scene. The importer sets the scene to 96 DPI, the resolution PowerPoint uses for its pixel sizes, and places each slide on a page of the slide’s size. @cesdk/node exports its own engine class, so the example casts the engine for the importer’s engine type.
// `parse()` adds the slides to the current scene, so each presentation// starts a new one. The importer sets the scene to 96 DPI, the// resolution of PowerPoint's own pixel sizes. `@cesdk/node` exports its// own engine class, so the importer's engine type needs the cast.engine.scene.create('VerticalStack');const parser = await PPTXParser.fromFile(engine as any, buffer);const result = await parser.parse();const pages = engine.scene.getPages();console.log(`${name}: imported ${pages.length} slide(s)`);Check Import Warnings#
The result carries a logger. Each message has a stable code, a type of info, warning or error, and a readable message. Warnings name what the importer changed, such as a substituted font or a gradient type it replaced. In a pipeline, store them next to the converted file so a reviewer sees what to check.
// Each message has a stable `code`, a `type` and a readable `message`.for (const message of result.logger.getMessages()) { if (message.type !== 'info') { console.warn(` [${message.code}] ${message.message}`); }}Save as Archive#
An archive bundles the scene with the images the importer extracted from the presentation. We write it with the .imgly extension, which the engine opens as an archive or a scene string.
// The archive bundles the scene with the images the importer extracted// from the presentation. It loads in the browser and in Node.js.const archive = await engine.scene.saveToArchive();await writeFile( new URL(`${name}.imgly`, outputDirectory), Buffer.from(await archive.arrayBuffer()));Export a Preview#
A PNG of the first page serves as the thumbnail of the converted template.
const png = await engine.block.export(pages[0], { mimeType: 'image/png' });await writeFile( new URL(`${name}.png`, outputDirectory), Buffer.from(await png.arrayBuffer()));Save Scenes with Stable URLs#
The importer stores slide images under transient buffer:// URIs. An archive keeps them, but a scene string from engine.scene.saveToString() only references them, and the references break when the scene is loaded again. To store a scene string, upload each buffer first and point the scene at the uploaded file.
// Optional: save the scene as a string with stable URLs instead.// The importer stores slide images under transient `buffer://` URIs,// which only an archive keeps. For `saveToString()`, upload each buffer// first and point the scene at the uploaded file.
// Replace with the upload to your storage. Here a file next to the scene// stands in for the permanent URL. The data is a view into the engine's// memory, so copy it before the asynchronous write.const uploadToBackend = async (data: Uint8Array, index: number) => { const fileURL = new URL(`${name}-resource-${index}`, outputDirectory); await writeFile(fileURL, Buffer.from(data)); return fileURL.href;};
// The list holds every transient resource, so keep only the importer's// `buffer://` URIs, the slide images.const resources = engine.editor.findAllTransientResources();for (const [index, resource] of resources.entries()) { const { URL: bufferUri, size } = resource; if (!bufferUri.startsWith('buffer://')) continue; const data = engine.editor.getBufferData(bufferUri, 0, size); const permanentUrl = await uploadToBackend(data, index); engine.editor.relocateResource(bufferUri, permanentUrl); // Relocating does not free the buffer, so a batch would keep the // images of every converted file in memory. engine.editor.destroyBuffer(bufferUri);}const sceneString = await engine.scene.saveToString();await writeFile(new URL(`${name}.scene`, outputDirectory), sceneString);findAllTransientResources() lists every transient resource, so the loop keeps only the importer’s buffer:// URIs, the slide images. getBufferData() reads one, and relocateResource() replaces the URI in every block that uses it. Relocating does not free the buffer, so destroyBuffer() releases it, otherwise a batch keeps the resources of every converted file in memory. The example writes each resource next to the scene and uses its file URL. In production, upload the data to your storage and use the public URL. The Google Fonts in the scene string point to the IMG.LY CDN. To serve fonts from your own host, register typeface asset sources under both ids, ly.img.gfonts and ly.img.gfonts-fallbacks, before the first import: the importer skips a source that already exists, and its resolver needs both.
Convert the Sample Presentation#
The example downloads a sample presentation and converts it, so the script runs without input files. When the download fails, the script logs the error and still converts the files in ./input.
try { const response = await fetch(SAMPLE_URL); if (!response.ok) throw new Error(`Could not download ${SAMPLE_URL}`); await convertPresentation(await response.arrayBuffer(), 'example-3-social');} catch (error) { // Without network access, the files in ./input still convert. console.error(`Sample: ${(error as Error).message}`);}Convert a Directory#
Every .pptx file in ./input goes through the same function. One engine serves the whole batch, and an error in one file is logged and does not stop the others. The outputs of these files start with input-, so a file with the sample’s name does not overwrite it.
// Convert every presentation in ./input, if the directory exists.const inputDirectory = new URL('./input/', import.meta.url);let inputFiles: string[] = [];try { inputFiles = await readdir(inputDirectory);} catch { console.log('No ./input directory. Put PPTX files there to convert them.');}for (const fileName of inputFiles) { if (extname(fileName).toLowerCase() !== '.pptx') continue; const bytes = await readFile(new URL(fileName, inputDirectory)); const buffer = bytes.buffer.slice( bytes.byteOffset, bytes.byteOffset + bytes.byteLength ); try { // The prefix keeps an input file from overwriting the sample's output. const name = `input-${basename(fileName, extname(fileName))}`; await convertPresentation(buffer, name); } catch (error) { // One broken file does not stop the batch. console.error(`${fileName}: ${(error as Error).message}`); }}Clean Up#
Dispose the engine when the run ends, also when a conversion threw.
engine.dispose();Run the script with tsx:
npx tsx server-js.tsAPI Reference#
| API | Description |
|---|---|
PPTXParser.fromFile(engine, buffer, options?) |
Reads the presentation and registers the Google Fonts asset sources. Throws for a file that is not a .pptx or has no slides. |
parser.parse() |
Adds one page per slide to the current scene. Returns { logger }. |
parser.getSlideCount() |
The number of slides in the file. |
result.logger.getMessages() |
The import messages, each with code, type and message. |
addGfontsAssetLibrary(engine) |
Registers the Google Fonts catalog and the proprietary-font aliases as asset sources. |
options.applyFontMetricsCorrection |
Default true. Moves top-aligned text blocks so the first baseline sits where PowerPoint puts it. |
options.autoCorrectTextOverflow |
Default true. Reduces the letter spacing of a text block that overflows its frame. |
Limitations#
- Tables, charts and SmartArt are dropped without a warning, so check the deck for them. Ungroup a table in PowerPoint before you save the file, so it imports as shapes and text.
- Animations, transitions, audio, video, comments and notes are not imported.
- Text keeps its basic formatting. Bullets and numbering import with basic formatting only.
These are the highlights. The @imgly/pptx-importer page on npm keeps the complete list of supported features and limitations.
Troubleshooting#
fromFile()throws “Failed to parse PPTX file”: the file is not a ZIP, so not a.pptx. Older.pptfiles are not supported. Open the file in PowerPoint and save it as.pptx.fromFile()throws “PPTX file missing presentation.xml”: the file is a ZIP but not a presentation, such as a.docx.addGfontsAssetLibrary()rejects with a network error: the Google Fonts catalog could not be fetched from the IMG.LY CDN. Without the startup call,fromFile()reports the same error on the first import. The run needs a network connection, or your own typeface sources under the idsly.img.gfontsandly.img.gfonts-fallbacks.- Text uses a different font: the font is not in the Google Fonts catalog and was substituted. The logger reports it as
FONT_NOT_FOUND. Register your own typeface sources, as described under stable URLs, to supply the font. - The run stops with an out-of-memory error on a large presentation:
@cesdk/noderuns the engine in WebAssembly with its own memory ceiling, which--max-old-space-sizedoes not raise.@cesdk/node-nativeuses the process memory. Convert a large file in a process of its own. - The slides appear after the pages of the previous file:
parse()adds to the current scene. Create a new scene before each file.
Next Steps#
- From PowerPoint in the browser imports presentations in the editor.
- PowerPoint Template Import is a complete app around this importer.
- From Photoshop and From InDesign convert other design files the same way.