简体   繁体   中英

How to add images with npm 'docx' package to word document?

I found this npm package docx that helps to generate word document files with javascript: https://github.com/dolanmiu/docx

I want to add an image to my doc but I can't seem to figure out how, or what's happening. I have spent quite a few hours on this, but the documentation isn't as comprehensive enough for a noob like me.

Here is what I tried:

Attempt #1:

import React, { useState } from "react";
import * as fs from "fs";
import moment from "moment";
import { Document, Packer, Paragraph, Media } from "docx";
import { saveAs } from "file-saver";
const GenerateDoc = () => {
    const doc = new Document();
    const logo = Media.addImage(doc, fs.readFileSync("myImage.png"), 200, 200); // ERROR HERE: "fs.readFileSync is not a function
    doc.addSection({children: [new Paragraph(logo)]});
    const download = () => {
        // download function...
    };
    return (
        <div>
            <button onClick={() => {download()}}>Generate</button>
        </div>
    );
};
export default GenerateDoc;

Output #1: TypeError: fs__WEBPACK_IMPORTED_MODULE_2__.readFileSync is not a function

Attempt #2:

import React, { useState } from "react";
import moment from "moment";
import { Document, Packer, Paragraph, Media } from "docx";
import { saveAs } from "file-saver";
const GenerateDoc = () => {
    const doc = new Document();
    const logo = doc.createImage("myImage.png"); // ERROR HERE: doc.createImage is not a function
    doc.addSection({children: [new Paragraph(logo)]});
    const download = () => {
        // download function...
    };
    return (
        <div>
            <button onClick={() => {download()}}>Generate</button>
        </div>
    );
};
export default GenerateDoc;

Output #2: TypeError: doc.createImage is not a function

What is working:

import React, { useState } from "react";
import moment from "moment";
import { Document, Packer, Paragraph, Media } from "docx";
import { saveAs } from "file-saver";
const GenerateDoc = () => {
    const doc = new Document();
    const logo = Media.addImage(doc); // returns a blank image in the word document since I didn't specify a file.
    doc.addSection({
        children: [new Paragraph(logo)]
    });
    const download = () => {
        // download function...
    };
    return (
        <div>
            <button onClick={() => {download()}}>Generate</button>
        </div>
    );
};
export default GenerateDoc;

Here are the documentations:
- https://docx.js.org/#/usage/images
- https://runkit.com/dolanmiu/docx-demo5
- https://github.com/dolanmiu/docx/wiki/Images

Any help is GREATLY appreciated!!

Thanks in advance!!

Edit:

Attempt #3:

import React, { useState } from "react";
import moment from "moment";
import { Document, Packer, Paragraph, Media } from "docx";
import { saveAs } from "file-saver";
const GenerateDoc = () => {
    const doc = new Document();
    const logo = Media.addImage(doc, '../myImage.png'); // ERROR: InvalidCharacterError: Failed to execute 'atob' on 'Window': The string to be decoded is not correctly encoded.
    doc.addSection({
        children: [new Paragraph(logo)]
    });
    const download = () => {
        // download function...
    };
    return (
        <div>
            <button onClick={() => {download()}}>Generate</button>
        </div>
    );
};
export default GenerateDoc;

Output #3: InvalidCharacterError: Failed to execute 'atob' on 'Window': The string to be decoded is not correctly encoded.

DOCX author here,

Here is an example of docx with images in React (base64 and with URL request from the internet):

https://stackblitz.com/edit/react-ts-qdqu7z

One way is by loading the file by import, converting to blob, and use ImageRun.

 import LetterHead from '../images/letterhead.jpg'; ... const export = async () => { const letterHead = await fetch(LetterHead); const doc = new Document({ sections: [ ... new ImageRun ({ data : await letterHead.blob() ... ... Packer.toBlob(doc)... }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM