@imgly/pdf-importer
v0.6.1
Published
Import PDF files into the Creative Editor Ecosystem
Readme
PDF Importer for the CE.SDK
Overview
The PDF Importer for the CE.SDK allows you to seamlessly integrate PDF files into the editor while retaining essential design attributes.
Here's an overview of the main features:
- File Format Translation: The importer converts PDF files into the CE.SDK scene file format using
pdfjs-dist(Mozilla's pdf.js), in its legacy/CJS-safe build. - Bulk Importing: The codebase is adaptable for bulk importing, streamlining large-scale projects.
- Color Translation: RGB, CMYK, and Separation spot colors from PDFs are translated into CE.SDK's native
RGBAColor,CMYKColor, andSpotColorvariants. CMYK values are preserved end-to-end instead of collapsed to sRGB; Separation inks are registered on the document's spot-color registry (viaengine.editor.setSpotColorCMYK) with their declared alternate CMYK values. DeviceN inks degrade to their alternate-space solid for now.
The following PDF design elements will be preserved by the import:
- Positioning and Rotation: Elements' positioning and rotation are accurately transferred.
- Image Elements: Embedded images (JPEG, PNG) are extracted and placed as graphic blocks. Note that only images with formats that are supported by CE.SDK will be rendered.
- Text Elements: Font family continuity is maintained, with options to supply font URIs or use Google fonts. Bold, italic, and weight styles are supported.
- Vector Paths: SVG path data from the PDF is imported as vector path blocks.
- Colors and Gradients: Solid colors, linear gradients, and radial gradients are faithfully reproduced. A stroke painted with a linear or radial gradient imports as a gradient stroke with CE.SDK 1.85 or later; older versions paint it with the mean color of the gradient and report
PATTERN_PAINT_UNSUPPORTED. - Spot Color Detection: Cut/fold marks using spot colors (CutContour, Thru-cut, etc.) are detected and can be handled separately. Brand spot inks (Separation entries in the page's
/ColorSpaceresource dictionary) are preserved asSpotColorfills and registered on the CE.SDK document-level spot registry. A Separation ink that the PDF only declares, with a path of no size such as0 0 m S, is registered too, so blocks can use it.parse()also adds one invisible, non-selectable block for each such ink, namedPDF ink <ink>and marked with the metadata keyly.img.pdf-importer.inkDeclaration. The block is a stroke of no length in the ink, which paints nothing and which a PDF export writes as the same declaration. Delete it to leave the ink out of the export.loadAsBlocks()adds no such block. - Overprint: Fills, strokes and text in a spot color that overprint in the PDF keep their overprint setting, so a PDF export overprints the same inks. CE.SDK exports overprint only for spot colors, so process colors, images, gradients and pattern fills import as knockout. CE.SDK keeps one overprint setting per text block, so a block whose visible spot-color parts mix overprint and knockout imports as knockout.
- Output Intent:
parse()reads the ICC profile of the PDF output intent (GTS_PDFXfirst, otherwise the first intent) and assigns it to the document's Output slot of the same color space. A CMYK profile also becomes the document's CMYK profile, so CMYK colors convert as the PDF intends. A profile larger than 16 MiB is not used. Requires CE.SDK 1.86 or later; older versions import without the profile and reportOUTPUT_INTENT_ENGINE_UNSUPPORTED. - Image Color: An 8-bit JPEG in DeviceGray, DeviceRGB, DeviceCMYK or ICCBased keeps its original bytes and its PDF color definition: color space, ICC profile,
/Decode, color transform and/Intent. A masked JPEG keeps them only with CE.SDK 1.85 or later and a stencil/Mask, a color-key/Maskor a grayscale JPEG soft mask that is no larger than the image; the mask goes on the definition too. Other images, JPEGs the engine cannot use, and images past 512 MiB of ICC profile data per import keep their decoded pixels (a repeated placement of one image counts once); a rejected definition reportsIMAGE_DEFINITION_FALLBACK, an unusable image profileIMAGE_PROFILE_REFUSED, the data limitIMAGE_PROFILE_BUDGET_EXCEEDED. When pieces of a flattened picture join into one image, the pieces that touch it keep their decoded pixels too, so the picture has one color conversion. Requires CE.SDK 1.84 or later; older versions import every image from its decoded pixels.
How It Works
The importer runs a three-stage pipeline on each PDF page:
- Extract — a
pdfjs-distoperator walker emits drawable blocks (images, vector paths, text outlines) in paint order.page.getTextContent()produces one editable text run per line. - Post-process — reunite text fragments on the same line.
- Emit — write the intermediate representation as CE.SDK blocks, then reconstruct compatible adjacent lines as editable paragraphs when their visible layout can be preserved.
parse() creates a scene in inches (1pt = 1/72 inch). loadAsBlocks({ units: 'scene' }) uses the active scene's design units, DPI, and font-size unit; without an active scene, it uses inch geometry and point font sizes. Omitting units selects the deprecated 'legacy' mode, which retains inch geometry and passes PDF font-size values unchanged to the engine for compatibility. Embedded images become buffer:// URIs; engine-provided fonts use bundle:// URIs.
Installation
You can install @imgly/pdf-importer via npm or yarn. Use the following commands to install the package:
npm install @imgly/pdf-importer
yarn add @imgly/pdf-importerBrowser Quick-Start Example
import CreativeEngine from '@cesdk/engine';
import { PDFParser, addGfontsAssetLibrary } from '@imgly/pdf-importer';
const blob = await fetch('https://example.com/document.pdf').then((res) =>
res.blob()
);
const engine = await CreativeEngine.init({
license: 'YOUR_LICENSE'
});
// We use google fonts to replace well known fonts in the default font resolver.
await addGfontsAssetLibrary(engine);
const parser = await PDFParser.fromFile(engine, blob);
await parser.parse();
const image = await engine.block.export(
engine.block.findByType('//ly.img.ubq/page')[0],
'image/png'
);
const sceneExportUrl = window.URL.createObjectURL(image);
console.log('The imported PDF file looks like:', sceneExportUrl);
// You can now e.g export the scene as archive with engine.scene.saveToArchive()Editable Paragraphs
By default, compatible adjacent PDF lines become one editable text block with
soft wrapping. Text reflows within a fixed inferred column width when you edit
it. The importer detects left, center, and right alignment, retains color and
font-style ranges, and measures line spacing using the active font layout.
It also reconstructs justified paragraphs from regularly spaced word fragments,
including PDFs that paint their words out of reading order. Whole PDF lines
with explicit word spacing can also form justified paragraphs; their original
space offsets are retained through per-range kerning when the engine supports it.
Positive PDF character spacing (Tc) on text in its embedded font is kept the
same way, as per-range kerning.
It replaces ordinary source lines only when every visible line keeps its text
and glyph bounds.
Use textLayout: 'lines' to keep a separate block for each PDF line:
const parser = await PDFParser.fromFile(engine, blob, { textLayout: 'lines' });
await parser.parse();Reconstruction stays conservative. Graphics, paragraph gaps, rotated text,
hyphenated endings, different fonts, and ambiguous word boundaries keep lines separate.
PDFs do not encode the original text frames or paragraph boundaries, so some
paragraphs remain split. Unambiguous solid underline strokes become text
decorations, so the underline follows edits. Other nearby rules and artwork
retain their original elements. Engines without text-decoration support or
usable font underline metrics retain the underline artwork too. The importer
does not synthesize missing font metrics or change the engine's defaults. A
retained underline can also keep its affected paragraph as separate source lines. Endpoint
verification currently supports ASCII word ranges in static fonts without
advanced substitution, positioning, or kerning tables. Other fonts retain
their artwork. Inline color/font runs and ranges with additional character
or word kerning also retain their artwork. Recovered endpoints differ by at most 0.5 PDF point and 0.05 em. Repeated bullet characters become editable
prefixes in separate item paragraphs. Wrapped item text may reflow to the
bullet's left edge, as with a manually typed bullet; hanging indentation is
not inferred. Ambiguous lists retain their original elements. Manual join and
split controls are not part of this package.
Paragraph reconstruction also applies to loadAsBlocks({ units: 'scene' })
when an active scene supplies measurable layout. The deprecated legacy units
mode retains separate lines. Setting maxBlocks also retains lines, so
speculative paragraph blocks cannot exhaust the allocation budget. Combining
separately positioned fragments within one line requires an engine with
getTextCharacterInkBoxes; older engines retain those fragments.
Uniform ASCII paragraphs reuse the flushed line layout. Other paragraph candidates
use at most 512 character-ink queries per reconstruction pass, including
temporary probes; further candidates retain their source lines. Underline
recognition separately limits text/artwork comparisons on each page and
character-ink reads per pass, and reads at most 16 font resources totaling
16 MiB per pass. A page past the comparison limit retains its underline artwork.
Scene-unit imports also preserve group frame bounds for later positioning and
scaling. preservePageBounds: true lets paragraphs use the retained page frame;
otherwise a changed paragraph frame keeps the original lines.
Importing into an Existing Scene
loadAsBlocks() returns detached groups, one per non-empty PDF page, without
replacing the active scene or changing its design units, DPI, or font-size unit.
Create the destination scene before importing and pass units: 'scene' to
convert geometry and text sizes to that scene's units while retaining their
physical size. Attach a returned group before scaling:
const parser = await PDFParser.fromFile(engine, blob);
const { blocks, logger } = await parser.loadAsBlocks({
units: 'scene',
pageIndex: 0,
signal: abortController.signal,
maxBlocks: 10000
});
for (const group of blocks) {
engine.block.appendChild(page, group);
engine.block.scale(group, 0.5);
}signal cancels preparation and emission. maxBlocks limits allocations,
including temporary blocks, shapes, fills, and duplicated descendants. Failed
imports clean up their own blocks and buffers. Changing the active scene or its
units during emission rejects the import. Temporary pages join the scene only
for synchronous layout and clipping operations and are removed before any await.
loadAsBlocks() also returns an idempotent dispose() callback. Call it if you
discard prepared artwork before committing it to your document's undo history.
It destroys the imported groups and releases their unused buffers and spot-color
definitions, while preserving resources referenced by other blocks. Each group
names the spot colors of its page's paths in the metadata keys
ly.img.pdf-importer.spotColor.<ink>, so an ink that a page only declares stays
while its group exists.
By default, group bounds follow the imported artwork after layout. To preserve
the original PDF page whitespace and content origin, pass
preservePageBounds: true to loadAsBlocks(). Each group then retains a
transparent, non-selectable child marked with metadata
ly.img.pdf-importer.pageBounds=true. Keep this child to preserve page whitespace
during layout, scaling, and serialization. Groups do not clip overflowing
content. Empty pages return no group.
Existing spot-color definitions remain unchanged; a conflicting PDF definition
produces a SPOT_COLOR_DEFINITION_PRESERVED warning.
The color profiles of the destination scene also remain unchanged. A PDF output
intent profile is not applied and produces an OUTPUT_INTENT_DROPPED_DETACHED
warning.
Selecting Units
The optional units option accepts 'legacy' or 'scene'. Omitting it is the
same as passing units: 'legacy', so existing calls keep their inch geometry
and pass PDF font-size values unchanged to the engine, regardless of the active
scene's units. For example, a PDF font size of 12 is still passed as 12 when the
scene uses pixel font units. This legacy mode is deprecated; loadAsBlocks()
itself remains supported. Keep any unit conversions your integration already
uses until you explicitly select scene units.
To opt into automatic unit conversion, create the destination scene and pass
units: 'scene'. Then remove the corresponding manual conversions from inches
or font points. Both modes accept the same other options and return
{ blocks, logger, dispose }. Cancellation, allocation limits, disposal, and
preservePageBounds are available in both modes. Neither mode changes the
scene's unit settings.
Both modes return detached groups, not page blocks, and omit empty PDF pages.
If you need to track source page numbers, use getPageCount() and import each
page with loadAsBlocks({ units: 'scene', pageIndex }), handling an empty
blocks array.
Saving Scenes with Stable URLs
By default, embedded images and the output intent profile get internal buffer:// URLs. These are transient resources that work well when saving to an archive (engine.scene.saveToArchive()), which bundles all assets together.
However, if you want to save scenes as JSON strings (engine.scene.saveToString()) with stable, permanent URLs (e.g., for storing in a database or referencing CDN-hosted assets), you need to relocate the transient resources first.
Why Relocate?
- Scene Archives (
saveToArchive): Include all assets in a single ZIP file. Transientbuffer://URLs work fine. - Scene Strings (
saveToString): Only contain references to assets. Transient URLs won't work when reloading the scene later. You need permanent URLs (e.g.,https://).
How to Relocate Transient Resources
After parsing the PDF file, use CE.SDK's native APIs to find and relocate all transient resources:
// 1. Parse the PDF file
const parser = await PDFParser.fromFile(engine, blob);
await parser.parse();
// 2. Find all transient resources (embedded images and the output intent profile)
const transientResources = engine.editor.findAllTransientResources();
// 3. Upload each resource and relocate to permanent URL
for (const resource of transientResources) {
const { URL: bufferUri, size } = resource;
// Extract binary data from the buffer
const data = engine.editor.getBufferData(bufferUri, 0, size);
// Upload to your backend/CDN (implement your own upload logic)
const permanentUrl = await uploadToBackend(data);
// Relocate the resource to the permanent URL
engine.editor.relocateResource(bufferUri, permanentUrl);
}
// 4. Now save to string - all URLs will be permanent
const sceneString = await engine.scene.saveToString();Note on Font URLs
When using addGfontsAssetLibrary() (the default font resolver), the resulting scene string will contain IMG.LY CDN URLs (cdn.img.ly) for fonts. If you need fonts hosted on your own infrastructure, configure a custom font resolver instead of using the default Google Fonts integration.
Font Strategies
The importer ships with three font-handling presets that trade editability against visual fidelity. Pick one via PDFParser.fromFile(engine, blob, { fontStrategy }), or compose your own with createFontStrategy / createFontCascade.
| Preset | Behavior | When to use |
| ----------------------------------- | ------------------------------------------------------------------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| editableFirstStrategy (default) | perfect-match → PDF-embedded subset bytes → any-match substitution | General-purpose import. Prefers asset-library typefaces for editability, falls back to the PDF's embedded subset for fidelity, substitutes when neither is available. |
| exactFidelityStrategy | perfect-match → PDF-embedded subset bytes | Print finalization. Never substitutes; falls through to vector outline when no matching typeface or embedded font is available. |
| assetLibraryStrategy | perfect-match → any-match substitution | Brand-locked tools. Skips the embedded-subset stage so only asset-library typefaces are used; non-matching fonts go through substitution or vector outline. |
import { PDFParser, exactFidelityStrategy } from '@imgly/pdf-importer';
const parser = await PDFParser.fromFile(engine, blob, {
fontStrategy: exactFidelityStrategy
});
await parser.parse();NodeJS Quick-Start Example
Prerequisite — emoji handling. Two CE.SDK settings need attention when running the importer headlessly under
@cesdk/node:
ubq://forceSystemEmojis = false— by default the engine routes any codepoint that ICU classifies asRGI_Emoji(e.g.♥,★, the dingbats block) through the emoji font even when the active typeface has a glyph for it. Customer PDFs frequently embed real text fonts (ZapfDingbats, Webdings, …) that map these codepoints to actual glyphs; forcing the substitution discards the producer's intended glyph and pulls in a generic color emoji. Setting the flag tofalsemakes the engine respect the embedded/substituted font when it covers the codepoint.ubq://defaultEmojiFontFileUri = <CDN URL>—@cesdk/nodeships onlyassets/core/, notassets/emoji/NotoColorEmoji.ttf. Even withforceSystemEmojis=false, true color emoji (🧐, 🎉, …) that no embedded text font covers still need a working emoji font URI, orengine.block.export(page, "image/png")aborts withFILE_FETCH_FAILEDfor the engine's synthesised local-file URL. Point the engine at the IMG.LY-hosted preset, or self-host the file and supply your own URI /bundle://path.engine.editor.setSettingBool('ubq://forceSystemEmojis', false); engine.editor.setSettingString( 'ubq://defaultEmojiFontFileUri', 'https://cdn.img.ly/assets/v4/emoji/NotoColorEmoji.ttf' );See the CE.SDK Emojis guide for the full set of options. Browser consumers initialised with the default IMG.LY-CDN
baseURLalready get the emoji font for free, and most integrations also wantforceSystemEmojis=falsefor the same embedded-font-respect reason.
// index.mjs
import CreativeEngine from '@cesdk/node';
import { promises as fs } from 'fs';
import { PDFParser, addGfontsAssetLibrary } from '@imgly/pdf-importer';
async function main() {
const engine = await CreativeEngine.init({
license: 'YOUR_LICENSE'
});
// Respect embedded fonts for emoji-class codepoints (♥, ★, …) and
// give true color emoji a working font URI — see the prerequisite
// note above.
engine.editor.setSettingBool('ubq://forceSystemEmojis', false);
engine.editor.setSettingString(
'ubq://defaultEmojiFontFileUri',
'https://cdn.img.ly/assets/v4/emoji/NotoColorEmoji.ttf'
);
await addGfontsAssetLibrary(engine);
const pdfBuffer = await fs.readFile('./document.pdf');
const parser = await PDFParser.fromFile(engine, pdfBuffer.buffer);
await parser.parse();
const image = await engine.block.export(
engine.block.findByType('//ly.img.ubq/page')[0],
'image/png'
);
const imageBuffer = await image.arrayBuffer();
await fs.writeFile('./example.png', Buffer.from(imageBuffer));
engine.dispose();
}
main();Issues
If you encounter any issues or have questions, please don't hesitate to contact us at [email protected].
Limitations and Unsupported Features
The PDF importer has some limitations and unsupported features that you should be aware of:
Linked Images
- Only embedded images are supported. External image references are not resolved.
Font Support
- Fonts not available as a typeface asset source fall back through the configured
fontStrategy(see Font Strategies above): embedded subset bytes when present, then resolver substitution, then a vector-outline rendering. The default strategy substitutes; configureexactFidelityStrategyto disable substitution.
- Fonts not available as a typeface asset source fall back through the configured
Complex Vector Paths
- Some complex clipping paths or compound shapes may experience minor distortion.
- Pages with at least 1,000 vector paths combine consecutive, non-overlapping opaque fills with matching colors and clipping into shared vector blocks to reduce memory use. Their component shapes are edited together.
Annotations and Forms
- PDF annotations, form fields, and interactive elements are not imported.
Transparency Groups
- Advanced transparency group blending modes may not be fully reproduced.
Image SMask Compositing
- Per-pixel soft masks (image-modulated luminosity SMasks) are supported and composited into the image as an RGBA PNG. As a consequence, JPEG images carrying an SMask lose the JPEG pass-through optimization — they are decoded and re-encoded as PNG, which increases file size.
Changelog
See CHANGELOG.md for release notes.
License
Use of this package is subject to LICENSE.md.
