Node.js OfficeGen Example to Create Word Docx Files & Add Text Images inside it Using Javascript

 

npm i officegen

 

 

index.js

 

 

 

 

Explanation of the Code:

 

  1. Import Required Libraries:
    • officegen: To create the .docx file.
    • fs: For file system operations (to save the generated document).
  2. Create a New Word Document:
    • let docx = officegen('docx'); initializes a new .docx document.
  3. Add Text to the Document:
    • The createP() method creates a new paragraph, and addText() adds text to that paragraph.
    • You can format the text using options like { bold: true, color: 'blue', font_size: 18 }.
  4. 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 the cx (width) and cy (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.
  5. Save the Word Document:
    • The document is saved to a file called example.docx using fs.createWriteStream('example.docx').
    • The docx.generate(out) method generates the document, and out.on('close') ensures the file is saved properly.

 

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply

Your email address will not be published. Required fields are marked *