上篇文章介绍了如何使用nodejs填充word模板,今天介绍一下哎浏览器端如何填充word模板。
<html>
<body>
<button onclick="generate()">Generate document</button>
</body>
<script src="https://cdnjs.cloudflare.com/ajax/libs/docxtemplater/3.19.10/docxtemplater.js"></script>
<script src="https://unpkg.com/pizzip@3.0.6/dist/pizzip.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/FileSaver.js/1.3.8/FileSaver.js"></script>
<script src="https://unpkg.com/pizzip@3.0.6/dist/pizzip-utils.js"></script>
<!--
Mandatory in IE 6, 7, 8 and 9.
-->
<!--[if IE]>
<script type="text/javascript" src="https://unpkg.com/pizzip@3.0.6/dist/pizzip-utils-ie.js"></script>
<![endif]-->
<script>
function loadFile(url,callback){
PizZipUtils.getBinaryContent(url,callback);
}
function generate() {
loadFile("https://docxtemplater.com/tag-example.docx",function(error,content){
if (error) { throw error };
// The error object contains additional information when logged with JSON.stringify (it contains a properties object containing all suberrors).
function replaceErrors(key, value) {
if (value instanceof Error) {
return Object.getOwnPropertyNames(value).reduce(function(error, key) {
error[key] = value[key];
return error;
}, {});
}
return value;
}
function errorHandler(error) {
console.log(JSON.stringify({error: error}, replaceErrors));
if (error.properties && error.properties.errors instanceof Array) {
const errorMessages = error.properties.errors.map(function (error) {
return error.properties.explanation;
}).join("\n");
console.log('errorMessages', errorMessages);
// errorMessages is a humanly readable message looking like this :
// 'The tag beginning with "foobar" is unopened'
}
throw error;
}
var zip = new PizZip(content);
var doc;
try {
doc=new window.docxtemplater(zip);
} catch(error) {
// Catch compilation errors (errors caused by the compilation of the template : misplaced tags)
errorHandler(error);
}
doc.setData({
first_name: 'John',
last_name: 'Doe',
phone: '0652455478',
description: 'New Website'
});
try {
// render the document (replace all occurences of {first_name} by John, {last_name} by Doe, ...)
doc.render();
}
catch (error) {
// Catch rendering errors (errors relating to the rendering of the template : angularParser throws an error)
errorHandler(error);
}
var out=doc.getZip().generate({
type:"blob",
mimeType: "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
}) //Output the document using Data-URI
saveAs(out,"output.docx")
})
}
</script>
</html>
这是直接放在浏览器中,我们通过cdn来引入所需要的库,如果是在现代web框架中,代码应该是这样的:
import PizZip from 'pizzip'
import Docxtemplater from 'docxtemplater'
import JszipUtil from 'jszip-utils'
import FileSave from 'file-saver'
//上面四个是需要用到的,通过npm i xxx即可安装
function fullWord(fileName, data) {
/**
* 文件放在public目录下,因此文件路径和文件名相同
*/
/** 将文件转为二进制 */
JszipUtil.getBinaryContent(fileName, function(err, res) {
if (err) {
console.error(err)
} else {
// 将文件转为zip文件
const pizZip = new PizZip(res)
// 创建Docxtemplater对象实例并添加zip文件
const docxtemplater = new Docxtemplater(pizZip)
// 设置填充内容
docxtemplater.setData(data)
// 进行内容填充
docxtemplater.render()
// 获取到要下载的文件
const out = docxtemplater.getZip().generate({
type: 'blob',
mimeType: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document'
})
// 进行下载
FileSave(out, fileName)
}
})
}
export { fullWord }
这里我们定义了一个方法,并将其导出。在前端将文件转化为2进制数据我们需要用到jszip-utils这个库,保存文件需要用到file-saver这个库。
参考:https://blog.csdn.net/qq_40716778/article/details/107567357
https://docxtemplater.readthedocs.io/en/latest/generate.html#browser
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。