UNPKG

legal-markdown-js

Version:

Node.js implementation of LegalMarkdown for processing legal documents with markdown and YAML - Complete feature parity with Ruby version

77 lines 2.88 kB
import { AlignmentType, Document, Footer, Header, PageNumber, PageOrientation, Packer, Paragraph, TextRun, } from 'docx'; import { adaptCssToDocxStyles } from './docx/css-style-adapter.js'; import { convertHtmlToDocxBlocks, createDefaultNumbering } from './docx/html-to-docx.js'; const PAGE_SIZES = { A4: { width: 11906, height: 16838 }, Letter: { width: 12240, height: 15840 }, Legal: { width: 12240, height: 20160 }, }; /** * Generate a DOCX Blob from HTML and CSS strings - browser-safe. * * Does not touch the filesystem. CSS is accepted as a string instead * of a file path. Returns a Blob that can be downloaded directly via * URL.createObjectURL. */ export async function generateDocxBuffer(html, css, options = {}) { const stylePreset = adaptCssToDocxStyles(css); const blocks = await convertHtmlToDocxBlocks(html, { styles: stylePreset, includeHighlighting: false, basePath: '', }); const header = new Header({ children: [new Paragraph({ children: [new TextRun('')] })], }); const footer = new Footer({ children: [ new Paragraph({ alignment: AlignmentType.RIGHT, children: [ new TextRun('Pg: '), new TextRun({ children: [PageNumber.CURRENT] }), new TextRun(' / '), new TextRun({ children: [PageNumber.TOTAL_PAGES] }), ], }), ], }); const selectedFormat = options.format ?? 'A4'; const pageDims = PAGE_SIZES[selectedFormat] ?? PAGE_SIZES.A4; const size = options.landscape ? { width: pageDims.height, height: pageDims.width, orientation: PageOrientation.LANDSCAPE } : { width: pageDims.width, height: pageDims.height, orientation: PageOrientation.PORTRAIT }; const margins = { top: 1440, right: 1440, bottom: 1440, left: 1440, header: 720, footer: 720, gutter: 0, }; const document = new Document({ title: options.title, description: options.title, styles: stylePreset.styles, numbering: createDefaultNumbering(stylePreset), sections: [ { properties: { page: { size, margin: margins } }, headers: { default: header }, footers: { default: footer }, children: blocks, }, ], }); const base64 = await Packer.toBase64String(document); const binaryStr = atob(base64); const bytes = new Uint8Array(binaryStr.length); for (let i = 0; i < binaryStr.length; i++) { bytes[i] = binaryStr.charCodeAt(i); } return new Blob([bytes], { type: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document', }); } //# sourceMappingURL=docx-browser.js.map