Search Docs
Loading...
Skip to content

From PDF

Convert PDF files into CE.SDK scene archives in Node.js, one page per PDF page, for a template library or a conversion pipeline.

8 mins
estimated time
Download
StackBlitz
GitHub

The @imgly/pdf-importer package has two ways to bring in a PDF. parse() replaces the scene with the whole document, one page per PDF page, with the page’s text, vector paths and images as editable blocks. loadAsBlocks() leaves the current scene as it is and returns single pages as groups, which Place PDF Pages in a Design covers. This guide uses parse() in Node.js, where it runs without a user interface, so it fits a build step that turns a folder of PDFs 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 PDF with a headless engine, choose how fonts are matched, 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 PDF importer. The importer has its own version numbers, so we do not pin it to the CE.SDK version.

Terminal window
npm install @cesdk/node@1.87.0 @imgly/pdf-importer dotenv

Using the native Node.js package? Install @cesdk/node-native@1.87.0 instead of @cesdk/node. The engine API is identical.

Convert Your First PDF#

A PDF becomes an archive in a few calls: read the file, register the font library, create a parser on the engine, parse and save.

import CreativeEngine from '@cesdk/node';
import { PDFParser, addGfontsAssetLibrary } from '@imgly/pdf-importer';
import { readFile, writeFile } from 'node:fs/promises';
const engine = await CreativeEngine.init({
license: 'YOUR_CESDK_LICENSE_KEY'
});
await addGfontsAssetLibrary(engine);
const bytes = await readFile('./document.pdf');
const buffer = bytes.buffer.slice(
bytes.byteOffset,
bytes.byteOffset + bytes.byteLength
);
const parser = await PDFParser.fromFile(engine, buffer);
await parser.parse();
const archive = await engine.scene.saveToArchive();
await writeFile('./document.imgly', Buffer.from(await archive.arrayBuffer()));
engine.dispose();

The archive loads in the browser and in Node.js. The sections below add font strategies, warnings, a preview image, stable URLs and batch conversion.

Supported Elements#

The importer keeps these PDF elements:

  • Text: editable text blocks, one per line, with font family, weight and style matched through the font strategy. Neighboring lines with the same font and size become one block
  • Vector paths: shapes, strokes and clipping paths as vector path blocks
  • Images: embedded raster images as graphic blocks, re-encoded as PNG, soft masks included
  • Colors: solid colors, linear and radial gradients. CMYK values stay CMYK, and spot colors are registered on the document
  • Layout: positions, rotation and paint order, with pages sized to the PDF’s trim box

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
});
// Keep glyphs such as ♥ or ★ in the font the PDF embeds, instead of the
// emoji font the engine substitutes by default.
engine.editor.setSetting('forceSystemEmojis', false);
// The importer resolves PDF fonts through the Google Fonts asset library,
// so we register it once for the run.
await addGfontsAssetLibrary(engine);
const outputDirectory = new URL('./output/', import.meta.url);
await mkdir(outputDirectory, { recursive: true });

By default the engine draws every symbol that Unicode lists as a pictograph, such as ♥ or ★, with the emoji font, even when the PDF’s own font has a glyph for it. The forceSystemEmojis setting set to false keeps the PDF’s glyph. The setting applies to every scene the engine loads. See Emojis for the emoji font itself, which the Node.js packages bundle.

The importer resolves PDF fonts through the Google Fonts asset library, so we register it with addGfontsAssetLibrary() once before the first file. The catalog comes from the IMG.LY CDN, so the run needs a network connection.

Choose a Font Strategy#

A PDF embeds a subset of each font it uses, and that font is often not in the asset library. The font strategy decides what the importer does then. Three presets ship with the package:

Strategy Order Use it for
editableFirstStrategy (default) library typeface, then the embedded subset, then a substitute, then vector outlines General import. Text stays editable wherever possible.
exactFidelityStrategy library typeface, then the embedded subset, then vector outlines Print. Nothing is substituted, unmatched text is no longer editable.
assetLibraryStrategy library typeface, then a substitute, then vector outlines Brand-locked tools where only your fonts may appear.
// `editableFirstStrategy`, the default, prefers a typeface from the asset
// library, then the font embedded in the PDF, then a substitute.
// `exactFidelityStrategy` never substitutes and draws unmatched text as
// vector outlines instead.
const fontStrategy = editableFirstStrategy;

