Export

You can export a chart or a diagram as an SVG, PNG, WebP or JPEG file, and put charts and diagrams into a Word document. You can also replace a chart with an image of it. Exporting reads the document and changes nothing. Only the commands change the document.
New tab

Files

import { downloadBlob } from '@tiptap-pro/extension-diagrams/export'

const { blob, svg, width, height, alt } = await editor.storage.diagrams.export(
  { pos },
  { format: 'png', scale: 2, background: '#ffffff' },
)
downloadBlob(blob, 'chart.png')

What to export

The first argument, target, is one of:

TargetExports
{ pos? }A chart or a diagram in the document
{ data, spec, renderer? }Chart data that is in no document

A diagram is drawn by its Diagram Renderer. The renderer and size options do not apply to a diagram. A diagram's colors come from the --tt-flow-diagram-* custom properties.

Options

OptionTypeDefaultDescription
format'svg' | 'png' | 'webp' | 'jpeg''svg'The file format
scalenumber2Pixels per SVG unit for an image
backgroundstring | nullnullA fill behind the chart
rendererstringThe chart'sDraw with another Renderer
themeChartThemeThe page'sA ChartTheme instead of the custom properties on the page
size{ width: number; height: number }{ width: 800, height: 450 }, or 800 wide at the chart's own ratioThe size to draw at
scheme'light' | 'dark''light'The color scheme to draw in, whatever the page shows

What comes back

FieldContent
blobThe file
svgThe SVG
width, heightThe size of the drawing
altThe title and description, for an alt attribute
rendererThe Renderer it was drawn with
rastertrue when the Renderer drew pixels
  • The SVG has concrete colors, not var(…), so it looks the same outside your page.
  • A Renderer that draws pixels, such as one that draws on a canvas, can be exported too. Its SVG holds an image instead of shapes, so it does not scale without loss. See Your own Renderer.
  • PNG, WebP and JPEG files need a browser.
  • The SVG of ECharts and D3 charts can be made on a server.

@tiptap-pro/extension-diagrams/export also has svgToBlob, svgToImage, toDataUrl, readSvgSize, inlineSvgStyles and rasterToSvg.

Word

There are three ways to get charts into a Word document:

WayWhat the Word file holds
editor.storage.diagrams.exportDocx()Only the charts and diagrams, without the rest of the document. Charts are native Word charts where Word can draw them, and diagrams are images
toPortableContent with ExportDocxThe whole document. Each chart is an image, a table or both, and each diagram is an image or its source
toPortableContent with charts: 'native', then addNativeChartsThe whole document, with native Word charts

A native Word chart is a chart that Word draws itself. You can restyle it in Word, and "Edit data" opens its data in Excel.

Charts and diagrams only

exportDocx writes a new Word file that holds only the charts and diagrams:

const { blob, notes } = await editor.storage.diagrams.exportDocx({
  targets: [{ pos }],
  title: 'Report',
})
downloadBlob(blob, 'charts.docx')
for (const note of notes) console.info(note.title ?? 'All charts', note.message)
OptionTypeDescription
targetsChartTarget[]The charts and diagrams to write, in order
titlestringA heading above the charts
fallbackFontstringThe font Word uses when it lacks the page's font. Default 'Arial'
images'auto' | 'always'When a chart becomes an image, see Charts as images

What the file holds

  • Each target, in order, becomes a native Word chart with its data in an embedded workbook, a Word table, or an image, as described below.
  • A diagram becomes a PNG image, scaled to the page width, with its title as caption.
  • Without targets, the file holds every chart that has data and is not hidden behind its table, and every diagram that has source, in document order.
  • When there is nothing to write, or nothing could be written, the promise rejects.
  • A chart with caption is followed by its description in Word's Caption style.
  • Every chart and image has its title and description as alt text.
  • A matrix becomes a Word table with shaded cells.
  • Series colors and the font come from the page. See Styling.

Charts as images

images decides when a chart becomes a PNG image instead of a native Word chart:

imagesWhat a chart becomes
'always'A PNG image, drawn by its Renderer, at the chart's size
'auto'A Word chart or a Word table when Word has a form for the type. An image for every other type, and in the two cases below
Left outThe docxImages option decides

With 'auto', a chart also becomes an image when a Word chart would show something different:

  • a scatter chart with numbers on its x axis, because Word would space the x values evenly,
  • a chart with reference lines, because Word charts have none.

When no image can be drawn, for example because no Renderer can draw the chart, a chart whose type has a Word form becomes a Word chart, with a note. A chart of any other type is left out, with a note.

Notes

notes lists what Word shows differently from the editor, one sentence each. The extension works the notes out from the chart's data and Chart Spec, so you get them without opening the file. A note has pos, title and message. Notes cover:

  • a font Word lacks (pos: null),
  • a pie or doughnut chart with more than one series, which Word shows with the first series only,
  • the range of the x axis, which Word ignores,
  • a background, series or axis color that is not a hex value,
  • grid lines or labels at only some categories, which Word puts at every category,
  • a value grid line where the category axis line is left out,
  • the edges of an area chart with series styles, which Word draws in its own line style,
  • options only one Renderer understands,
  • that a linked chart holds a snapshot of its data in Word,
  • a matrix, which is a Word table,
  • a chart written as an image, and why when its type has a Word form,
  • a chart left out, or written as a Word chart, because no image could be drawn,
  • a diagram, which is an image in Word, or was left out because it could not be drawn.

Without exporting

These functions from @tiptap-pro/extension-diagrams/core tell you what Word gets, without writing a file:

FunctionReturns
wordForm(type, images?)What a type becomes: 'chart', 'table' or 'image'
wordChartForm(data, spec, images?)What one chart becomes: 'chart', 'table' or 'image'
wordLimitations(data, spec, { theme, source?, images? })The same list as notes, for one chart

