var officegen = require('officegen'); var fs = require('fs'); var path = require('path'); var docx = officegen('docx'); docx.on('finalize', function (written) { console.log('Finish to create Word file.\nTotal bytes created: ' + written + '\n'); }); docx.on('error', function (err) { console.log(err); }); // 添加目录 docx.createP(); docx.putPageBreak(); docx.createP().addText('目录', { bold: true, font_face: 'Arial', font_size: 14 }); docx.createP().addText('第一章', { hyperlink: 'chapter_1' }); docx.createP().addText('第二章', { hyperlink: 'chapter_2' }); docx.createP().addText('第三章', { hyperlink: 'chapter_3' }); // 添加正文 docx.putPageBreak(); docx.createP().addText('第一章', { anchor: 'chapter_1' }); docx.createP().addText('这是第一章的内容。'); // 添加页码 var pObj = docx.createP(); pObj.addText('第 '); pObj.addPageNumber(); pObj.addText(' 页'); var out = fs.createWriteStream(path.resolve(__dirname, 'output.docx')); out.on('error', function (err) { console.log(err); }); docx.generate(out);
const docx4js = require('docx4js'); const fs = require('fs'); const path = require('path'); const doc = docx4js.create(); doc.addParagraph(docx4js.createParagraph().addRun(docx4js.createRun().addText('第一章'))); doc.addParagraph(docx4js.createParagraph().addRun(docx4js.createRun().addText('这是第一章的内容。'))); doc.addParagraph(docx4js.createParagraph().addRun(docx4js.createRun().addText('第二章'))); doc.addParagraph(docx4js.createParagraph().addRun(docx4js.createRun().addText('这是第二章的内容。'))); doc.addParagraph(docx4js.createParagraph().addRun(docx4js.createRun().addText('第三章'))); doc.addParagraph(docx4js.createParagraph().addRun(docx4js.createRun().addText('这是第三章的内容。'))); doc.addTableOfContents(); doc.addPageNumber(); const out = fs.createWriteStream(path.resolve(__dirname, 'output.docx')); out.on('error', function (err) { console.log(err); }); doc.generate(out);
标签:docx,word,nodejs,docx4js,addText,createRun,createP,doc,页码 From: https://www.cnblogs.com/navysummer/p/17342139.html