docx.js로 HTML을 Word 문서에 쉽게 삽입하기
발행: (2025년 12월 12일 오후 06:57 GMT+9)
4 min read
원문: Dev.to
Source: Dev.to
빠른 시작
npm에서 라이브러리를 설치하세요:
npm install html-docxjs-compiler docx
최신 버전은 docx ^9.5.0와 호환됩니다.
기본 예제
import { transformHtmlToDocx } from 'html-docxjs-compiler';
import { Document, Packer } from 'docx';
import * as fs from 'fs';
async function createDocument() {
const html = `
## My Document
This is a paragraph with **bold** and *italic* text.
- First item
- Second item
`;
// Transform HTML to DOCX elements
const elements = await transformHtmlToDocx(html);
// Create a document with the elements
const doc = new Document({
sections: [{ children: elements }],
});
// Generate and save the document
const buffer = await Packer.toBuffer(doc);
fs.writeFileSync('output.docx', buffer);
}
createDocument();
자세한 예제
다음 데모는 리스트를 생성하고, 요소 스타일을 적용하며, 다양한 HTML 태그를 처리하는 방법을 보여줍니다.
const { transformHtmlToDocx } = require('../dist/index');
const { Document, Packer } = require('docx');
const { WORD_NUMBERING_CONFIGURATION } = require('./config');
const fs = require('fs');
const path = require('path');
async function runBasicDemo() {
console.log('Running Basic Demo...\n');
const html = `
## Welcome to HTML-DOCX Compiler
This is a **basic demo** showing how to convert HTML to DOCX format.
## Features
The package supports:
- Headings (H1 through H6)
- **Bold** and *italic* text
- Underlined and strikethrough text
- Superscript2 and subscript2
- Links like [GitHub](https://github.com)
## Ordered Lists
You can also create numbered lists:
- First item
- Second item
- Third item
## Text Formatting
This text is centered.
This text is right-aligned.
This text is blue.
This text has a yellow background.
You can also use div elements to group content.
Multiple paragraphs within a div work perfectly.
`;
try {
console.log('Converting HTML to DOCX elements...');
const docxElements = await transformHtmlToDocx(html);
const doc = new Document({
numbering: WORD_NUMBERING_CONFIGURATION,
sections: [{ children: docxElements }],
});
const buffer = await Packer.toBuffer(doc);
const outputDir = path.join(__dirname, 'output');
if (!fs.existsSync(outputDir)) {
fs.mkdirSync(outputDir, { recursive: true });
}
const outputPath = path.join(outputDir, 'basic-demo.docx');
fs.writeFileSync(outputPath, buffer);
console.log('✅ Success! Document created at:', outputPath);
} catch (error) {
console.error('❌ Error:', error.message);
console.error(error.stack);
}
}
runBasicDemo();
생성된 문서는 다음과 같습니다:
하나의 문서에 여러 HTML 블록
const headerHtml = `
## Invoice #123
`;
const bodyHtml = `
Thank you for your purchase.
`;
const footerHtml = `
This is an automated document.
`;
const header = compileHtmlToComponents(headerHtml);
const body = compileHtmlToComponents(bodyHtml);
const footer = compileHtmlToComponents(footerHtml);
const doc = new Document({
sections: [
{
children: [
...header,
...body,
...footer,
],
},
],
});
손쉽게 이미지 추가
이미지 삽입도 라이브러리를 사용하면 간단합니다.
const {
transformHtmlToDocx,
HttpImageDownloadStrategy,
ImageDownloadStrategyManager,
} = require('../dist/index');
const { Document, Packer } = require('docx');
const fs = require('fs');
const path = require('path');
async function runAdvancedDemo() {
console.log('Running Advanced Demo...\n');
const html = `
## Image adding
**Image example:**

## Important Notes
⚠️ **Confidential:** This document contains sensitive information
and should not be distributed outside the organization.
`;
try {
console.log('Setting up configuration...');
const strategyManager = new ImageDownloadStrategyManager();
strategyManager.addStrategy(new HttpImageDownloadStrategy());
const config = { strategyManager };
console.log('Converting HTML to DOCX elements...');
const docxElements = await transformHtmlToDocx(html, config);
const doc = new Document({
sections: [
{
properties: {
page: {
margin: {
top: 1440, // 1 inch = 1440 twips
right: 1440,
bottom: 1440,
left: 1440,
},
},
},
children: docxElements,
},
],
creator: 'HTML-DOCX Compiler',
});
const buffer = await Packer.toBuffer(doc);
const outputPath = path.join(__dirname, 'advanced-demo.docx');
fs.writeFileSync(outputPath, buffer);
console.log('✅ Document with images created at:', outputPath);
} catch (error) {
console.error('❌ Error:', error);
}
}
runAdvancedDemo(); 