Pass the strategy to PDFParser.fromFile() in its options. createFontStrategy() builds your own from the same stages.

Parse the PDF#

parse() replaces the current scene with the document. The scene uses inches as its design unit, because a PDF measures in points, and each page gets the size of the PDF page’s trim box. @cesdk/node exports its own engine class, so the example casts the engine for the importer’s engine type.

// `parse()` replaces the current scene with the PDF, one page per PDF
// page. `@cesdk/node` exports its own engine class, so the importer's
// engine type needs the cast.
const parser = await PDFParser.fromFile(engine as any, buffer, {
fontStrategy
});
const { logger } = await parser.parse();
const pages = engine.scene.getPages();
console.log(`${name}: imported ${pages.length} page(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 or skipped, such as a substituted font or an unsupported blend mode. 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 logger.getMessages()) {
if (message.type !== 'info') {
console.warn(` [${message.code}] ${message.message}`);
}
}

Save as Archive#

An archive bundles the scene with the images and fonts the importer extracted from the PDF. 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 and fonts the importer
// extracted from the PDF. 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 extracted images and embedded fonts 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 extracted images and embedded fonts 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, embedded fonts included.
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
// resources 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, embedded fonts included. 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. Fonts from the Google Fonts library point to the IMG.LY CDN. To serve fonts from your own host, register your own typeface asset source and a font resolver that finds them.

Convert the Sample Document#

The example downloads a sample PDF 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 convertDocument(await response.arrayBuffer(), 'postcard');
} catch (error) {
// Without network access, the files in ./input still convert.
console.error(`Sample: ${(error as Error).message}`);
}

Convert a Directory#

Every .pdf 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 PDF 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 PDF files there to convert them.');
}
for (const fileName of inputFiles) {
if (extname(fileName).toLowerCase() !== '.pdf') continue;
const bytes = await readFile(new URL(fileName, inputDirectory));
const buffer = bytes.buffer.slice(
bytes.byteOffset,
bytes.byteOffset + bytes.byteLength
);
try {
// The prefix keeps ./input/postcard.pdf from overwriting the sample.
const name = `input-${basename(fileName, extname(fileName))}`;
await convertDocument(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:

Terminal window
npx tsx server-js.ts

API Reference#

API Description
PDFParser.fromFile(engine, file, options?) Creates a parser from a Blob, File or ArrayBuffer. Options: fontStrategy, fontResolver, pageBounds ('trim', the default, sizes the page to the TrimBox; 'media' keeps the page’s visible size, the CropBox, and does not shift the content) and preserveWhitePageBackground.
parser.parse() Replaces the scene with the document, one page per PDF page. Returns { scene, logger }.
parser.getPageCount() The number of pages. Parses the file once; later calls reuse the result.
parser.loadAsBlocks(options) Returns single pages as groups without replacing the scene. See Place PDF Pages in a Design.
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. Call it before the first parse.
editableFirstStrategy, exactFidelityStrategy, assetLibraryStrategy The three font strategy presets.
createFontStrategy({ cascade, emission }) Builds a custom font strategy.

Limitations#

  • Linked images are not resolved. Only embedded images import.
  • Annotations, form fields and other interactive elements are not imported.
  • Transparency groups with advanced blend modes may not render the same.
  • Complex clipping paths and compound shapes may show minor distortion.
  • Pages with 1,000 or more vector paths combine neighboring opaque fills of the same color into shared vector blocks, to save memory. Those shapes are edited together.
  • Every image is stored as PNG, so an archive of a photo-heavy PDF is larger than the PDF.

These are the highlights. The @imgly/pdf-importer page on npm keeps the complete list of supported features and limitations.

Troubleshooting#

  • Text uses a different font: the font is not in the asset library, and the PDF embeds no usable subset of it, so the importer substituted it. The logger reports FONT_SUBSTITUTIONS. Register your own typeface source with the font, or use exactFidelityStrategy to get vector outlines instead of a substitute.
  • Text is not editable: the strategy fell through to vector outlines, because no typeface matched and the PDF embeds no usable font for it.
  • An image is missing: the PDF links to it instead of embedding it. Embed the image in the PDF.
  • The run stops with an out-of-memory error on a large PDF: @cesdk/node runs the engine in WebAssembly with its own memory ceiling, which --max-old-space-size does not raise. @cesdk/node-native uses the process memory. Convert a large file in a process of its own.

Next Steps#