Converting DOCX to WEBP with Node.js

This guide shows how to convert a DOCX image to WEBP in Node.js with the Sharp package. This requires PDF as an intermediary step, if you would like to know more read the main article.

Installing Prerequisites

These instructions are written for Ubuntu 24.04; it should be relatively simple to adapt them for operating system distributions to suit your own needs.

  1. update the apt package manager:
apt update
  1. LibreOffice, to convert DOCX to PDF:
apt install -y libreoffice
  1. libpoppler so Sharp can convert PDFs to images:
apt install -y libpoppler-glib-dev
  1. build tools:
apt install -y build-essential pkg-config meson ninja-build cmake libglib2.0-dev libexpat1-dev
  1. libraries you need for parity with a standard distribution of Sharp:
apt install -y libjpeg-turbo8-dev libpng-dev libwebp-dev libtiff-dev libgif-dev libcgif-dev libimagequant-dev libheif-dev libdav1d-dev liblcms2-dev libexif-dev zlib1g-dev libbrotli-dev

Building libvips

libvips is a library written in C, which Sharp uses to convert images. If you want to convert file types which are not supported out-of-the-box, you will have to rebuild libvips:

curl -L -O https://github.com/libvips/libvips/releases/download/v8.18.0/vips-8.18.0.tar.xz
tar xf vips-8.18.0.tar.xz
cd vips-8.18.0
meson setup build --prefix=/usr/local
ninja -C build
ninja -C build install
ldconfig
cd ..

If you would like to know more, you can read about it here.

Installing Node Packages

LibreOffice accessible from Node.js without an intermediary, install it:

npm i libreoffice

You will have to install these and build Sharp with your local libvips:

npm i node-addon-api
npm explore sharp -- npm run build

Code

Create a file (e.g. example.js) with the following contents:

example.js
import sharp from "sharp";
import * as path from 'path';
import {readFileSync} from 'fs';
import libre from 'libreoffice';
import {promisify} from "util";
libre.convertAsync = promisify(libre.convert);

const pdfBuffer = await libre.convertAsync(readFileSync('test.docx'), '.pdf', undefined);
sharp(pdfBuffer).webp().toFile('from_docx.webp');

Run with:

node example.js