CVBora / utils /htmlPrep.js
ismizo's picture
Upload 15 files
1ff8e13 verified
Raw History Blame Contribute Delete
1.69 kB
const TurndownService = require('turndown');
const { marked } = require('marked');
/**
* Prepares HTML for document conversion (DOCX).
* Because html-to-docx is incredibly unstable with styled HTML tables/divs,
* we will use Turndown to extract the raw text/markdown structure,
* and then convert it back into safe, barebones HTML for Word.
*
* @param {string} rawHtml
* @returns {string} cleaned HTML
*/
function prepareHtmlForConversion(rawHtml) {
if (!rawHtml || typeof rawHtml !== 'string') return '';
try {
// 1. Convert complex AI HTML to simple Markdown
const turndownService = new TurndownService({
headingStyle: 'atx',
bulletListMarker: '-'
});
// Strip out styling blocks before turndown
const cleanRaw = rawHtml.replace(/<style[^>]*>[\s\S]*?<\/style>/gi, '')
.replace(/<script[^>]*>[\s\S]*?<\/script>/gi, '');
const markdown = turndownService.turndown(cleanRaw);
// 2. Convert simple Markdown back to guaranteed-safe HTML
const safeHtml = marked.parse(markdown);
// 3. Wrap in DOCX required skeleton
return `<!DOCTYPE html><html><head><meta charset="UTF-8"></head><body>${safeHtml}</body></html>`;
} catch (e) {
console.warn("Turndown conversion failed, returning fallback:", e);
// Absolute fallback
const fallbackMsg = "<h1>Resume</h1><p>Error parsing advanced CV styling. Please use the PDF download.</p>";
return `<!DOCTYPE html><html><head><meta charset="UTF-8"></head><body>${fallbackMsg}</body></html>`;
}
}
module.exports = { prepareHtmlForConversion };