feat: add DOCX/TXT/HTML document converters

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
This commit is contained in:
2026-07-30 09:10:34 +02:00
co-authored by Claude Sonnet 5
parent a049be2fc8
commit 16b4f28b42
2 changed files with 127 additions and 0 deletions
+50
View File
@@ -0,0 +1,50 @@
import fs from 'node:fs/promises';
import mammoth from 'mammoth';
import puppeteer from 'puppeteer';
import { register } from './registry.js';
async function renderHtmlToPdf(html, outputPath) {
const browser = await puppeteer.launch({
headless: true,
args: ['--no-sandbox', '--disable-setuid-sandbox'],
});
try {
const page = await browser.newPage();
await page.setContent(html, { waitUntil: 'networkidle0' });
await page.pdf({ path: outputPath, format: 'A4', printBackground: true });
} finally {
await browser.close();
}
}
function escapeHtml(text) {
return text.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
}
async function convertDocxToHtml(inputPath, outputPath) {
const result = await mammoth.convertToHtml({ path: inputPath });
await fs.writeFile(outputPath, result.value);
}
async function convertTxtToPdf(inputPath, outputPath) {
const text = await fs.readFile(inputPath, 'utf8');
const html = `<html><body><pre>${escapeHtml(text)}</pre></body></html>`;
await renderHtmlToPdf(html, outputPath);
}
async function convertHtmlToPdf(inputPath, outputPath) {
const html = await fs.readFile(inputPath, 'utf8');
await renderHtmlToPdf(html, outputPath);
}
async function convertDocxToPdf(inputPath, outputPath) {
const result = await mammoth.convertToHtml({ path: inputPath });
await renderHtmlToPdf(result.value, outputPath);
}
export function registerDocumentConverters() {
register({ family: 'document', sourceFormat: 'docx', targetFormat: 'html', convert: convertDocxToHtml });
register({ family: 'document', sourceFormat: 'txt', targetFormat: 'pdf', convert: convertTxtToPdf });
register({ family: 'document', sourceFormat: 'html', targetFormat: 'pdf', convert: convertHtmlToPdf });
register({ family: 'document', sourceFormat: 'docx', targetFormat: 'pdf', convert: convertDocxToPdf });
}