### Convert Document to PDF (Callback) Source: https://context7.com/elwerene/libreoffice-convert/llms.txt Use this function to convert a document buffer to a specified format using callbacks. Ensure LibreOffice is installed and accessible. ```javascript 'use strict'; const fs = require('fs'); const path = require('path'); const { convert } = require('libreoffice-convert'); // Read a .docx file from disk const inputBuffer = fs.readFileSync(path.join(__dirname, 'example.docx')); // Convert to PDF using the default filter convert(inputBuffer, 'pdf', undefined, (err, pdfBuffer) => { if (err) { console.error('Conversion failed:', err.message); // err.message examples: // 'Could not find soffice binary' // 'Error calling soffice: ...' return; } // pdfBuffer is a Buffer containing the PDF bytes fs.writeFileSync(path.join(__dirname, 'example.pdf'), pdfBuffer); console.log(`PDF written, size: ${pdfBuffer.length} bytes`); // → PDF written, size: 84302 bytes }); ``` -------------------------------- ### Convert Office Document to PDF Source: https://github.com/elwerene/libreoffice-convert/blob/master/Readme.md Use this snippet to convert a DOCX file to PDF asynchronously. Ensure LibreOffice is installed on your system and accessible. ```javascript 'use strict'; const path = require('path'); const fs = require('fs').promises; const libre = require('libreoffice-convert'); 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 const docxBuf = await fs.readFile(inputPath); // Convert it to pdf format with undefined filter (see Libreoffice docs about filter) let pdfBuf = await libre.convertAsync(docxBuf, ext, undefined); // Here in done you have pdf file which you can save or transfer in another stream await fs.writeFile(outputPath, pdfBuf); } main().catch(function (err) { console.log(`Error converting file: ${err}`); }); ``` -------------------------------- ### Advanced Conversion with Options Source: https://context7.com/elwerene/libreoffice-convert/llms.txt Use `convertWithOptions` for custom binary paths, extra arguments, retry behavior, and input format hinting. Ensure the `sofficeBinaryPaths` are correctly configured for your environment. ```javascript 'use strict'; const fs = require('fs').promises; const path = require('path'); const { promisify } = require('util'); const { convertWithOptions } = require('libreoffice-convert'); const convertWithOptionsAsync = promisify(convertWithOptions); async function advancedConvert(inputPath) { const inputBuffer = await fs.readFile(inputPath); const options = { // Hint the filename so LibreOffice infers the input format correctly fileName: path.basename(inputPath), // Override the binary search path (useful in Docker/CI environments) sofficeBinaryPaths: [ '/usr/lib/libreoffice/program/soffice', '/opt/libreoffice7.6/program/soffice', ], // Configure retry behavior for the output-file read step asyncOptions: { times: 5, // retry up to 5 times (default: 3) interval: 500, // wait 500 ms between retries (default: 200) }, // Pass additional soffice CLI flags sofficeAdditionalArgs: ['--infilter=writer8'], // Configure the tmp module for the working directory tmpOptions: { dir: '/tmp/my-conversions', }, }; try { const pdfBuffer = await convertWithOptionsAsync(inputBuffer, 'pdf', undefined, options); const outputPath = inputPath.replace(path.extname(inputPath), '.pdf'); await fs.writeFile(outputPath, pdfBuffer); console.log(`Done: ${outputPath} (${pdfBuffer.length} bytes)`); // → Done: ./contract.pdf (102548 bytes) } catch (err) { // Possible errors: // 'Could not find soffice binary' — none of the paths resolved // 'Error calling soffice: ...' — LibreOffice reported an error on stderr console.error('Conversion error:', err.message); throw err; } } advancedConvert('./contract.docx'); ``` -------------------------------- ### Demonstrate Various Document Conversions with LibreOffice Source: https://context7.com/elwerene/libreoffice-convert/llms.txt This snippet shows how to convert a .docx file to multiple formats including PDF, plain text, HTML, and ODT. It also demonstrates converting .xlsx to CSV using a specific filter and .pptx to PNG. Ensure input files like 'data.xlsx' and 'slides.pptx' exist for full execution. ```javascript 'use strict'; const fs = require('fs').promises; const { promisify } = require('util'); const libre = require('libreoffice-convert'); const convertAsync = promisify(libre.convert); async function demonstrateFormats(inputBuffer) { // --- Common format targets --- // Word .docx → PDF (most common use case) const pdf = await convertAsync(inputBuffer, 'pdf', undefined); // Word .docx → plain text const txt = await convertAsync(inputBuffer, 'txt', undefined); // Word .docx → HTML const html = await convertAsync(inputBuffer, 'html', undefined); // Word .docx → OpenDocument Text const odt = await convertAsync(inputBuffer, 'odt', undefined); // Spreadsheet .xlsx → CSV // Use a filter string to target a specific sheet/format variant const xlsxBuf = await fs.readFile('./data.xlsx'); const csv = await convertAsync(xlsxBuf, 'csv', 'Text - txt - csv (StarCalc)'); // Presentation .pptx → PNG (first slide) const pptxBuf = await fs.readFile('./slides.pptx'); const png = await convertAsync(pptxBuf, 'png', undefined); // Write results await fs.writeFile('./out.pdf', pdf); await fs.writeFile('./out.txt', txt); await fs.writeFile('./out.html', html); await fs.writeFile('./out.odt', odt); await fs.writeFile('./out.csv', csv); await fs.writeFile('./out.png', png); console.log('All format conversions complete.'); // → All format conversions complete. } (async () => { const docxBuf = await fs.readFile('./example.docx'); await demonstrateFormats(docxBuf); })(); ``` -------------------------------- ### convert(document, format, filter, callback) Source: https://context7.com/elwerene/libreoffice-convert/llms.txt Performs a basic document conversion from a Buffer to a specified format using LibreOffice. It accepts the document buffer, target format string, an optional filter, and a callback function that receives an error or the resulting buffer. ```APIDOC ## convert(document, format, filter, callback) ### Description Converts an office document `Buffer` to the specified format using the system LibreOffice installation. The callback receives `(err, resultBuffer)`. This is the simplest entry point: supply the raw file bytes, the target extension string, an optional filter (pass `undefined` for the default), and a callback. LibreOffice is invoked with `--headless --convert-to ` inside a self-cleaning temporary directory. ### Parameters - **document** (Buffer) - The document content as a Buffer. - **format** (string) - The target output format (e.g., 'pdf', 'txt', 'png'). - **filter** (string | undefined) - An optional LibreOffice filter string. Pass `undefined` for the default filter. - **callback** (function) - A Node.js style callback function `(err, resultBuffer)`. ### Request Example ```javascript 'use strict'; const fs = require('fs'); const path = require('path'); const { convert } = require('libreoffice-convert'); // Read a .docx file from disk const inputBuffer = fs.readFileSync(path.join(__dirname, 'example.docx')); // Convert to PDF using the default filter convert(inputBuffer, 'pdf', undefined, (err, pdfBuffer) => { if (err) { console.error('Conversion failed:', err.message); // err.message examples: // 'Could not find soffice binary' // 'Error calling soffice: ...' return; } // pdfBuffer is a Buffer containing the PDF bytes fs.writeFileSync(path.join(__dirname, 'example.pdf'), pdfBuffer); console.log(`PDF written, size: ${pdfBuffer.length} bytes`); // → PDF written, size: 84302 bytes }); ``` ### Response #### Success Response - **resultBuffer** (Buffer) - A Buffer containing the converted document's content. ``` -------------------------------- ### convert (promisified) Source: https://context7.com/elwerene/libreoffice-convert/llms.txt Provides an async/await compatible version of the `convert` function by using `util.promisify`. This is the recommended pattern for modern Node.js codebases, allowing for cleaner asynchronous operations. ```APIDOC ## convert (promisified) ### Description Because `convert` follows the Node.js error-first callback pattern, it can be wrapped with `util.promisify` for use with `async/await`. This is the recommended pattern for modern codebases and works with any supported output format. ### Method `async/await` (promisified `convert` function) ### Parameters - **document** (Buffer) - The document content as a Buffer. - **format** (string) - The target output format (e.g., 'pdf', 'txt', 'png'). - **filter** (string | undefined) - An optional LibreOffice filter string. Pass `undefined` for the default filter. ### Returns - **Promise** - A Promise that resolves with a Buffer containing the converted document's content, or rejects with an error. ### Request Example ```javascript 'use strict'; const fs = require('fs').promises; const path = require('path'); const { promisify } = require('util'); const libre = require('libreoffice-convert'); const convertAsync = promisify(libre.convert); async function convertDocument(inputPath, outputExt) { const inputBuffer = await fs.readFile(inputPath); try { const outputBuffer = await convertAsync(inputBuffer, outputExt, undefined); const outputPath = inputPath.replace(path.extname(inputPath), `.${outputExt}`); await fs.writeFile(outputPath, outputBuffer); console.log(`Converted to ${outputExt}: ${outputPath}`); return outputPath; } catch (err) { console.error(`Failed to convert ${inputPath}:`, err.message); throw err; } } // Examples (async () => { await convertDocument('./report.docx', 'pdf'); // → Converted to pdf: ./report.pdf await convertDocument('./spreadsheet.xlsx', 'pdf'); // → Converted to pdf: ./spreadsheet.pdf await convertDocument('./presentation.pptx', 'png'); // → Converted to png: ./presentation.png })(); ``` ``` -------------------------------- ### Convert Document to Various Formats (Async/Await) Source: https://context7.com/elwerene/libreoffice-convert/llms.txt This promisified version of the convert function is recommended for modern Node.js applications using async/await. It handles errors and file writing asynchronously. ```javascript 'use strict'; const fs = require('fs').promises; const path = require('path'); const { promisify } = require('util'); const libre = require('libreoffice-convert'); const convertAsync = promisify(libre.convert); async function convertDocument(inputPath, outputExt) { const inputBuffer = await fs.readFile(inputPath); try { const outputBuffer = await convertAsync(inputBuffer, outputExt, undefined); const outputPath = inputPath.replace(path.extname(inputPath), `.${outputExt}`); await fs.writeFile(outputPath, outputBuffer); console.log(`Converted to ${outputExt}: ${outputPath}`); return outputPath; } catch (err) { console.error(`Failed to convert ${inputPath}:`, err.message); throw err; } } // Examples (async () => { await convertDocument('./report.docx', 'pdf'); // → Converted to pdf: ./report.pdf await convertDocument('./spreadsheet.xlsx', 'pdf'); // → Converted to pdf: ./spreadsheet.pdf await convertDocument('./presentation.pptx', 'png'); // → Converted to png: ./presentation.png })(); ``` -------------------------------- ### Express.js PDF Conversion Endpoint Source: https://context7.com/elwerene/libreoffice-convert/llms.txt Integrates `libreoffice-convert` into an Express.js application to handle file uploads and convert them to PDF. Uses `multer` for file handling and streams the converted PDF back to the client. ```javascript 'use strict'; const express = require('express'); const multer = require('multer'); const { promisify } = require('util'); const libre = require('libreoffice-convert'); const convertAsync = promisify(libre.convert); const upload = multer({ storage: multer.memoryStorage(), limits: { fileSize: 50 * 1024 * 1024 } }); const app = express(); // POST /convert — multipart field: "document" // Returns: application/pdf app.post('/convert', upload.single('document'), async (req, res) => { if (!req.file) { return res.status(400).json({ error: 'No document uploaded.' }); } try { const pdfBuffer = await convertAsync(req.file.buffer, 'pdf', undefined); res.set({ 'Content-Type': 'application/pdf', 'Content-Disposition': `attachment; filename="${req.file.originalname.replace(/\.[^.]+$/, '.pdf')}"`, 'Content-Length': pdfBuffer.length, }); res.send(pdfBuffer); } catch (err) { console.error('Conversion failed:', err.message); res.status(500).json({ error: 'Document conversion failed.', detail: err.message }); } }); app.listen(3000, () => console.log('Listening on http://localhost:3000')); // curl example: // curl -X POST http://localhost:3000/convert \ // -F "document=@./report.docx" \ // --output report.pdf ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.