npm i officegen
index.js
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 |
const officegen = require('officegen'); const fs = require('fs'); // Create a new Word document (docx) let docx = officegen('docx'); // Set up the document for adding content docx.on('finalize', function(written) { console.log('Word document created with ' + written + ' bytes.'); }); docx.on('error', function(err) { console.log(err); }); // Add a title or heading let pObj = docx.createP(); pObj.addText('Officegen Word Document Example', { bold: true, font_size: 18, color: 'blue' }); pObj.addLineBreak(); // Add a paragraph with some regular text pObj = docx.createP(); pObj.addText('This is a simple paragraph with some text in a Word document generated using Node.js and Officegen.'); // Add another paragraph with formatted text pObj = docx.createP(); pObj.addText('This text is in bold and green.', { bold: true, color: 'green' }); pObj.addLineBreak(); pObj.addText('And this is a regular sentence following the bold text.'); // Add an image to the document pObj = docx.createP(); pObj.addText('Here is an image inserted below:'); pObj.addLineBreak(); pObj.addImage('path_to_your_image.jpg', { cx: 400, cy: 300 }); // Set image size (in EMUs) // Save the document to a file const out = fs.createWriteStream('example.docx'); docx.generate(out); // Handle completion of file generation out.on('close', function() { console.log('The Word document has been successfully created as example.docx!'); }); |
Explanation of the Code:
- Import Required Libraries:
officegen
: To create the.docx
file.fs
: For file system operations (to save the generated document).
- Create a New Word Document:
let docx = officegen('docx');
initializes a new.docx
document.
- Add Text to the Document:
- The
createP()
method creates a new paragraph, andaddText()
adds text to that paragraph. - You can format the text using options like
{ bold: true, color: 'blue', font_size: 18 }
.
- The
- Add an Image:
addImage('path_to_your_image.jpg', { cx: 400, cy: 300 });
adds an image to the Word document. You can adjust the size of the image using thecx
(width) andcy
(height) options (in English Metric Units, or EMUs).- Make sure to replace
'path_to_your_image.jpg'
with the actual file path of the image you want to add.
- Save the Word Document:
- The document is saved to a file called
example.docx
usingfs.createWriteStream('example.docx')
. - The
docx.generate(out)
method generates the document, andout.on('close')
ensures the file is saved properly.
- The document is saved to a file called