Files
DolanandClaude Fable 5.1 19087e8b79 fix: name images in the package as Word does, image1.png and so on (#3872)
* fix: name images in the package as Word does, image1.png and so on

Images were written to word/media under a SHA-1 hash of their data,
such as 4bf7547c9322fd2143bd3e8dfa84109d9d3fed14.png. Word for the web
has shown an empty box in place of an image named like that, and shown
it once the file was renamed image1.png as Word names its own, as
https://github.com/dolanmiu/docx/issues/496 reports.

The hash is still the key an image is added to the media under, so an
image used twice is stored once and its placeholders are unchanged, but
the file is written as image1.png, image2.jpg and so on, numbered in the
order images are added. The numbers come from the document's
PackageParts, which an ImagePatch's parts already take theirs from, so
an image never takes a part's name, nor a part an image's, and in
patchDocument new images are numbered after the template's own.

Closes #496
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01QzDw6ZwCkrdX4ZsWzeVQNC

* docs: say images are numbered by type, image1.png and image1.jpg

A document's images take their names from PackageParts.takePath,
which numbers by the whole file name, so a PNG and a JPEG are
image1.png and image1.jpg, not image2.jpg as the docs and the Media
comment said. Word for the web shows images named this way, as the
images demo showed, and an ImagePatch's images were already numbered
so. The docs now say that, and a Media without a path taker numbers
its images by type too, so it names them as a document does.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01QzDw6ZwCkrdX4ZsWzeVQNC

* test: a document numbers its images by type, in the order they are added

Covers a PNG, a JPEG and a second PNG written through File, which
takePath names image1.png, image1.jpg and image2.png.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01QzDw6ZwCkrdX4ZsWzeVQNC

* test: check the relationships to a document's images, numbered by type

The mixed-extension test checked the media files and their bytes, but
not the relationships that point the drawings at them, which is the
XML the names matter in.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01QzDw6ZwCkrdX4ZsWzeVQNC

* test: check each of a document's images is written under its own number

Swapping the two PNGs' bytes passed the mixed-extension test, though
its name says images are numbered in the order they are added.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01QzDw6ZwCkrdX4ZsWzeVQNC

---------

Co-authored-by: Claude Fable 5.1 <noreply@anthropic.com>
2026-10-31 14:10:01 +00:00

28 KiB
Raw Permalink Blame History

Images

!> Images requires an understanding of Sections and Paragraphs.

?> To draw rectangles, lines, arrows and other shapes instead of pictures, see Shapes.

Common Use Cases

I want to... Use Example
Insert an image inline with text Inline (default) Logo next to company name
Position image at specific coordinates Floating with offset Letterhead logo at top-right
Have text wrap around an image Floating with wrap Magazine-style layout
Put an image in a table cell Inline in TableCell Product catalog
Add image to header/footer Inline in Header/Footer Company letterhead
Trim edges off an image crop option Removing unwanted borders
Insert an image that's sharp at any size type: "svg" with a fallback Vector logo

Inline vs Floating: When to Use Which

Use Inline when:

  • Image should flow with text
  • Image is part of content (diagrams, screenshots)
  • Image goes inside tables
  • Image in headers/footers

Use Floating when:

  • Image needs precise positioning
  • Text should wrap around image
  • Image overlays content (watermarks)
  • Complex page layouts

To create a floating image on top of text:

import { Document, ImageRun, Paragraph, TextRun } from "docx";
import * as fs from "fs";

const image = new ImageRun({
    type: "gif",
    data: fs.readFileSync("./demo/assets/images/pizza.gif"),
    transformation: {
        width: 200,
        height: 200,
    },
    floating: {
        horizontalPosition: {
            offset: 1014400,
        },
        verticalPosition: {
            offset: 1014400,
        },
    },
});

const doc = new Document({
    sections: [
        {
            children: [
                new Paragraph({
                    children: [image, new TextRun("The image floats on top of this text, instead of making room for it in the line.")],
                }),
            ],
        },
    ],
});

By default with no arguments, its an inline image. Add it into the document by adding the image into a paragraph:

import { Document, ImageRun, Paragraph } from "docx";
import * as fs from "fs";

const image = new ImageRun({
    type: "gif",
    data: fs.readFileSync("./demo/assets/images/pizza.gif"),
    transformation: {
        width: 100,
        height: 100,
    },
});

const doc = new Document({
    sections: [
        {
            children: [
                new Paragraph({
                    children: [image],
                }),
            ],
        },
    ],
});

Intro

Adding images can be easily done by creating an instance of ImageRun. This can be added in a Paragraph or Hyperlink:

import { Document, ImageRun, Paragraph } from "docx";
import * as fs from "fs";

const doc = new Document({
    sections: [
        {
            children: [
                new Paragraph({
                    children: [
                        new ImageRun({
                            type: "png",
                            data: fs.readFileSync("./demo/assets/images/dog.png"),
                            transformation: {
                                width: 166,
                                height: 150,
                            },
                        }),
                    ],
                }),
            ],
        },
    ],
});

The type is jpg (for JPEG files), png, gif, bmp or svg. TypeScript requires it. From JavaScript, an image without one has its type read from the start of its data, and docx throws an error when the data isn't a PNG, JPEG, GIF or BMP file.

The width and height in transformation are in pixels, at 96 to the inch, so width: 528 is 5.5 inches wide. They aren't in EMUs, which floating offsets use. Word won't open a document with an image more than 225457 pixels wide or tall, so docx throws an error for one, such as an image sized in EMUs by mistake.

In the .docx, images are written to word/media with the names Word gives them, image1.png, image2.png and so on, numbered by type in the order they are added, so a document with a PNG and a JPEG has image1.png and image1.jpg. An image used more than once, such as a logo in the body and in a header, is written once. Word for the web shows images with Word's own names, and has shown an empty box in place of an image named otherwise.

SVG Images

An SVG image stays sharp at any size. Give it type: "svg" and a fallback: a png, jpg, gif or bmp copy of the same picture, which apps that can't draw SVG show instead. Word for Microsoft 365 and Word 2019 or later draw the SVG, and so does LibreOffice. Older Word and Apple Pages draw the fallback.

import { Document, ImageRun, Paragraph } from "docx";
import * as fs from "fs";

const doc = new Document({
    sections: [
        {
            children: [
                new Paragraph({
                    children: [
                        new ImageRun({
                            type: "svg",
                            data: fs.readFileSync("./demo/assets/images/linux-svg.svg"),
                            fallback: {
                                type: "png",
                                data: fs.readFileSync("./demo/assets/images/linux-png.png"),
                            },
                            transformation: {
                                width: 200,
                                height: 200,
                            },
                        }),
                    ],
                }),
            ],
        },
    ],
});

The fallback is drawn at the SVG's size, from the same transformation, so give it the same proportions. All the other options, such as floating, altText and outline, work the same as for other images.

The data of an SVG is the file's bytes, or a base64 data URI, as for other images. To use SVG markup that is in a string, such as one from an API or a charting library, turn it into bytes with TextEncoder. A string of markup on its own isn't read as an SVG, and docx throws an error:

import { Document, ImageRun, Paragraph } from "docx";
import * as fs from "fs";

// SVG markup in a string
const svg = fs.readFileSync("./demo/assets/images/linux-svg.svg", "utf8");

const doc = new Document({
    sections: [
        {
            children: [
                new Paragraph({
                    children: [
                        new ImageRun({
                            type: "svg",
                            data: new TextEncoder().encode(svg),
                            fallback: {
                                type: "png",
                                data: fs.readFileSync("./demo/assets/images/linux-png.png"),
                            },
                            transformation: {
                                width: 200,
                                height: 200,
                            },
                        }),
                    ],
                }),
            ],
        },
    ],
});

Options

Property Type Notes Possible Values
type "svg" Required "svg"
data Buffer, Uint8Array, ArrayBuffer or string Required The SVG file's bytes, or a base64 data URI
fallback { type: "png" | "jpg" | "gif" | "bmp", data: ... } Required A copy of the picture for apps that can't draw SVG

Positioning

Positioning is the method on how to place the image on the document

Word Image Positioning

Two types of image positioning are supported:

  • Floating
  • Inline

By default, images are exported as Inline elements.

Usage

To float an image, give the ImageRun a floating option, as the examples below do.

Floating

To change the position the image to be on top of the text, simply add the floating property to the last argument. By default, the offsets are relative to the top left corner of the page. Offset units are in emus:

import { Document, ImageRun, Paragraph, TextRun } from "docx";
import * as fs from "fs";

const image = new ImageRun({
    type: "png",
    data: fs.readFileSync("./demo/assets/images/linux-png.png"),
    transformation: {
        width: 200,
        height: 240,
    },
    floating: {
        horizontalPosition: {
            offset: 1014400, // relative: HorizontalPositionRelativeFrom.PAGE by default
        },
        verticalPosition: {
            offset: 1014400, // relative: VerticalPositionRelativeFrom.PAGE by default
        },
    },
});

const doc = new Document({
    sections: [
        {
            children: [
                new Paragraph({
                    children: [
                        image,
                        new TextRun("The image is placed 1014400 EMUs from the top left corner of the page, on top of this text."),
                    ],
                }),
            ],
        },
    ],
});
import { Document, HorizontalPositionRelativeFrom, ImageRun, Paragraph, TextRun, VerticalPositionRelativeFrom } from "docx";
import * as fs from "fs";

const image = new ImageRun({
    type: "png",
    data: fs.readFileSync("./demo/assets/images/linux-png.png"),
    transformation: {
        width: 60,
        height: 72,
    },
    floating: {
        horizontalPosition: {
            relative: HorizontalPositionRelativeFrom.RIGHT_MARGIN,
            offset: 182880,
        },
        verticalPosition: {
            relative: VerticalPositionRelativeFrom.BOTTOM_MARGIN,
            offset: 182880,
        },
    },
});

const doc = new Document({
    sections: [
        {
            children: [
                new Paragraph({
                    children: [image, new TextRun("The image is placed in the bottom right corner, in the right and bottom margins.")],
                }),
            ],
        },
    ],
});

Options

Full options you can pass into floating are:

Property Type Notes
horizontalPosition HorizontalPositionOptions Required
verticalPosition VerticalPositionOptions Required
allowOverlap boolean Optional
lockAnchor boolean Optional
behindDocument boolean Optional
layoutInCell boolean Optional
zIndex number Optional

HorizontalPositionOptions are:

Property Type Notes Possible Values
relative HorizontalPositionRelativeFrom Required CHARACTER, COLUMN, INSIDE_MARGIN, LEFT_MARGIN, MARGIN, OUTSIDE_MARGIN, PAGE, RIGHT_MARGIN
align HorizontalPositionAlign You can either have align or offset, not both CENTER, INSIDE, LEFT, OUTSIDE, RIGHT
offset number You can either have align or offset, not both 0 to Infinity

VerticalPositionOptions are:

Property Type Notes Possible Values
relative VerticalPositionRelativeFrom Required BOTTOM_MARGIN, INSIDE_MARGIN, LINE, MARGIN, OUTSIDE_MARGIN, PAGE, PARAGRAPH, TOP_MARGIN
align VerticalPositionAlign You can either have align or offset, not both BOTTOM, CENTER, INSIDE, OUTSIDE, TOP
offset number You can either have align or offset, not both 0 to Infinity

Wrap text

Wrapping only works for floating elements. Text will "wrap" around the floating image.

Add wrap options inside the floating options:

wrap: {
    type: [TextWrappingType],
    side: [TextWrappingSide],
},

For example:

import { Document, ImageRun, Paragraph, TextRun, TextWrappingSide, TextWrappingType } from "docx";
import * as fs from "fs";

const image = new ImageRun({
    type: "gif",
    data: fs.readFileSync("./demo/assets/images/pizza.gif"),
    transformation: {
        width: 200,
        height: 200,
    },
    floating: {
        horizontalPosition: {
            offset: 2014400,
        },
        verticalPosition: {
            offset: 2014400,
        },
        wrap: {
            type: TextWrappingType.SQUARE,
            side: TextWrappingSide.BOTH_SIDES,
        },
    },
});

const doc = new Document({
    sections: [
        {
            children: [
                new Paragraph({
                    children: [image, new TextRun("This text wraps around both sides of the image. ".repeat(40))],
                }),
            ],
        },
    ],
});

Wrap options have the following properties are:

Property Type Notes Possible Values
type TextWrappingType Optional NONE, SQUARE, TIGHT, THROUGH, TOP_AND_BOTTOM
side TextWrappingSide Optional BOTH_SIDES, LEFT, RIGHT, LARGEST

Margins

Margins give some space between the text and the image. Margins only work for floating elements. Additionally, the image must also be in wrap mode (see above).

?> Be sure to also set wrap in your options!

To use, add the margins options inside the floating options:

margins: {
    top: number,
    bottom: number,
    left: number,
    right: number
},

For example:

import { Document, ImageRun, Paragraph, TextRun, TextWrappingSide, TextWrappingType } from "docx";
import * as fs from "fs";

const image = new ImageRun({
    type: "gif",
    data: fs.readFileSync("./demo/assets/images/pizza.gif"),
    transformation: {
        width: 200,
        height: 200,
    },
    floating: {
        horizontalPosition: {
            offset: 2014400,
        },
        verticalPosition: {
            offset: 2014400,
        },
        wrap: {
            type: TextWrappingType.SQUARE,
            side: TextWrappingSide.BOTH_SIDES,
        },
        margins: {
            top: 201440,
            bottom: 201440,
        },
    },
});

const doc = new Document({
    sections: [
        {
            children: [
                new Paragraph({
                    children: [image, new TextRun("The margins keep this text further from the top and bottom of the image. ".repeat(40))],
                }),
            ],
        },
    ],
});

Run Formatting

Use run to format the run the image is in, with the same options as a TextRun's formatting. position raises or lowers an inline image from the text's baseline, by a signed length such as "2pt" or "-2pt":

import { Document, ImageRun, Paragraph, TextRun } from "docx";
import * as fs from "fs";

const image = new ImageRun({
    type: "gif",
    data: fs.readFileSync("./demo/assets/images/pizza.gif"),
    transformation: { width: 100, height: 100 },
    run: { position: "-2pt" },
});

const doc = new Document({
    sections: [
        {
            children: [
                new Paragraph({
                    children: [new TextRun("Text before "), image, new TextRun(" text after")],
                }),
            ],
        },
    ],
});

To place an image at page coordinates or control text wrapping, use floating instead.

Space between images

An inline image sits in its line like a letter, so images next to each other in a paragraph touch. To space them out, put a space between each two, in a TextRun whose characterSpacing widens it by that many twentieths of a point. Word ignores characterSpacing on an image's own run, and an image's margins only work when it floats.

import { Document, ImageRun, Paragraph, TextRun } from "docx";
import * as fs from "fs";

const photos = [
    { file: "./demo/assets/images/cat.jpg", width: 150 },
    { file: "./demo/assets/images/image1.jpeg", width: 133 },
    { file: "./demo/assets/images/cat.jpg", width: 150 },
];

const images = photos.map(
    ({ file, width }) => new ImageRun({ type: "jpg", data: fs.readFileSync(file), transformation: { width, height: 100 } }),
);

const doc = new Document({
    sections: [
        {
            children: [
                new Paragraph({
                    // Between each two images, a space 10 points (200 twentieths) wider than usual
                    children: images.flatMap((image, index) =>
                        index === 0 ? [image] : [new TextRun({ text: " ", characterSpacing: 200 }), image],
                    ),
                }),
            ],
        },
    ],
});

The preview on this page doesn't widen the spaces, so download the document to see them in Word.

To put images one under another instead, give each its own paragraph, with space after it:

import { Document, ImageRun, Paragraph } from "docx";
import * as fs from "fs";

const photos = [
    { file: "./demo/assets/images/cat.jpg", width: 150 },
    { file: "./demo/assets/images/image1.jpeg", width: 133 },
];

const doc = new Document({
    sections: [
        {
            children: photos.map(
                ({ file, width }) =>
                    new Paragraph({
                        // 10 points (200 twentieths) of space after each image
                        spacing: { after: 200 },
                        children: [new ImageRun({ type: "jpg", data: fs.readFileSync(file), transformation: { width, height: 100 } })],
                    }),
            ),
        },
    ],
});

Alternative Text

Give a picture a description for screen readers, as Word's Alt Text does, and optionally a title. Its name is what Word's Selection Pane calls it, and is empty unless given. All three are optional.

import { Document, ImageRun, Paragraph } from "docx";
import * as fs from "fs";

const image = new ImageRun({
    type: "gif",
    data: fs.readFileSync("./demo/assets/images/pizza.gif"),
    transformation: { width: 100, height: 100 },
    altText: {
        title: "This is an ultimate title",
        description: "This is an ultimate image",
        name: "My Ultimate Image",
    },
});

const doc = new Document({
    sections: [
        {
            children: [new Paragraph({ children: [image] })],
        },
    ],
});

Options

Property Type Notes Possible Values
name string Optional Specimen A
title string Optional My awesome title of my image
description string Optional My awesome description of my image

Give an image a link to open a web page when it is clicked (with Ctrl in Word), the same as Word's Insert > Link on a picture:

import { Document, ImageRun, Paragraph } from "docx";
import * as fs from "fs";

const image = new ImageRun({
    type: "png",
    data: fs.readFileSync("./demo/assets/images/linux-png.png"),
    transformation: { width: 100, height: 120 },
    altText: { name: "Logo", description: "Company logo", title: "Logo" },
    link: "https://example.com",
});

const doc = new Document({
    sections: [
        {
            children: [new Paragraph({ children: [image] })],
        },
    ],
});

An image inside an ExternalHyperlink links to the hyperlink's address already. If it has a link of its own, its own link is used.

Mark an image as decorative when it carries no information, such as a border or a flourish, so screen readers skip it. It is the same as Word's Mark as decorative, and is used instead of alternative text:

import { Document, ImageRun, Paragraph } from "docx";
import * as fs from "fs";

const flourish = new ImageRun({
    type: "jpg",
    data: fs.readFileSync("./demo/assets/images/cat.jpg"),
    transformation: { width: 300, height: 200 },
    decorative: true,
});

const doc = new Document({
    sections: [
        {
            children: [new Paragraph({ children: [flourish] })],
        },
    ],
});

Both work for inline and floating images.

Options

Property Type Notes Possible Values
link string Optional "https://example.com"
decorative boolean Optional true

Cropping

Crop an image by trimming a percentage off each edge before it's stretched to fill its frame. Pass a crop property to ImageRun with left, top, right and/or bottom percentages (0 to 100):

import { Document, ImageRun, Paragraph } from "docx";
import * as fs from "fs";

const image = new ImageRun({
    type: "gif",
    data: fs.readFileSync("./demo/assets/images/pizza.gif"),
    transformation: {
        width: 200,
        height: 200,
    },
    crop: {
        left: 10,
        top: 5,
        right: 10,
        bottom: 5,
    },
});

const doc = new Document({
    sections: [
        {
            children: [new Paragraph({ children: [image] })],
        },
    ],
});

Options

Property Type Notes Possible Values
left number Optional 0 to 100
top number Optional 0 to 100
right number Optional 0 to 100
bottom number Optional 0 to 100

Outline

Draw a border around an image with outline. Its width is in EMUs, where 12700 is one point and 9525 is one pixel:

import { Document, ImageRun, Paragraph } from "docx";
import * as fs from "fs";

const image = new ImageRun({
    type: "png",
    data: fs.readFileSync("./demo/assets/images/dog.png"),
    transformation: {
        width: 166,
        height: 150,
    },
    outline: {
        type: "solidFill",
        solidFillType: "rgb",
        value: "1F4E79",
        width: 38100,
    },
});

const doc = new Document({
    sections: [
        {
            children: [new Paragraph({ children: [image] })],
        },
    ],
});

Options

Property Type Notes
type "solidFill" or "noFill" Required. "noFill" draws no outline
solidFillType "rgb" or "scheme" Required with "solidFill"
value string Required with "solidFill". A hex colour such as "FF0000", or a SchemeColor for "scheme"
width number Optional. In EMUs
cap "ROUND", "SQUARE" or "FLAT" Optional. The shape of the line's ends
compoundLine "SINGLE", "DOUBLE", "THICK_THIN", "THIN_THICK" or "TRI" Optional. Draws the outline as several lines
align "CENTER" or "INSET" Optional. Whether the line is centred on the image's edge or drawn inside it

Track Changes

Images can be marked as inserted or deleted revisions for change tracking. Pass an insertion or deletion property to ImageRun, or both for an image that was inserted and then deleted, such as by another author:

import { Document, ImageRun, Paragraph } from "docx";
import * as fs from "fs";

const doc = new Document({
    sections: [
        {
            children: [
                new Paragraph({
                    children: [
                        new ImageRun({
                            type: "png",
                            data: fs.readFileSync("./demo/assets/images/dog.png"),
                            transformation: { width: 120, height: 120 },
                            insertion: {
                                id: 30,
                                author: "Firstname Lastname",
                                date: "2020-10-06T09:00:00Z",
                            },
                        }),
                    ],
                }),
            ],
        },
    ],
});

See Change Tracking – Image Revisions for full details and examples.

Examples

Add image to the document

Importing Images from file system path

Example

Source: https://github.com/dolanmiu/docx/blob/master/demo/images/images.ts

Example showing how to add image to headers and footers

Example

Source: https://github.com/dolanmiu/docx/blob/master/demo/images/images-in-header-and-footer.ts

Floating images

Example showing how to float images on top of text and optimally give a margin

Example

Source: https://github.com/dolanmiu/docx/blob/master/demo/images/text-wrapping.ts

Example

Source: https://github.com/dolanmiu/docx/blob/master/demo/images/image-links.ts