Pictures and embedded objectsDocument
Which picture formats Birch UI Document Editor reads, shows and writes in DOCX, how EMF and WMF metafiles are drawn, and how embedded Excel, Word, PowerPoint, PDF and other files are opened, downloaded and inserted.
Picture formats#
A picture in a DOCX file is read with its original bytes, and those bytes are what an export writes, whatever the editor shows on screen.
| Format | Imported | Shown in the editor | Exported |
|---|---|---|---|
| PNG, JPEG, GIF, WebP, BMP | original bytes | by the browser | the same bytes |
| TIFF | original bytes | only in browsers that draw TIFF (Safari); a blank frame elsewhere | the same bytes |
SVG with a PNG fallback (asvg:svgBlip) |
the fallback as the picture, the SVG part kept | the fallback | both parts and the reference |
| SVG inserted in the editor | — | by the browser | the picture with an asvg:svgBlip extension |
| EMF, WMF | original bytes | drawn as SVG by the editor | the same bytes |
test/docx-images.test.ts checks every row: the bytes in the model equal the part, and the part of the export equals the original, both when the block is kept and when it is rebuilt.
EMF and WMF#
Browsers do not draw Windows metafiles. The editor reads the records and draws them as SVG; the metafile stays in the document and is written back unchanged. HTML export uses the drawing, so the page it produces shows the picture.
import { metafileToSvg } from '@birchui/document';
const svg = metafileToSvg(bytes); // an SVG document, or null when the bytes are not a metafile or draw nothing| Records that are drawn | |
|---|---|
| WMF | window origin and extent, placeable header; MoveTo, LineTo, Polyline, Polygon, PolyPolygon, Rectangle, RoundRect, Ellipse, Arc, Pie, Chord; TextOut, ExtTextOut; pens, brushes and fonts with SelectObject and DeleteObject; text colour, background mode, polygon fill mode, text alignment; StretchDIBits and DIBStretchBlt bitmaps; SaveDC, RestoreDC; an enhanced metafile carried in comment records is preferred |
| EMF | bounds and frame; window and viewport origin and extent; MoveToEx, LineTo, Polyline, Polygon, PolyPolygon, PolyBezier, PolyBezierTo, PolylineTo with 16-bit and 32-bit points; Rectangle, RoundRect, Ellipse; paths with BeginPath, EndPath, CloseFigure, FillPath, StrokePath, StrokeAndFillPath; CreatePen, ExtCreatePen, CreateBrushIndirect, ExtCreateFontIndirectW, stock objects; ExtTextOutW; SetWorldTransform, ModifyWorldTransform; StretchDIBits and BitBlt bitmaps; SaveDC, RestoreDC |
Other records are skipped. Clipping regions, gradient and hatched or patterned fills, opaque text backgrounds, RLE-compressed bitmaps and EMF+ (GDI+) records are not drawn, and raster operations other than copying are approximated with blend modes, so a metafile that relies on them looks different from Word. A file that is truncated or damaged gives null, never an exception; the picture then shows as a frame, the import reports a warning, and the bytes are still exported.
scripts/docx-metafiles.py lets LibreOffice convert a chart to EMF and WMF and builds lo-metafile-pictures.docx from them. The tests draw both files and check the bars, the curve, the outline and the labels of the chart in the SVG.
Embedded objects#
A Word file can carry other files: a workbook, a presentation, another document, a PDF, an Outlook message, any file. On import each of them becomes an embedded_object node with:
| Attribute | Content |
|---|---|
fileName, mimeType, progId |
the name and type of the file and the ProgID of the object (Excel.Sheet.12, Word.Document.12, PowerPoint.Show.12, Package, AcroExch.Document.DC and others) |
data |
the bytes of the file, base64. For an Office file this is the embedded package; for a Package object it is the file taken out of the Ole10Native stream of the compound file; for a PDF object it is the CONTENTS stream |
icon |
the preview or icon picture the file stores, as a data URL (a metafile is drawn as SVG for display); null for an object without a picture of its own, which is shown with the icon of its file type |
asIcon, width, height |
how it is shown |
What an object looks like#
Every object shows what kind of file it is:
- An object without a picture of its own is drawn as the icon of its file type with a short badge (DOCX, XLSX, PPTX, PDF, MSG and so on) and the file name under it, on one or two lines. A long name is shortened in the middle so that the extension stays visible.
- An object with a preview or icon stored in the document shows that picture at its size, with the badge of the file type on its lower left corner. If the picture cannot be drawn, the icon of the type takes its place in the same box.
The tooltip gives the name, the type and the size, and the accessible name reads like "Embedded PDF document: Q3-report.pdf". The same icon, name, type and size head the toolbar of a selected object and its context menu, and Properties lists the name, type, size, content type and object class. Print, the PDF export of the editor (as vector shapes and text) and the exports made without a browser (documentToPdf, documentToHtml, ODT) draw the icon and the name too.
| Type | Badge examples | Recognised from |
|---|---|---|
| Word document | DOCX, DOCM, DOC, RTF, ODT | Word.Document.*, extension, package content types, the WordDocument stream |
| Excel workbook | XLSX, XLSM, XLSB, XLS, ODS | Excel.Sheet.*, extension, package content types, the Workbook stream |
| PowerPoint presentation | PPTX, PPTM, PPT, ODP | PowerPoint.Show.*, extension, package content types, the PowerPoint Document stream |
| PDF document | AcroExch.*, Acrobat.*, Foxit*, extension, %PDF |
|
| Outlook message, e-mail | MSG, EML | Outlook.*, extension, the property stream of a message, mail headers |
| Image | PNG, JPG, GIF, BMP, WEBP, TIFF, SVG, EMF, WMF | extension, signature |
| Text and CSV | TXT, CSV, TSV, JSON, XML, HTML | extension, text without control characters; CSV when the lines have the same number of separators |
| Archive | ZIP, 7Z, RAR, GZ | extension, signature |
| Audio and video | MP3, WAV, OGG, FLAC, M4A, MP4, MOV, AVI, WEBM | extension, signature |
| File | the extension, or FILE | everything else |
The type is decided from, in this order: the ProgID of the object, the file name (the name in the Ole10Native stream of a packaged file), the content type and the extension of the part, and last the leading bytes. A ZIP file is opened far enough to read [Content_Types].xml, so a macro-enabled workbook or a template is told apart from a plain one. The icons are drawings of this package; they are not the icons of the applications.
import { detectFileType, embeddedObjectType, fileIconSvg, fileTypeLabel } from '@birchui/document';
const type = detectFileType({ progId: 'Package', fileName: 'oleObject1.bin', data: bytes });
type.kind; // 'word' | 'excel' | 'powerpoint' | 'pdf' | 'email' | 'image' | 'text' | 'archive' | 'media' | 'file'
type.badge; // 'PDF'
type.source; // 'progId' | 'fileName' | 'contentType' | 'content' | 'none'
fileTypeLabel(type.label); // 'PDF document'
fileIconSvg(type, { width: 32, height: 40 }); // an SVG document
const [node] = editor.getJSON().content.content?.[0].content ?? [];
embeddedObjectType(node?.attrs); // the same for an embedded_object node
editor.getEmbeddedObjects()[0].kind; // 'pdf'Select an object with a click or with Shift and an arrow key, and a small toolbar offers Open, Download and Properties; Enter moves into the toolbar, the arrow keys move between the buttons and Escape returns to the text. A right click selects the object and adds the same three entries to the context menu. They also work in a read-only document. A double click opens.
A file whose name has no extension, or the extension .bin, is opened and downloaded with the extension and the content type of what it holds: a packaged PDF named oleObject1.bin is downloaded as oleObject1.pdf with application/pdf.
The editor does not open the file itself. Open emits embeddedObjectOpen with the bytes, and your application decides what to do with them:
function openInHost(kind: 'workbook' | 'pdf' | 'other', data: Uint8Array, fileName: string): void {
window.parent.postMessage({ kind, fileName, data }, location.origin);
}
editor.on('embeddedObjectOpen', ({ fileName, mimeType, progId, data }) => {
if (progId.startsWith('Excel.') || fileName.endsWith('.xlsx')) openInHost('workbook', data, fileName);
else if (mimeType === 'application/pdf') openInHost('pdf', data, fileName);
else openInHost('other', data, fileName);
});
editor.getEmbeddedObjects(); // [{ pos, fileName, mimeType, progId, data, asIcon, kind }]
editor.openEmbeddedObject(); // the selected one, or pass a position
editor.downloadEmbeddedObject();openInHost stands for your own code: hand an .xlsx to a spreadsheet component and a PDF to a viewer.
Inserting a file#
Object on the Insert tab (ribbon control id embedFile, key tip J) opens the file picker of the browser. A dialog then shows the icon, the name, the type and the size of the chosen file, and Insert embeds it at the cursor. The button is disabled in a read-only document. From code, without the dialog:
const file = fileInput.files![0];
editor.insertEmbeddedObject({
data: await file.arrayBuffer(),
fileName: file.name,
mimeType: file.type,
asIcon: true,
});On export the object is written the way Word writes it:
- an
.xlsx,.docxor.pptxfile is stored as a package part (word/embeddings/Microsoft_Excel_Worksheet1.xlsx) with the ProgID of its application and apackagerelationship; - any other file is wrapped in an OLE compound file with an
Ole10Nativestream and aCompObjstream, stored asword/embeddings/oleObject1.binwith the ProgIDPackageand anoleObjectrelationship; - the paragraph gets a
w:objectwith av:shape, the picture asv:imagedataand ano:OLEObject. For an object without a picture of its own the editor writes a PNG of the icon of the file type with the badge and the file name (208 × 168 pixels, shown at 104 × 84), so Word and LibreOffice show an icon too. When such a file is read again the picture is recognised and the object is drawn with the sharp icon of the editor; - the same file embedded twice is stored once.
An object that is not edited is written back with its original XML and its original part.
What was checked, and with what#
| Check | Tool | Result |
|---|---|---|
A document with a workbook, a Word file, a presentation, a PDF and an Outlook message inserted through embeddedObjectNode validates |
validateDocxPackage |
no errors |
| The embeddings exist with the right content types and relationships | python-docx 1.2 | Microsoft_Excel_Worksheet1.xlsx, Microsoft_Word_Document1.docx and Microsoft_PowerPoint_Presentation1.pptx (package), oleObject1.bin and oleObject2.bin (oleObject), five icon pictures |
| The file opens and the objects are there | LibreOffice, converted to ODT and to PDF | the ODT holds the five files (Obj100 to Obj104, byte-identical to the packages that went in; the workbook and the Word file are also converted to Object 1 and Object 2) with their replacement pictures; the PDF has one page with the five icons |
One object of each of the twenty files in test/fixtures/docx/embedded-types (written by scripts/docx-embedded-types.py), inserted and exported |
LibreOffice, converted to PDF; python-docx 1.2 | the PDF draws twenty icons with badge and file name; python-docx finds twenty embeddings, twenty PNG pictures of 208 × 168 pixels and the ProgIDs Excel.Sheet.12, Word.Document.12, PowerPoint.Show.12 and Package |
| The type of each of those files is found from the bytes alone, from the name, and from the ProgID | test/docx-file-type.test.ts, document-embed-object.spec.ts in Chrome and Firefox |
as listed in the table above |
The two oleObject parts are compound files with CompObj and Ole10Native streams and the Package class id, in the export and in the ODT LibreOffice wrote |
olefile | as expected |
| An SVG picture inserted in the editor and the metafile fixture, exported and converted to PDF | LibreOffice | the pictures are drawn |
| Reading the export again gives the same bytes, names and types | the reader of this package | identical |
Files that come with objects (py-embedded-objects.docx, py-embedded-files.docx) are written back with identical document.xml, relationships and embeddings |
package tests | identical |
The exports have not been opened in Microsoft Word.
Limits#
- An object is not edited in place and is not drawn live: the picture is the one stored in the file, or the icon.
- A linked object (
Type="Link") is not read as a file. It stays a preserved drawing with its picture and is written back as it was. - An object whose embedding part is missing stays a preserved drawing. A compound file that cannot be read is offered as it is, as a
.binfile. - PDF export without a browser (
documentToPdf) leaves out metafiles and SVG pictures; it draws PNG and JPEG only. An embedded object is drawn with its PNG or JPEG preview, and otherwise with the icon of its type. PDF export from the editor draws what is on screen. - The file name inside the PNG that is written for Word and LibreOffice is drawn with a built-in 5 × 7 pixel font that covers printable ASCII. The package ships no glyph outlines (PDF export uses the standard fonts or the fonts you pass), so a name with other letters is written in Latin letters first: accents are dropped (
GrößebecomesGrosse), Cyrillic and Greek are transliterated (ОтчётbecomesOtchet), and a run of characters without a Latin form, such as Chinese or Arabic, becomes one hyphen or is left out; a name of nothing else becomesfile. On screen, in print and in the PDF export the name is the real text. - The badge of the file type is laid over the lower left corner of a preview picture; it covers that corner.
briefing.pptamong the fixtures is only a compound file with the stream names of a presentation; the other fixtures are real files.- An SVG picture that came with a PNG fallback loses its SVG part when the picture is edited (resized, cropped); the fallback stays.
datais part of the document JSON, so a large embedded file makes the JSON large.