
Docxtemplater
템플릿에서 Word DOCX를 생성 및 관리하는 무료 Node.js 라이브러리
간단한 템플릿 기반 접근 방식을 통한 JavaScript API로 Word DOCX, XLSX 문서를 동적으로 생성, 편집 및 조작할 수 있게 해주는 선도적인 오픈 소스 Node.js 라이브러리.
Docxtemplater란?
오늘날 빠르게 변화하는 디지털 시대에 효율성은 특히 문서 관리에서 가장 중요합니다. 사용자가 계약서를 초안하고, 보고서를 생성하며, 개인화된 편지를 작성할 때, 문서 생성을 자동화할 수 있는 신뢰할 수 있는 도구가 있다면 시간과 자원을 크게 절약할 수 있습니다. 바로 이러한 요구를 충족시키는 강력한 라이브러리인 Docxtemplater가 있습니다. 이 라이브러리는 템플릿 기반 문서 생성을 단순화하여 Word 문서 템플릿 안의 플레이스홀더를 실제 데이터로 교체함으로써 최종 출력 문서를 만들 수 있게 합니다.
Docxtemplater는 근본적으로 데이터를 미리 정의된 템플릿과 병합하여 동적인 Word, Excel, PowerPoint 문서를 생성하고 관리할 수 있게 해주는 강력한 오픈 소스 JavaScript 라이브러리입니다. OpenXML 포맷을 활용하여 사용자의 문서 구조와 내용을 세밀하게 제어할 수 있으며, 런타임에 실제 데이터로 교체될 플레이스홀더를 삽입할 수 있게 합니다.
Docxtemplater는 소프트웨어 개발자가 문서 생성을 손쉽게 자동화할 수 있도록 돕는 다목적 라이브러리입니다. 템플릿과 데이터 병합의 힘을 활용하면 문서 작업 흐름을 간소화하고 생산성을 크게 향상시킬 수 있습니다. 라이브러리를 올바르게 사용하면 개발자는 특정 요구에 맞는 동적 문서를 쉽게 생성할 수 있습니다. 문서 생성 작업을 자동화하든 보고서를 개인화하든, Docxtemplater는 여러분의 도구 상자에 유용한 도구가 됩니다.
Docxtemplater 설치 방법은?
Docxtemplater를 설치하려면 JavaScript용 패키지 매니저 npm을 사용할 수 있습니다. 성공적인 설치를 위해 다음 명령을 사용하십시오.
npm을 통해 Docxtemplater 설치
npm install --save docxtemplater pizzipNode.js에서 템플릿을 이용한 Word 문서 생성
오픈 소스 Docxtemplater 라이브러리는 템플릿을 사용해 Microsoft Word DOCX 문서를 쉽게 생성할 수 있게 해줍니다. 개발자는 키-값 쌍을 포함한 객체를 전달하여 동적 데이터를 템플릿에 주입하고, 플레이스홀더를 실제 데이터로 교체하여 최종 출력 문서를 만들 수 있습니다. 다음 예제는 개발자가 기존 템플릿을 로드하고 Node.js 환경에서 Word 문서를 생성하는 방법을 보여줍니다.
Node.js 내부에서 템플릿을 사용해 Word 문서를 생성하는 방법은?
const fs = require('fs');
const Docxtemplater = require('docxtemplater');
// Load the template
const content = fs.readFileSync('template.docx', 'binary');
const doc = new Docxtemplater(content);
// Set data to fill placeholders
const data = {
firstName: 'John',
lastName: 'Doe'
};
// Replace placeholders with actual data
doc.setData(data);
// Render the document
doc.render();
// Save the generated document
const output = fs.writeFileSync('output.docx', doc.getZip().generate({type: 'nodebuffer'}));
console.log('Document generated successfully!');
Node.js 앱에 커스텀 함수 및 필터 추가
Docxtemplater 라이브러리의 커스텀 함수와 필터는 템플릿 내에서 데이터를 조작하고 특정 작업을 수행하는 고급 기능을 제공합니다. 기본적인 플레이스홀더 교체를 넘어 라이브러리의 기능을 확장하여 동적 콘텐츠 생성과 복잡한 데이터 처리를 가능하게 합니다. 템플릿 내에서 데이터를 조작하거나 특정 작업을 수행하기 위해 커스텀 함수와 필터를 정의할 수 있습니다. 아래 예제는 개발자가 쇼핑 카트 아이템의 총 가격을 계산하는 커스텀 함수를 구현하고 통화 값을 포맷하는 필터를 적용하는 방법을 보여줍니다.
커스텀 함수를 이용해 쇼핑 카트의 아이템 가격을 계산하고 필터로 통화 값을 포맷하는 방법은?
const fs = require('fs');
const Docxtemplater = require('docxtemplater');
// Define custom function to calculate total price
function calculateTotal(items) {
return items.reduce((total, item) => total + item.price * item.quantity, 0);
}
// Define custom filter to format currency
function formatCurrency(value) {
return '$' + value.toFixed(2); // Format as dollars with 2 decimal places
}
// Load the template
const content = fs.readFileSync('template.docx', 'binary');
const doc = new Docxtemplater(content, {
parser: {
// Define custom tag for invoking functions
getFunction: function(tag) {
if (tag === 'calculateTotal') {
return calculateTotal;
}
},
// Define custom tag for applying filters
getFilter: function(tag) {
if (tag === 'currency') {
return formatCurrency;
}
}
}
});
// Set data with shopping cart items
const data = {
items: [
{ name: 'Product 1', price: 10, quantity: 2 },
{ name: 'Product 2', price: 20, quantity: 1 },
{ name: 'Product 3', price: 15, quantity: 3 }
]
};
// Replace placeholders with actual data
doc.setData(data);
// Render the document
doc.render();
// Save the generated document
const output = fs.writeFileSync('output.docx', doc.getZip().generate({ type: 'nodebuffer' }));
console.log('Document generated successfully!');
풍부한 서식 지원
오픈 소스 Docxtemplater는 간단한 템플릿 기반 접근 방식을 제공하여 Word 문서 생성 및 관리를 단순화합니다. Word 문서에서의 풍부한 서식 지원은 글꼴 스타일, 색상, 크기, 정렬 등 다양한 스타일 속성을 문서 내 여러 요소에 적용할 수 있는 능력을 의미합니다. 여기에는 텍스트, 표, 이미지, 단락, 섹션 서식, 리스트, 글머리표 및 기타 콘텐츠의 서식 지정이 포함되어 가독성과 시각적 매력을 높입니다. 아래 예제는 문서 내부의 텍스트 일부에 풍부한 서식을 적용하는 방법을 보여줍니다.
Node.js 애플리케이션에서 Docxtemplater를 사용해 텍스트에 풍부한 서식을 적용하는 방법은?
// Render the document with custom parser options for rich formatting
doc.render({
parser: {
// Custom tag for interpreting HTML-like tags for rich formatting
tagToken: function(tag) {
return {
tagName: tag.substring(1),
mode: 'open'
};
},
// Apply rich formatting based on tag names
commands: {
b: function(scope, context, tag) {
return {
type: 'applyRichText',
value: { b: true }
};
},
i: function(scope, context, tag) {
return {
type: 'applyRichText',
value: { i: true }
};
},
u: function(scope, context, tag) {
return {
type: 'applyRichText',
value: { u: true }
};
},
strike: function(scope, context, tag) {
return {
type: 'applyRichText',
value: { strike: true }
};
}
}
}
});
// Save the generated document
const output = fs.writeFileSync('output.docx', doc.getZip().generate({ type: 'nodebuffer' }));
console.log('Document generated successfully!');
