React实现打印word
使用React实现打印Word文档
在React中实现打印Word文档功能,可以通过以下几种方法实现:
方法一:使用第三方库react-to-print
安装react-to-print库:
npm install react-to-print
在组件中使用:
import React, { useRef } from 'react';
import { useReactToPrint } from 'react-to-print';
const WordPrintComponent = () => {
const componentRef = useRef();
const handlePrint = useReactToPrint({
content: () => componentRef.current,
});
return (
<div>
<div ref={componentRef}>
{/* 这里放置Word文档内容 */}
<h1>Word文档标题</h1>
<p>文档内容...</p>
</div>
<button onClick={handlePrint}>打印文档</button>
</div>
);
};
export default WordPrintComponent;
方法二:使用window.print()原生方法
创建一个可打印的组件:
const PrintableComponent = () => {
const handlePrint = () => {
window.print();
};
return (
<div>
<div className="print-content">
{/* Word文档内容 */}
<h1>文档标题</h1>
<p>文档正文内容...</p>
</div>
<button onClick={handlePrint}>打印</button>
</div>
);
};
添加CSS样式控制打印效果:
@media print {
body * {
visibility: hidden;
}
.print-content, .print-content * {
visibility: visible;
}
.print-content {
position: absolute;
left: 0;
top: 0;
}
}
方法三:使用docx.js生成Word文档
安装docx.js库:
npm install docx
创建并下载Word文档:
import { Document, Paragraph, TextRun, Packer } from "docx";
const generateWordDoc = async () => {
const doc = new Document({
sections: [{
children: [
new Paragraph({
children: [
new TextRun("Word文档标题"),
],
}),
new Paragraph({
children: [
new TextRun("文档内容..."),
],
}),
],
}],
});
const blob = await Packer.toBlob(doc);
const url = URL.createObjectURL(blob);
const link = document.createElement('a');
link.href = url;
link.download = 'document.docx';
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
};
方法四:使用模板引擎生成Word
使用html-docx-js将HTML转换为Word:
npm install html-docx-js
实现代码:
import htmlDocx from 'html-docx-js';
const convertToWord = () => {
const html = `
<h1>Word文档标题</h1>
<p>文档内容...</p>
`;
const converted = htmlDocx.asBlob(html);
const url = URL.createObjectURL(converted);
const link = document.createElement('a');
link.href = url;
link.download = 'document.docx';
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
};
注意事项
- 打印样式需要通过CSS的@media print规则进行控制
- 生成Word文档时注意浏览器兼容性问题
- 复杂文档建议使用专业库如docx.js处理
- 打印前可添加页面设置选项(方向、边距等)







