Images
Images convey information that is easier to illustrate than to describe. Univer supports two image types: floating images, which are placed above the grid, and cell images, which are bound to a single cell.
Plugin mode
Installation
pnpm add @univerjs/docs-drawing @univerjs/drawing @univerjs/drawing-ui @univerjs/sheets-drawing @univerjs/sheets-drawing-uinpm install @univerjs/docs-drawing @univerjs/drawing @univerjs/drawing-ui @univerjs/sheets-drawing @univerjs/sheets-drawing-uiyarn add @univerjs/docs-drawing @univerjs/drawing @univerjs/drawing-ui @univerjs/sheets-drawing @univerjs/sheets-drawing-uibun add @univerjs/docs-drawing @univerjs/drawing @univerjs/drawing-ui @univerjs/sheets-drawing @univerjs/sheets-drawing-uiUsage
import { IImageIoService, LocaleType, mergeLocales, Univer } from '@univerjs/core'import { UniverDocsDrawingPlugin } from '@univerjs/docs-drawing'import { UniverDrawingPlugin } from '@univerjs/drawing'import { UniverDrawingUIPlugin } from '@univerjs/drawing-ui'import DrawingUIEnUS from '@univerjs/drawing-ui/locale/en-US'import { UniverSheetsDrawingPlugin } from '@univerjs/sheets-drawing'import { UniverSheetsDrawingUIPlugin } from '@univerjs/sheets-drawing-ui'import SheetsDrawingUIEnUS from '@univerjs/sheets-drawing-ui/locale/en-US'import '@univerjs/drawing-ui/lib/index.css'import '@univerjs/sheets-drawing-ui/lib/index.css'import '@univerjs/sheets-drawing/facade'import '@univerjs/sheets-drawing-ui/facade'const univer = new Univer({ locale: LocaleType.EN_US, locales: { [LocaleType.EN_US]: mergeLocales( DrawingUIEnUS, SheetsDrawingUIEnUS, ), },})univer.registerPlugin(UniverDrawingPlugin)univer.registerPlugin(UniverDrawingUIPlugin)univer.registerPlugin(UniverSheetsDrawingPlugin)univer.registerPlugin(UniverSheetsDrawingUIPlugin)If you use Collaboration, add the override configuration:
univer.registerPlugin(UniverDrawingPlugin, { override: [[IImageIoService, null]], // allowImageSize: 20 * 1024 * 1024, // set the maximum allowed size of uploaded images to 20MB, optional})UniverDrawingPlugin
override[DependencyIdentifier, Provider | null][]Dependency overrides used by the drawing plugin.[0]DependencyIdentifierDependency identifier. UseIImageIoServicefor image storage.[1]Provider | nullReplacement provider. Passnullto let collaboration supply this service.
Plugin configuration
UniverDrawingPlugin
allowImageSizenumberDefault:5 * 1024 * 1024Maximum upload size in bytes.
Mobile support
Configure the mobile editor first. In the plugin-mode setup on this page, replace the desktop registrations listed below with the mobile exports from the same packages, and perform the replacement before opening a document. The model plugins, styles, locales, and Facade imports remain unchanged, and the two variants must not be registered at the same time.
| Package | Desktop registration | Mobile registration |
|---|---|---|
@univerjs/drawing-ui | UniverDrawingUIPlugin | UniverDrawingMobileUIPlugin |
@univerjs/sheets-drawing-ui | UniverSheetsDrawingUIPlugin | UniverSheetsDrawingMobileUIPlugin |
Preset mode
Installation
pnpm add @univerjs/preset-sheets-drawingnpm install @univerjs/preset-sheets-drawingyarn add @univerjs/preset-sheets-drawingbun add @univerjs/preset-sheets-drawingUsage
import { UniverSheetsCorePreset } from '@univerjs/preset-sheets-core'import UniverPresetSheetsCoreEnUS from '@univerjs/preset-sheets-core/locales/en-US'import { UniverSheetsDrawingPreset } from '@univerjs/preset-sheets-drawing'import UniverPresetSheetsDrawingEnUS from '@univerjs/preset-sheets-drawing/locales/en-US'import { createUniver, LocaleType, mergeLocales } from '@univerjs/presets'import '@univerjs/preset-sheets-core/lib/index.css'import '@univerjs/preset-sheets-drawing/lib/index.css'const { univerAPI } = createUniver({ locale: LocaleType.EN_US, locales: { [LocaleType.EN_US]: mergeLocales( UniverPresetSheetsCoreEnUS, UniverPresetSheetsDrawingEnUS, ), }, presets: [ UniverSheetsCorePreset(), UniverSheetsDrawingPreset(), ],})If you use Collaboration, pass the collaboration: true option to UniverSheetsDrawingPreset:
UniverSheetsDrawingPreset({ collaboration: true, })UniverSheetsDrawingPreset
collaborationbooleanDefault:falseEnable collaborative image storage by using the collaboration service for image I/O.
Preset configuration
UniverSheetsDrawingPreset
allowImageSizenumberDefault:5 * 1024 * 1024Maximum upload size in bytes.collaborationbooleanDefault:falseEnable collaboration for drawing resources.
Facade API
The complete Facade API type definitions are in the FacadeAPI.
Importing
Plugin mode note
Only plugin mode requires importing the Facade package manually. Preset mode already includes the matching package.
import '@univerjs/sheets-drawing/facade'import '@univerjs/sheets-drawing-ui/facade'Add floating DOM
FWorksheet.addFloatDomToPosition(layer) adds a floating DOM element at the specified position.
const fWorksheet = univerAPI.getActiveWorkbook().getActiveSheet()// You should register components at an appropriate time (e.g., when Univer is loaded)// This is a React component. For Vue3 components, the third parameter should be `{ framework: 'vue3' }`univerAPI.registerComponent( 'myFloatDom', ({ data }) => ( <div style={{ width: '100%', height: '100%', background: '#fff', border: '1px solid #ccc', boxSizing: 'border-box' }}> popup content: {' '} {data?.label} </div> ),)// Add a floating DOM// If disposable is null, floating DOM addition failedconst disposable = fWorksheet.addFloatDomToPosition({ componentKey: 'myFloatDom', initPosition: { startX: 100, endX: 300, startY: 100, endY: 200, }, // Component data data: { label: 'hahah', },})// 2 秒后移除浮动 DOMsetTimeout(() => { disposable?.dispose()}, 2000)FWorksheet.addFloatDomToRange(range, layer, domLayout) adds a floating DOM element over the specified range.
const fWorksheet = univerAPI.getActiveWorkbook().getActiveSheet()// Register a range loading componentfunction RangeLoading() { const divStyle = { width: '100%', height: '100%', backgroundColor: '#fff', border: '1px solid #ccc', boxSizing: 'border-box' as const, display: 'flex', justifyContent: 'center', alignItems: 'center', textAlign: 'center' as const, transformOrigin: 'top left', } return ( <div style={divStyle}> Loading... </div> )}univerAPI.registerComponent('RangeLoading', RangeLoading)// Add the range loading component covering the range A1:C3const fRange = fWorksheet.getRange('A1:C3')const disposable = fWorksheet.addFloatDomToRange(fRange, { componentKey: 'RangeLoading' }, {}, 'myRangeLoading')// Remove the floating DOM after 2 secondssetTimeout(() => { disposable?.dispose()}, 2000)// another example-------------------// Register a float button componentfunction FloatButton() { const divStyle = { width: '100px', height: '30px', backgroundColor: '#fff', border: '1px solid #ccc', boxSizing: 'border-box' as const, display: 'flex', justifyContent: 'center', alignItems: 'center', textAlign: 'center' as const, cursor: 'pointer', } const clickHandler = () => { console.warn('click') } return ( <div style={divStyle} onClick={clickHandler}> FloatButton </div> )}univerAPI.registerComponent('FloatButton', FloatButton)// Add the float button to the range A5:C7, position is start from A5 cell, and width is 100px, height is 30px, margin is 100% of range width and heightconst fRange2 = fWorksheet.getRange('A5:C7')const disposable2 = fWorksheet.addFloatDomToRange( fRange2, { componentKey: 'FloatButton', }, { width: 100, height: 30, marginX: '100%', // margin percent to range width, or pixel marginY: '100%', }, 'myFloatButton',)FWorksheet.addFloatDomToColumnHeader(column, layer, domPos) adds a floating DOM element to the specified column header.
const fWorksheet = univerAPI.getActiveWorkbook().getActiveSheet()// Register a float button componentfunction FloatButton() { const divStyle = { width: '100px', height: '30px', backgroundColor: '#fff', border: '1px solid #ccc', boxSizing: 'border-box' as const, display: 'flex', justifyContent: 'center', alignItems: 'center', textAlign: 'center' as const, cursor: 'pointer', } const clickHandler = () => { console.warn('click') } return ( <div style={divStyle} onClick={clickHandler}> FloatButton </div> )}univerAPI.registerComponent('FloatButton', FloatButton)// Add the float button to the column D header, position is right align, width is 100px, height is 30px, margin is 0const disposable = fWorksheet.addFloatDomToColumnHeader( 3, { componentKey: 'FloatButton', allowTransform: false, }, { width: 100, height: 30, marginX: 0, marginY: 0, horizonOffsetAlign: 'right', }, 'myFloatButton',)// Remove the float button after 2 secondssetTimeout(() => { disposable?.dispose()}, 2000)Insert floating images
FWorksheet.newOverGridImage() returns a builder for a floating image, an instance of FOverGridImageBuilder. Chaining the setters produces an ISheetImage object that can be inserted into the sheet.
The builder, FOverGridImageBuilder, provides the following methods:
| Method | Description |
|---|---|
| buildAsync | Build the image and return an ISheetImage object |
| setSource | Set the image source |
| setColumn | Set the image's horizontal position |
| setRow | Set the image's vertical position |
| setColumnOffset | Set the image's horizontal offset |
| setRowOffset | Set the image's vertical offset |
| setWidth | Set the image width |
| setHeight | Set the image height |
| setAnchorType | Set the anchor type, which determines whether the position and size change with the cell |
| setCropTop | Set the top edge of the crop region so that only the desired part of the image is shown |
| setCropLeft | Set the left edge of the crop region so that only the desired part of the image is shown |
| setCropBottom | Set the bottom edge of the crop region so that only the desired part of the image is shown |
| setCropRight | Set the right edge of the crop region so that only the desired part of the image is shown |
| setRotate | Set the rotation angle of the image |
// create a new image builder and set image source.// then build `ISheetImage` and insert it into the sheet, position is start from F6 cell, width is 500px, height is 300pxconst fWorkbook = univerAPI.getActiveWorkbook()const fWorksheet = fWorkbook.getActiveSheet()const image = await fWorksheet.newOverGridImage() .setSource('https://avatars.githubusercontent.com/u/61444807?s=48&v=4', univerAPI.Enum.ImageSourceType.URL) .setColumn(5) .setRow(5) .setWidth(500) .setHeight(300) .buildAsync()fWorksheet.insertImages([image])An image can also be inserted with the FWorksheet.insertImage(url, column, row, offsetX, offsetY) method.
// Insert an image to the sheet, position is F6, offset is 10pxconst fWorksheet = univerAPI.getActiveWorkbook().getActiveSheet()const result = await fWorksheet.insertImage('https://avatars.githubusercontent.com/u/61444807?s=48&v=4', 5, 5, 10, 10)Get floating images
FWorksheet.getImages() returns all floating images in the worksheet as an array of FOverGridImage[] instances.
const fWorksheet = univerAPI.getActiveWorkbook().getActiveSheet()const images = fWorksheet.getImages()images.forEach((image) => { image.getId()})To get one floating image by its ID, use the FWorksheet.getImageById(id) method.
Update floating images
FWorksheet.updateImages(sheetImages) updates floating images in place: position, size, and other properties.
// create a new image builder and set image source.// then build `ISheetImage` and insert it into the sheet, position is start from F6 cell, width is 500px, height is 300pxconst fWorkbook = univerAPI.getActiveWorkbook()const fWorksheet = fWorkbook.getActiveSheet()const image = await fWorksheet.newOverGridImage() .setSource('https://avatars.githubusercontent.com/u/61444807?s=48&v=4', univerAPI.Enum.ImageSourceType.URL) .setColumn(5) .setRow(5) .setWidth(500) .setHeight(300) .buildAsync()fWorksheet.insertImages([image])// update the image width to 100px and height to 50px after 4 secondssetTimeout(async () => { const imageBuilder = fWorksheet.getImageById(image.drawingId).toBuilder() const newImage = await imageBuilder.setWidth(100).setHeight(50).buildAsync() fWorksheet.updateImages([newImage])}, 4000)Delete floating images
FWorksheet.deleteImages(sheetImages) deletes floating images.
const fWorksheet = univerAPI.getActiveWorkbook().getActiveSheet()const image = fWorksheet.getImages()[0]// Delete the first image of the sheetfWorksheet.deleteImages([image])Insert cell images
FRange.insertCellImageAsync(file) inserts an image into a cell.
const fWorkbook = univerAPI.getActiveWorkbook()const fWorksheet = fWorkbook.getActiveSheet()// Insert an image into the cell A10const fRange = fWorksheet.getRange('A10')const result = await fRange.insertCellImageAsync('https://avatars.githubusercontent.com/u/61444807?s=48&v=4')Worksheet background image
A worksheet can also have one tiled background image, drawn behind the cells. The image is stored in IWorksheetData.backgroundImage and is independent of floating and cell images. The drawing preset includes this feature. In plugin mode, the required packages are @univerjs/sheets-drawing, its Facade entry, and the drawing UI, which provides rendering and upload controls.
import '@univerjs/sheets-drawing/facade'const sheet = univerAPI.getActiveWorkbook()?.getActiveSheet()if (!sheet) throw new Error('No active worksheet')sheet.setBackgroundImage('https://example.com/background.png')console.log(sheet.getBackgroundImage())sheet.deleteBackgroundImage()setBackgroundImage() uses ImageSourceType.URL by default and replaces any existing background; deleteBackgroundImage() removes it. Both operations are implemented as commands, so undo and redo apply. Uploaded images are resolved by the UI through the configured image I/O service. The background is displayed on screen only and is excluded from printing.
Image opacity
Floating images use a single opacity value for the entire image. setOpacity() accepts a finite number from 0 (transparent) to 1 (opaque); the default is 1, and any other value throws RangeError. Set it on FOverGridImageBuilder before building, or on an FOverGridImage that is already in the sheet. Both expose getOpacity(). The image properties panel also provides a transparency control.
const sheet = univerAPI.getActiveWorkbook()?.getActiveSheet()const image = sheet?.getImages()[0]if (image) { image.setOpacity(0.5) console.log(image.getOpacity())}Image sizing and anchors
Images inserted through the built-in file picker keep their aspect ratio and are scaled down to fit inside 500 × 500 pixels when they are too large; small images are not enlarged. That display size is independent of the allowImageSize byte limit on uploads. When an image is inserted through the Facade, the caller supplies the dimensions.
Anchors determine what happens when cells move or resize. SheetDrawingAnchorType.Position moves the image with the cells while keeping its size, Both moves and resizes it with the anchored range, and None keeps a fixed position and size. Hiding or showing rows or columns preserves the anchor definition: an image sized to a range can collapse with that range and recover when the range is shown again. The temporary hidden-row geometry must not be written back over the saved anchors.
How is this guide?