soffice
Version:
wrapper of the LibreOffice CLI - convert between office files, pdf, and html files
103 lines (102 loc) • 3.24 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.ChildProcessError = void 0;
exports.is_soffice_installed = is_soffice_installed;
exports.convertTo = convertTo;
exports.convertToPDF = convertToPDF;
exports.convertToHTML = convertToHTML;
const child_process_1 = require("child_process");
const promises_1 = require("fs/promises");
const path_1 = require("path");
function is_soffice_installed() {
try {
let output = (0, child_process_1.execSync)('soffice --version').toString();
return output.includes('LibreOffice');
}
catch (error) {
// e.g. not in PATH
return false;
}
}
function extractFileDetails(input_file, convert_to) {
let input_ext = (0, path_1.extname)(input_file);
let output_ext = '.' + convert_to.split(':')[0];
let output_file = input_file.slice(0, input_file.length - input_ext.length) + output_ext;
let dir = (0, path_1.dirname)(input_file);
return { output_file, dir };
}
/**
* Convert a file to a different format using LibreOffice cli `soffice`.
*
* @param options.input_file - The path to the input file.
* @param options.convert_to - The format to convert the file to.
*
* @returns The path to the output file.
*/
function convertTo(options) {
let { input_file, convert_to } = options;
const { dir, output_file } = extractFileDetails(input_file, convert_to);
return new Promise((resolve, reject) => {
let child = (0, child_process_1.spawn)('soffice', [
'--headless',
'--writer',
'--convert-to',
convert_to,
input_file,
'--outdir',
dir,
]);
child.on('error', reject);
let stdout = '';
child.stdout.on('data', data => {
stdout += data.toString();
});
let stderr = '';
child.stderr.on('data', data => {
stderr += data.toString();
});
child.on('exit', async (code) => {
try {
if (code !== 0) {
throw new ChildProcessError(`Failed to convert file "${input_file}" into ${convert_to}`, code, stdout, stderr);
}
try {
await (0, promises_1.access)(output_file);
resolve(output_file);
}
catch (error) {
let from = (0, path_1.extname)(input_file);
let to = (0, path_1.extname)(output_file);
throw new Error(`Not supported to convert from ${from} to ${to}`);
}
}
catch (error) {
reject(error);
}
});
});
}
function convertToPDF(input_file) {
return convertTo({
input_file,
convert_to: 'pdf',
});
}
function convertToHTML(input_file) {
return convertTo({
input_file,
convert_to: 'html',
});
}
class ChildProcessError extends Error {
code;
stdout;
stderr;
constructor(message, code, stdout, stderr) {
super(message);
this.code = code;
this.stdout = stdout;
this.stderr = stderr;
}
}
exports.ChildProcessError = ChildProcessError;