libreoffice-convert

repository·master·Indexed 43 days ago

https://github.com/elwerene/libreoffice-convert

A Node.js module for converting office documents to different formats using LibreOffice. Version 1.8.2 provides the `convert` and `convertWithOptions` functions to transform document buffers into target formats like PDF, utilizing the system's soffice binary.

Tokens
1.8K
Snippets
3
Records
6
Agent score
5%

What's inside libreoffice-convert

  1. Install LibreOffice dependency

    master

    This module requires LibreOffice to be installed on your system to perform conversions. Depending on your operating system, follow these steps:

    • macOS: Install LibreOffice in /Applications.
    • Linux: Install LibreOffice using your preferred package manager.
    • Windows: Install LibreOffice using the .msi installer. Additionally, you must add a PROGRAMFILES environment variable to your local project pointing to the Windows program files path.
  2. How LibreOffice binary discovery works

    master

    The library automatically attempts to locate the soffice binary on your system. It checks the sofficeBinaryPaths provided in options first, then falls back to platform-specific defaults:

    • macOS (darwin): /Applications/LibreOffice.app/Contents/MacOS/soffice
    • Linux: /usr/bin/libreoffice, /usr/bin/soffice, /snap/bin/libreoffice, /opt/libreoffice/program/soffice, /opt/libreoffice7.6/program/soffice
    • Windows (win32): Searches common Program Files and Program Files (x86) paths, checks the LIBRE_OFFICE_EXE environment variable, and falls back to C:/Program Files/LibreOffice/program/soffice.exe.

    If no binary is found, the callback returns an error: Could not find soffice binary.

  3. Convert documents using libreoffice-convert

    master

    The libreoffice-convert module provides a convert function to transform office documents into different formats. Since the base module uses callbacks, it is recommended to promisify it using util.promisify to use async/await syntax.

    To convert a file:

    1. Read the input file into a Buffer.
    2. Call the conversion function with the input Buffer, the target extension (e.g., .pdf), and an optional filter.
    3. The function returns a Buffer containing the converted file content.
    'use strict';
    
    const path = require('path');
    const fs = require('fs').promises;
    const libre = require('libreoffice-convert');
    
    // Promisify the convert method for async/await usage
    libre.convertAsync = require('util').promisify(libre.convert);
    
    async function main() {
        const ext = '.pdf';
        const inputPath = path.join(__dirname, '/resources/example.docx');
        const outputPath = path.join(__dirname, `/resources/example${ext}`);
    
        // Read file into a Buffer
        const docxBuf = await fs.readFile(inputPath);
    
        // Convert it to pdf format with undefined filter
        // The third argument is the LibreOffice filter
        let pdfBuf = await libre.convertAsync(docxBuf, ext, undefined);
        
        // Save the resulting Buffer to a file
        await fs.writeFile(outputPath, pdfBuf);
    }
    
    main().catch(function (err) {
        console.log(`Error converting file: ${err}`);
    });
  4. Convert document buffers using convert()

    master

    The convert function is the primary API for transforming a document buffer into a different format using LibreOffice. It is a convenience wrapper around convertWithOptions that uses default settings.

    Parameters:

    • document (Buffer): The source document buffer.
    • format (string): The target format (e.g., 'pdf', 'docx').
    • filter (string, optional): An optional LibreOffice filter string to refine the conversion.
    • callback (function): A callback function that receives (err, result). result is the Buffer of the converted document.
    const { convert } = require('libreoffice-convert');
    
    const inputBuffer = fs.readFileSync('input.docx');
    
    convert(inputBuffer, 'pdf', '', (err, outputBuffer) => {
        if (err) {
            console.error(err);
            return;
        }
        fs.writeFileSync('output.pdf', outputBuffer);
    });
  5. Configure conversion with convertWithOptions()

    master

    Use convertWithOptions when you need to provide specific configuration for the temporary directory, execution, or LibreOffice binary paths.

    Parameters:

    • document (Buffer): The source document buffer.
    • format (string): The target format.
    • filter (string, optional): LibreOffice filter string.
    • options (Object, optional): Configuration object containing:
      • tmpOptions (Object): Options passed to the tmp library for creating temporary directories.
      • asyncOptions (Object): Options for the internal retry logic (e.g., times, interval).
      • execOptions (Object): Options passed to child_process.execFile.
      • fileName (string): The name used for the temporary source file (defaults to 'source').
      • sofficeAdditionalArgs (Array<string>): Additional command-line arguments to pass to the soffice binary.
      • sofficeBinaryPaths (Array<string>): Custom paths to search for the soffice binary. If not provided, the library searches standard locations for macOS, Linux, and Windows.
    • callback (function): A callback function that receives (err, result). result is the Buffer of the converted document.
    const { convertWithOptions } = require('libreoffice-convert');
    
    const options = {
        fileName: 'my-document.odt',
        sofficeAdditionalArgs: ['--no-sandbox'],
        asyncOptions: {
            times: 5,
            interval: 500
        }
    };
    
    convertWithOptions(inputBuffer, 'pdf', '', options, (err, outputBuffer) => {
        // handle result
    });
  6. Reference: convertWithOptions options object

    master

    The following keys are available in the options object passed to convertWithOptions:

    • tmpOptions: Configuration for the tmp package used to create tempDir and installDir.
    • asyncOptions: Configuration for the async.retry mechanism used when loading the destination file. Supported keys: times (default: 3), interval (default: 200).
    • execOptions: Configuration for the execFile call to the soffice binary.
    • fileName: The base name for the temporary source file. Defaults to 'source'.
    • sofficeAdditionalArgs: An array of strings appended to the soffice command line.
    • sofficeBinaryPaths: An array of strings representing filesystem paths to search for the soffice executable.