Complete API reference for the LibreOffice WASM Document Converter.
- Node.js API
- Browser API
- Document Inspection & Rendering
- Document Editing API
- Image Encoding
- Types
- Configuration
- Error Handling
- Troubleshooting
- Performance
- Building from Source
One-shot conversion utility. Creates a converter, performs the conversion, then destroys it.
import { convertDocument } from '@matbee/libreoffice-converter';
const result = await convertDocument(
docxBuffer,
{ outputFormat: 'pdf' },
{ wasmPath: './wasm' }
);Parameters:
| Parameter | Type | Description |
|---|---|---|
input |
Uint8Array | ArrayBuffer | Buffer |
Document data |
options |
ConversionOptions |
Conversion options |
converterOptions |
LibreOfficeWasmOptions |
Optional converter config |
Returns: Promise<ConversionResult>
One-shot image export utility. Creates a converter, exports to image, then destroys it.
import { exportAsImage } from '@matbee/libreoffice-converter';
// Export DOCX to PNG
const pngData = await exportAsImage(docxBuffer, 'png');
// Export with options
const highResPng = await exportAsImage(docxBuffer, 'png', {
dpi: 300,
width: 1920
});
// Export presentation to SVG
const svgData = await exportAsImage(pptxBuffer, 'svg');Parameters:
| Parameter | Type | Default | Description |
|---|---|---|---|
input |
Uint8Array | ArrayBuffer | Buffer |
- | Document data |
format |
'png' | 'jpg' | 'svg' |
'png' |
Output image format |
imageOptions |
ImageOptions |
- | Image rendering options |
converterOptions |
LibreOfficeWasmOptions |
- | Optional converter config |
Returns: Promise<ConversionResult>
Creates and initializes a main-thread converter instance.
import { createConverter } from '@matbee/libreoffice-converter';
const converter = await createConverter({
wasmPath: './wasm',
verbose: false,
onProgress: (info) => console.log(info.message),
onReady: () => console.log('Ready!'),
onError: (err) => console.error(err),
});Options:
| Option | Type | Default | Description |
|---|---|---|---|
wasmPath |
string |
'./wasm' |
Path to WASM files directory |
verbose |
boolean |
false |
Enable debug logging |
onProgress |
(info: ProgressInfo) => void |
- | Progress callback |
onReady |
() => void |
- | Called when initialization completes |
onError |
(error: Error) => void |
- | Error callback |
Creates a converter that runs in a worker thread. Recommended for servers as it doesn't block the main thread.
import { createWorkerConverter } from '@matbee/libreoffice-converter';
const converter = await createWorkerConverter({
wasmPath: './wasm',
verbose: false,
});
// Same API as LibreOfficeConverter
const result = await converter.convert(docxBuffer, { outputFormat: 'pdf' });
await converter.destroy();| Converter | Thread | Memory | Use Case |
|---|---|---|---|
createConverter() |
Main | Shared | Simple scripts |
createWorkerConverter() |
Worker | Shared | Servers (recommended) |
Convert a document to a different format.
const result = await converter.convert(
inputBuffer,
{
outputFormat: 'pdf',
inputFormat: 'docx', // Optional, auto-detected from filename
password: 'secret', // For encrypted documents
pdf: {
pdfaLevel: 'PDF/A-2b',
quality: 90,
},
},
'document.docx' // Optional filename for format detection
);Returns: Promise<ConversionResult>
interface ConversionResult {
data: Uint8Array; // Converted document bytes
mimeType: string; // MIME type of output
filename: string; // Suggested output filename
duration: number; // Conversion time in ms
}Clean up resources. Call when done converting.
await converter.destroy();Check if a specific conversion path is supported.
import { isConversionSupported } from '@matbee/libreoffice-converter';
isConversionSupported('docx', 'pdf'); // true
isConversionSupported('pdf', 'docx'); // false - PDFs can't be converted to DOCX
isConversionSupported('xlsx', 'csv'); // true
isConversionSupported('pptx', 'xlsx'); // false - can't convert presentations to spreadsheetsGet valid output formats for a given input format.
import { getValidOutputFormatsFor } from '@matbee/libreoffice-converter';
getValidOutputFormatsFor('docx');
// ['pdf', 'docx', 'doc', 'odt', 'rtf', 'txt', 'html', 'png']
getValidOutputFormatsFor('xlsx');
// ['pdf', 'xlsx', 'xls', 'ods', 'csv', 'html', 'png']
getValidOutputFormatsFor('pdf');
// ['pdf', 'png', 'svg', 'html'] (PDFs are imported as Draw documents)Check if a format is supported.
import { isInputFormatSupported, isOutputFormatSupported } from '@matbee/libreoffice-converter';
isInputFormatSupported('docx'); // true
isOutputFormatSupported('pdf'); // trueGet lists of all supported formats.
import { LibreOfficeConverter } from '@matbee/libreoffice-converter';
const inputFormats = LibreOfficeConverter.getSupportedInputFormats();
// ['doc', 'docx', 'xls', 'xlsx', 'ppt', 'pptx', 'odt', 'ods', 'odp', ...]
const outputFormats = LibreOfficeConverter.getSupportedOutputFormats();
// ['pdf', 'docx', 'doc', 'odt', 'rtf', 'txt', 'html', 'xlsx', ...]| Format | Extension | Description |
|---|---|---|
| Microsoft Word | .doc, .docx |
Word 97-2003 and modern |
| Microsoft Excel | .xls, .xlsx |
Excel 97-2003 and modern |
| Microsoft PowerPoint | .ppt, .pptx |
PowerPoint 97-2003 and modern |
| OpenDocument Text | .odt |
LibreOffice Writer |
| OpenDocument Spreadsheet | .ods |
LibreOffice Calc |
| OpenDocument Presentation | .odp |
LibreOffice Impress |
| Rich Text Format | .rtf |
Cross-platform text |
| Plain Text | .txt |
UTF-8 text |
| HTML | .html, .htm |
Web pages |
| CSV | .csv |
Comma-separated values |
.pdf |
For editing (limited) | |
| EPUB | .epub |
E-books |
| Format | Extension | MIME Type |
|---|---|---|
.pdf |
application/pdf |
|
| DOCX | .docx |
application/vnd.openxmlformats-officedocument.wordprocessingml.document |
| DOC | .doc |
application/msword |
| ODT | .odt |
application/vnd.oasis.opendocument.text |
| RTF | .rtf |
application/rtf |
| TXT | .txt |
text/plain |
| HTML | .html |
text/html |
| XLSX | .xlsx |
application/vnd.openxmlformats-officedocument.spreadsheetml.sheet |
| XLS | .xls |
application/vnd.ms-excel |
| ODS | .ods |
application/vnd.oasis.opendocument.spreadsheet |
| CSV | .csv |
text/csv |
| PPTX | .pptx |
application/vnd.openxmlformats-officedocument.presentationml.presentation |
| PPT | .ppt |
application/vnd.ms-powerpoint |
| ODP | .odp |
application/vnd.oasis.opendocument.presentation |
| PNG | .png |
image/png |
| JPG | .jpg |
image/jpeg |
| SVG | .svg |
image/svg+xml |
Runs LibreOffice in a Web Worker, keeping the main thread responsive. Recommended for browsers.
import { WorkerBrowserConverter, createWasmPaths } from '@matbee/libreoffice-converter/browser';
const converter = new WorkerBrowserConverter({
...createWasmPaths(), // Defaults to /wasm/
browserWorkerJs: '/dist/browser.worker.js',
onProgress: (info) => {
progressBar.style.width = `${info.percent}%`;
statusText.textContent = info.message;
},
});
await converter.initialize();
// Convert a File object
const file = document.querySelector('input[type="file"]').files[0];
const arrayBuffer = await file.arrayBuffer();
const result = await converter.convert(new Uint8Array(arrayBuffer), {
outputFormat: 'pdf',
}, file.name);
// Download the result
const blob = new Blob([result.data], { type: result.mimeType });
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = result.filename;
a.click();Main thread converter (blocks UI during conversion):
import { BrowserConverter, createWasmPaths } from '@matbee/libreoffice-converter/browser';
const converter = new BrowserConverter({
...createWasmPaths(),
onProgress: (info) => console.log(`${info.percent}%: ${info.message}`),
});
await converter.initialize();
const result = await converter.convert(fileData, { outputFormat: 'pdf' }, 'doc.docx');import { createWasmPaths, DEFAULT_WASM_BASE_URL } from '@matbee/libreoffice-converter/browser';
// Use default /wasm/ path (same-origin)
const paths = createWasmPaths();
// Returns:
// {
// sofficeJs: '/wasm/soffice.js',
// sofficeWasm: '/wasm/soffice.wasm',
// sofficeData: '/wasm/soffice.data',
// sofficeWorkerJs: '/wasm/soffice.worker.js',
// }
// Or use your own CDN
const paths = createWasmPaths('https://cdn.example.com/wasm/');
// Or specify each path manually
const converter = new WorkerBrowserConverter({
sofficeJs: 'https://cdn.example.com/wasm/soffice.js',
sofficeWasm: 'https://cdn.example.com/wasm/soffice.wasm',
sofficeData: 'https://cdn.example.com/wasm/soffice.data',
sofficeWorkerJs: 'https://cdn.example.com/wasm/soffice.worker.js',
browserWorkerJs: '/workers/browser.worker.js',
});SharedArrayBuffer requires specific CORS headers on your server:
Cross-Origin-Opener-Policy: same-origin
Cross-Origin-Embedder-Policy: require-corp
const converter = new WorkerBrowserConverter({
...createWasmPaths('/wasm/'),
browserWorkerJs: '/dist/browser.worker.js',
onProgress: (progress) => {
console.log(`Phase: ${progress.phase}`);
console.log(`Progress: ${progress.percent}%`);
console.log(`Message: ${progress.message}`);
// During download phases, bytes info is available
if (progress.bytesLoaded !== undefined) {
const mb = (progress.bytesLoaded / 1024 / 1024).toFixed(1);
const totalMb = (progress.bytesTotal! / 1024 / 1024).toFixed(1);
console.log(`Downloaded: ${mb} MB / ${totalMb} MB`);
}
},
});interface WasmLoadProgress {
percent: number; // Overall progress 0-100
message: string; // Human-readable status message
phase: WasmLoadPhase; // Current loading phase
bytesLoaded?: number; // Bytes downloaded (during download phases)
bytesTotal?: number; // Total bytes to download
}
type WasmLoadPhase =
| 'download-wasm' // Downloading soffice.wasm (~142MB)
| 'download-data' // Downloading soffice.data (~96MB)
| 'compile' // WebAssembly compilation
| 'filesystem' // Emscripten filesystem setup
| 'lok-init' // LibreOfficeKit initialization
| 'ready'; // Complete| Phase | Weight | Description |
|---|---|---|
download-wasm |
30% | Downloading soffice.wasm (~142MB) |
download-data |
20% | Downloading soffice.data (~96MB) |
compile |
10% | WebAssembly compilation |
filesystem |
5% | Virtual filesystem setup |
lok-init |
35% | LibreOffice initialization |
All converters provide APIs for inspecting documents and rendering page previews.
Get document metadata including type, page count, and valid output formats.
const docInfo = await converter.getDocumentInfo(fileBuffer, 'docx');
console.log(docInfo);
// {
// documentType: 0, // 0=TEXT, 1=SPREADSHEET, 2=PRESENTATION, 3=DRAWING
// documentTypeName: 'Text Document',
// validOutputFormats: ['pdf', 'docx', 'odt', 'html', 'txt', 'png'],
// pageCount: 5
// }Get just the page count for a document.
const pageCount = await converter.getPageCount(docxBuffer, 'docx');Render a single page as raw RGBA pixel data.
const preview = await converter.renderPage(pptxBuffer, 'pptx', 0, 800);
// preview.data is a Uint8Array containing raw RGBA pixel data
console.log(`Rendered: ${preview.width}x${preview.height} pixels`);Returns: Promise<PagePreview>
interface PagePreview {
page: number; // Page index
data: Uint8Array; // Raw RGBA pixel data
width: number; // Actual rendered width
height: number; // Actual rendered height
}Render multiple pages as thumbnails.
// Render all pages at 400px width
const previews = await converter.renderPagePreviews(pptxBuffer, 'pptx', {
width: 400,
});
// Render only specific pages
const selectedPreviews = await converter.renderPagePreviews(pptxBuffer, 'pptx', {
width: 800,
pageIndices: [0, 2, 4], // Only pages 1, 3, and 5
});Extract all text content from a document.
const text = await converter.getDocumentText(docxBuffer, 'docx');Get slide names (for presentations) or sheet names (for spreadsheets).
const slideNames = await converter.getPageNames(pptxBuffer, 'pptx');
// ['Introduction', 'Overview', 'Conclusion']
const sheetNames = await converter.getPageNames(xlsxBuffer, 'xlsx');
// ['Sheet1', 'Data', 'Summary']Open a document for editing.
const session = await converter.openDocument(docxBuffer, 'docx');
// {
// sessionId: 'edit_session_0_1234567890',
// documentType: 'writer', // 'writer', 'calc', or 'impress'
// pageCount: 5
// }Execute an editing operation on an open document.
// Get document structure
const structure = await converter.editorOperation(session.sessionId, 'getStructure');
// Get document type
const docType = await converter.editorOperation(session.sessionId, 'getDocumentType');
// Insert text (Writer documents)
await converter.editorOperation(session.sessionId, 'insertText', 'Hello, World!');
// Set cell value (Calc documents)
await converter.editorOperation(session.sessionId, 'setCellValue', 'A1', 42);Close an editing session and get the modified document.
const modifiedData = await converter.closeDocument(session.sessionId);
if (modifiedData) {
fs.writeFileSync('modified.docx', modifiedData);
}The renderPage and renderPagePreviews methods return raw RGBA pixel data. Use the built-in image encoding utilities to convert to PNG, JPEG, or WebP.
The image utilities use sharp when available. Sharp is an optional peer dependency - if not installed, a pure JavaScript PNG fallback is used.
# Optional: Install sharp for faster encoding and JPEG/WebP support
npm install sharpConvert raw RGBA pixel data to PNG format.
import { createWorkerConverter, rgbaToPng } from '@matbee/libreoffice-converter';
const converter = await createWorkerConverter({ wasmPath: './wasm' });
const preview = await converter.renderPage(docBuffer, 'docx', 0, 800);
const pngBuffer = await rgbaToPng(preview.data, preview.width, preview.height);
fs.writeFileSync('page.png', pngBuffer);Encode to any supported format with options.
import { encodeImage } from '@matbee/libreoffice-converter';
// PNG with custom compression
const png = await encodeImage(preview.data, preview.width, preview.height, {
format: 'png',
compressionLevel: 9, // 0-9, default 6
});
// JPEG (requires sharp)
const jpeg = await encodeImage(preview.data, preview.width, preview.height, {
format: 'jpeg',
quality: 85, // 1-100, default 90
});
// WebP (requires sharp)
const webp = await encodeImage(preview.data, preview.width, preview.height, {
format: 'webp',
quality: 80,
});Check if sharp is installed for advanced encoding options.
import { isSharpAvailable } from '@matbee/libreoffice-converter';
if (await isSharpAvailable()) {
console.log('Using sharp for fast image encoding');
} else {
console.log('Using pure JS fallback (PNG only)');
}import { rgbaToPng, rgbaToJpeg, rgbaToWebp } from '@matbee/libreoffice-converter';
const png = await rgbaToPng(data, width, height); // Works without sharp
const jpeg = await rgbaToJpeg(data, width, height, 90); // Requires sharp
const webp = await rgbaToWebp(data, width, height, 80); // Requires sharpinterface LibreOfficeWasmOptions {
wasmPath?: string; // Path to WASM files (default: './wasm')
verbose?: boolean; // Enable debug logging (default: false)
onReady?: () => void; // Called when ready
onError?: (error: Error) => void; // Called on error
onProgress?: (progress: ProgressInfo) => void; // Progress callback
}interface ConversionOptions {
outputFormat: OutputFormat; // Required: output format
inputFormat?: InputFormat; // Optional: input format hint
pdf?: PdfOptions; // PDF-specific options
image?: ImageOptions; // Image output options
password?: string; // For encrypted documents
}interface ConversionResult {
data: Uint8Array; // Converted document bytes
mimeType: string; // MIME type of output
filename: string; // Suggested output filename
duration: number; // Conversion time in ms
}interface PdfOptions {
pdfaLevel?: 'PDF/A-1b' | 'PDF/A-2b' | 'PDF/A-3b'; // PDF/A conformance
quality?: number; // 0-100, affects image compression (default: 90)
}interface ImageOptions {
width?: number; // Image width in pixels
height?: number; // Image height in pixels
dpi?: number; // DPI for rendering (default: 150)
}type InputFormat =
| 'doc' | 'docx' | 'xls' | 'xlsx' | 'ppt' | 'pptx'
| 'odt' | 'ods' | 'odp' | 'odg' | 'odf'
| 'rtf' | 'txt' | 'html' | 'htm' | 'csv' | 'xml' | 'epub' | 'pdf';
type OutputFormat =
| 'pdf' | 'docx' | 'doc' | 'odt' | 'rtf' | 'txt' | 'html'
| 'xlsx' | 'xls' | 'ods' | 'csv'
| 'pptx' | 'ppt' | 'odp'
| 'png' | 'jpg' | 'svg';const result = await converter.convert(input, {
outputFormat: 'pdf',
pdf: {
pdfaLevel: 'PDF/A-2b', // 'PDF/A-1b', 'PDF/A-2b', 'PDF/A-3b'
quality: 90,
},
});const result = await converter.convert(input, {
outputFormat: 'png',
image: {
width: 1920,
height: 1080,
dpi: 150,
},
});const result = await converter.convert(encryptedDoc, {
outputFormat: 'pdf',
password: 'document-password',
});class ConversionError extends Error {
code: ConversionErrorCode;
details?: string;
}| Code | Description |
|---|---|
WASM_NOT_INITIALIZED |
Module not loaded or initialized |
INVALID_INPUT |
Empty or invalid input document |
UNSUPPORTED_FORMAT |
Format not supported |
CORRUPTED_DOCUMENT |
Cannot parse input document |
PASSWORD_REQUIRED |
Document is encrypted |
CONVERSION_FAILED |
Generic conversion error |
LOAD_FAILED |
Could not load document |
import { ConversionError, ConversionErrorCode } from '@matbee/libreoffice-converter';
try {
const result = await converter.convert(input, { outputFormat: 'pdf' });
} catch (err) {
if (err instanceof ConversionError) {
switch (err.code) {
case ConversionErrorCode.INVALID_INPUT:
console.error('Invalid input document');
break;
case ConversionErrorCode.PASSWORD_REQUIRED:
console.error('Document is password protected');
break;
default:
console.error('Conversion failed:', err.message);
}
}
}Ensure the wasm/ directory contains all required files:
soffice.wasmsoffice.cjssoffice.datasoffice.worker.cjsloader.cjs
SharedArrayBuffer requires specific headers. Add to your server:
Cross-Origin-Opener-Policy: same-origin
Cross-Origin-Embedder-Policy: require-corp
Browser initialization includes downloading ~240MB of WASM files. This is network-dependent.
- WASM files are cached by the browser after first load
- Conversions take 1-5 seconds depending on document size
- Reuse the converter instance for multiple conversions
- For servers (Node.js), initialization is much faster (~1-2s) since files load from disk
The WASM module uses ~1GB RAM. For memory-constrained environments:
- Use
converter.destroy()after batch conversions - Avoid parallel conversions
Compress WASM files for 79% smaller downloads:
# Brotli (best - 40MB total)
brotli -9 wasm/soffice.wasm -o wasm/soffice.wasm.br
brotli -9 wasm/soffice.data -o wasm/soffice.data.br
# Gzip (63MB total)
gzip -9 -k wasm/soffice.wasm
gzip -9 -k wasm/soffice.dataThe WASM module uses pthread workers that keep the Node.js process alive:
// Option 1: Explicitly exit when done
await converter.destroy();
process.exit(0);
// Option 2: For servers, the process stays alive anyway (this is fine)
// Option 3: Use setTimeout with unref() for scripts
const timer = setTimeout(() => {}, 0);
timer.unref();const converter = await createConverter({
wasmPath: './wasm',
verbose: true, // Shows LibreOffice internal logs
});Node.js (filesystem-based):
| Operation | Time |
|---|---|
| First initialization | ~1s |
| DOCX → PDF | ~100ms (first), ~35ms (subsequent) |
| XLSX → PDF | ~65ms (first), ~35ms (subsequent) |
| PPTX → PDF | ~290ms (first), ~250ms (subsequent) |
Browser (Chromium, local server):
| Operation | Time |
|---|---|
| WASM download (~240MB) | 5-30s (depends on network) |
| LibreOfficeKit initialization | ~2.5s |
| DOCX → PDF | ~95ms |
| XLSX → PDF | ~85ms |
| PPTX → PDF | ~305ms |
- Reuse converter instances - Initialization cost is paid only once
- Pre-initialize - Start loading during idle time or page load
- Server keep-warm - In production, keep converter processes alive
- Use Web Workers - Keep UI responsive (browser)
- Enable Brotli compression - Reduces transfer size by 79% (192MB → 40MB)
- Cache WASM files - Browser caches files after first load
- Ubuntu 22.04+ / Debian 12+ (or compatible)
- 16GB+ RAM (32GB recommended)
- 50GB+ disk space
- 8+ CPU cores (32 recommended)
- Build time: 1-4 hours
# Ubuntu/Debian
sudo apt-get update
sudo apt-get install -y \
build-essential git cmake ninja-build \
python3 python3-pip python3-dev \
autoconf automake bison ccache flex gawk gettext \
libarchive-dev libcups2-dev libcurl4-openssl-dev \
libfontconfig1-dev libfreetype6-dev libglib2.0-dev \
libharfbuzz-dev libicu-dev libjpeg-dev liblcms2-dev \
libpng-dev libssl-dev libtool libxml2-dev libxslt1-dev \
pkg-config uuid-dev xsltproc zip unzip wget curl \
ca-certificates xz-utils gperf nasmgit clone https://github.com/matbeedotcom/libreoffice-document-converter.git
cd libreoffice-document-converter
# Run the build script (takes 1-4 hours)
BUILD_JOBS=32 ./build/build-wasm.sh| Environment Variable | Default | Description |
|---|---|---|
BUILD_JOBS |
$(nproc) |
Number of parallel compile jobs |
BUILD_DIR |
~/libreoffice-wasm-build |
Build directory |
OUTPUT_DIR |
./wasm |
Output directory for WASM files |
LIBREOFFICE_VERSION |
libreoffice-24-8 |
LibreOffice Git branch |
EMSDK_VERSION |
3.1.51 |
Emscripten SDK version |
| File | Size (Raw) | Size (Brotli) | Description |
|---|---|---|---|
soffice.wasm |
112 MB | 24.8 MB | Main WebAssembly binary |
soffice.data |
80 MB | 15.2 MB | Filesystem image (fonts, configs) |
soffice.cjs |
230 KB | - | JavaScript loader |
soffice.worker.cjs |
4 KB | - | Web Worker script |
loader.cjs |
8 KB | - | Node.js module loader |
| Total | 192 MB | 40 MB | With Brotli compression |
LibreOffice filter names for each output format.
const FORMAT_FILTERS: Record<OutputFormat, string> = {
pdf: 'writer_pdf_Export',
docx: 'MS Word 2007 XML',
doc: 'MS Word 97',
odt: 'writer8',
// ... etc
};MIME types for each output format.
const FORMAT_MIME_TYPES: Record<OutputFormat, string> = {
pdf: 'application/pdf',
docx: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
// ... etc
};