A whole document

A converter that does not know the chart and flowDiagram nodes leaves them out. toPortableContent from @tiptap-pro/extension-diagrams/core returns a copy of the document in which charts and diagrams are made of nodes every converter knows, such as tables, images and paragraphs. Export that copy instead.

This example exports the copy with @tiptap-pro/extension-export-docx, which sends it to Tiptap's Convert service:

import { Editor } from '@tiptap/core'
import { ConvertKit } from '@tiptap-pro/extension-convert-kit'
import { toPortableContent } from '@tiptap-pro/extension-diagrams/core'
import { ExportDocx } from '@tiptap-pro/extension-export-docx'

const file = await new Promise((resolve, reject) => {
  const exporter = new Editor({
    element: null,
    content: toPortableContent(editor.getJSON()),
    extensions: [
      ConvertKit,
      ExportDocx.configure({ token: 'CONVERT_TOKEN', onCompleteExport: resolve, onError: reject }),
    ],
  })
  exporter.commands.exportDocx()
})

toPortableContent needs no browser, so it runs on a server too. CONVERT_TOKEN is your Convert API token. See the export-docx docs for its options.

What the copy holds

In the documentIn the copy
A chartIts image, when there is one, and its data as a table. Its title above a table without an image. Its description below, when the chart shows it as a caption
A chart hidden behind the table it followsNothing, because the table is already there
A diagramIts image, when imageFor gives one. Otherwise its title and its source as code-formatted lines
An open Quick InputIts text as code-formatted lines

A chart has an image only when your app uploads one with uploadImage, which sets previewUrl. Without it, the copy holds the chart's data as a table.

A matrix cell's color is its background attribute, and its text color is a textStyle mark. A converter that reads them keeps the colors.

Options

OptionValueDefault
charts'both', 'image' (the image, or the table when there is none), 'table' or 'native' (see Native Word charts)'both'
imageFor(figure) => url | null, the image of a chart or a diagram. figure is { kind, attrs }A chart's previewUrl
sources'paragraphs', one code-formatted paragraph per line, or 'codeBlock''paragraphs'
namesYour node names for table, tableRow, tableHeader, tableCell, paragraph, image, codeBlockStarterKit's and @tiptap/extension-table's
decimalSeparator'.' or ',' for numbers in a table'.'
themeThe ChartTheme for the colors of a matrix chart's cellsdefaultChartTheme

'paragraphs' keeps a diagram's source in a converter that leaves out code blocks. Choose 'codeBlock' for a converter that writes them, such as one to Markdown or HTML.

Native Word charts

With charts: 'native', a chart of a type Word draws itself becomes a marker line instead of an image and a table. These types are bar, line, area, scatter, pie, doughnut, radar and combo. Any converter can then write the Word file. After that, addNativeCharts replaces each marker with a native Word chart.

import { Editor } from '@tiptap/core'
import { ConvertKit } from '@tiptap-pro/extension-convert-kit'
import { addNativeCharts, toPortableContent } from '@tiptap-pro/extension-diagrams/core'
import { ExportDocx } from '@tiptap-pro/extension-export-docx'

const doc = editor.getJSON()
const exported = await new Promise((resolve, reject) => {
  const exporter = new Editor({
    element: null,
    content: toPortableContent(doc, { charts: 'native' }),
    extensions: [
      ConvertKit,
      ExportDocx.configure({
        token: 'CONVERT_TOKEN',
        exportType: 'buffer',
        onCompleteExport: resolve,
        onError: reject,
      }),
    ],
  })
  exporter.commands.exportDocx()
})
const docx = addNativeCharts({ docx: exported, doc })
  • Other types are written as with 'both'.
  • Pass addNativeCharts the same document that you passed to toPortableContent. It finds the charts in the same order.
  • addNativeCharts also takes theme and fallbackFont. theme sets the colors and the font of the charts and defaults to defaultChartTheme. fallbackFont is the font Word uses when it lacks the theme's font, 'Arial' by default, as for exportDocx.
  • A marker that a converter split or changed is left as text.

Commands

convertChartToImage

Replaces a chart with an image of it. The image is a node of the type named by the imageNodeName option.

editor.commands.convertChartToImage({ format: 'svg', keepData: true })
OptionTypeDescription
format'svg' | 'png' | 'webp' | 'jpeg'The image format. Default 'png'
keepDatabooleanThe image keeps the chart, so convertImageToChart brings it back. Kept unless false
posnumberThe chart's position. Defaults to the selected chart
  • The image is uploaded with uploadImage, or embedded as a data URL without it.
  • The chart is replaced once the image is ready, unless the chart changed in the meantime.
  • The image is exported at twice its size, so it stays sharp on high-density screens.
  • When the image node has a width attribute, as @tiptap/extension-image does, the command sets it to the chart's width, and the image shows at that size.

Give images max-width: 100% so they shrink on a narrow screen:

.tiptap img {
  max-width: 100%;
  height: auto;
}

convertImageToChart

Turns an image made with keepData back into the chart.

editor.commands.convertImageToChart()
OptionTypeDescription
posnumberThe image's position. Defaults to the selected image

redrawChartImage

Draws an image made with keepData again from the chart it keeps, with the current styles, Renderers and color scheme.

editor.commands.redrawChartImage({ pos })
OptionTypeDescription
format'svg' | 'png' | 'webp' | 'jpeg'The image format. Default 'png'
posnumberThe image's position. Defaults to the selected image
  • The image keeps its other attributes and the chart it keeps.
  • Only its file, text and width change, once the new file is ready, unless the image changed in the meantime.

Returns false for an image that keeps no chart, and when no Renderer draws its type.