LoginSignup
8
11

More than 3 years have passed since last update.

docx.jsを使って、ブラウザでMS Wordファイルを書き出せるようになるまで

Posted at

概要

Wordファイル(.docx)を書き出すためのライブラリ docx.js をブラウザで動かすための手順。
https://docx.js.org/

公式にブラウザでも動くとなっているのですが、ドキュメントのサンプルが基本、node.jsベースになっており、私のスキル不足も相まって意外とハマったので、全手順をメモしておきます。

ポイント

  • node.jsでは、最終的なファイル書き出しは、fsモジュールを使うらしいが、ブラウザでは動かないので、FileSaver.jsを使う

手順

npmの初期化。対話式で聞かれる設定は適当に設定します。ただし、ここで名前をdocxとしないこと。後に名前の競合で進めなくなります。

npm init

docxのインストール

npm install docx --save-dev

webpackのインストール

npm install webpack webpack-cli --save-dev

HTMLの準備
ざっくり以下のような感じで、webpackでこれから書き出すdocx_browser.jsFileSaverをロードし、generate()というメソッドをボタンで呼ぶようにする。

index.html
<html>
    <head>
        <meta charset="utf-8">
        <title>docx sample</title>
        <!-- script by webpack -->
        <script src="docx_browser.js"></script>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/FileSaver.js/1.3.8/FileSaver.js"></script>
    </head>
    <body>
        <h1>docx sample</h1>
        <button onclick="generate()">Generate DOCX</button>
    </body>
</html>

jsの準備
https://docx.js.org/#/?id=basic-usage
こちらを参考にするが、以下を変更(変更箇所コメントいれています。)

  • 1行目の import * as fs from "fs"; は削除
  • ファイル書き出し部分をブラウザ用に書き換え
  • 全体をfunction generate()で囲み、HTML上からgenerate()呼び出すために、グローバル関数にする命令を追加
./src/main.js
//不要コメントアウト
//import * as fs from "fs";
import { Document, Packer, Paragraph, TextRun } from "docx";

//全体をfunctionで囲む
function generate() {
    // Create document
    const doc = new Document();

    // Documents contain sections, you can have multiple sections per document, go here to learn more about sections
    // This simple example will only contain one section
    doc.addSection({
        properties: {},
        children: [
            new Paragraph({
                children: [
                    new TextRun("Hello World"),
                    new TextRun({
                        text: "Foo Bar",
                        bold: true,
                    }),
                    new TextRun({
                        text: "\tGithub is the best",
                        bold: true,
                    }),
                ],
            }),
        ],
    });

    // Used to export the file into a .docx file
    //ブラウザ動作用に書き換え
    /*
    Packer.toBuffer(doc).then((buffer) => {
            fs.writeFileSync("My Document.docx", buffer);
    });
    */
    //以下ブラウザ動作用
    Packer.toBlob(doc).then((blob) => {
        saveAs(blob, "output.docx");
        console.log("Document created successfully");
    });

}

//グローバル関数にする
window.generate = generate;

webpackでビルドする

npx webpack --mode development ./src/main.js --output docx_browser.js

以上です。

実行結果

ブラウザで表示
image.png

書き出されたWordファイル
image.png

動作環境

  • IE11は動きません。

おまけ

いくつか同名の別ライブラリがあり、それを取り扱った日本語記事もあるのですが、ここで紹介したものが唯一メンテナンスされています。
メンテが止まっている別ライブラリ
https://github.com/MrRio/DOCX.js
https://github.com/stephen-hardy/DOCX.js

他に使えそうなライブラリ(まだ試していない)
https://github.com/guigrpa/docx-templates
テンプレートファイルを書き換えるという方法で生成する。

8
11
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
8
11