LoginSignup
1
1

More than 1 year has passed since last update.

Vue3でpdfmakeの日本語化するときのvfs周りの問題対処

Posted at

結論

このgithub投稿のorderでコンポーネントをimportする

環境

  • Win11
  • Laravel Jetstream with Inertia.js
  • Vue3

詰まるまでの過程

  • 公式を見てインストールしました。その際コンポーネントは公式にもある通り、
hogehoge.vue
<script setup>
import pdfMake from "pdfmake/build/pdfmake";
import pdfFonts from "pdfmake/build/vfs_fonts";
pdfMake.vfs = pdfFonts.pdfMake.vfs;

を用いました。

  • 公式を参考に、游ゴシックをttfファイルに変換し、node_module/pdfmake直下にexamples/fontsというフォルダを作りそこにコピーし、node build-vfs.js "./examples/fonts"しました。
  • 生成されたbuild/vfs_fonts.jsの中身を見て、用意したttfファイルの名前を確認し、正しくbuildされたことが確認できました。
  • この時点では以下のようなコードとなっています。
hogehoge.vue
<script setup>
import pdfMake from "pdfmake/build/pdfmake";
import pdfFonts from "pdfmake/build/vfs_fonts";
pdfMake.vfs = pdfFonts.pdfMake.vfs;

pdfMake.fonts = {
    YuGothic: {
        normal: 'YuGothic-Regular-01.ttf',
        bold: 'YuGothic-Regular-01.ttf',
        italics: 'YuGothic-Regular-01.ttf',
        bolditalics: 'YuGothic-Regular-01.ttf'
    }
}

const defaultStyle = "YuGothic"

function exportPdf() {
    let text = [["hogehoge","hugahuga"]]
    let document = {
        content: [
            {
                table: {
                    widths: [100, 100],
                    body: text
                }
            },
        ],
        defaultStyle: {
            font:defaultStyle
        }
    }   
    pdfMake.createPdf(document).open();
}
</script>
  • 適当なボタンで関数を発火させたところ、Uncaught File 'YuGothic-Regular-01.ttf' not found in virtual file systemとコンソールに表示されました。
  • vfsにフォントが見つからないという趣旨ですが、VScodeのvite拡張機能を使っているため更新時にbuildされているし、このエラー文でググるとStackOverflowで見かけるpdfMake.vfs = pdfFonts.pdfMake.vfsの記述は既に済ませていました。

解決

最初に貼った、pdfFontsにdefault export出来ないという趣旨のIssueを眺めていたところ、Svelte環境におけるimportとして

import * as pdfFonts from  'pdfmake/build/vfs_fonts';
import pdfMake from "pdfmake";
pdfMake.vfs = pdfFonts.pdfMake.vfs

があり、その下に

Thank you! Doing this solved my build issue using vite bundler with a vue project
ありがとう!viteを使ったvueプロジェクトのbuild時の問題もこれで解決したよ。

とあったので自分も流用したら解決しました。
ポイントとしては先頭のimport * as pdfFonts from 'pdfmake/build/vfs_fonts';で、まずviteだと気付きにくいのですが手動でnpm run buildをしてみると、

"default" is not exported by "node_modules/pdfmake/build/vfs_fonts.js", imported by "resources/js/hogehoge.vue".

と表示され、defaultに関係するエラーが表示されています。 import * asとすることでこのエラーはなくすことが出来ます。
次の順序を逆にすることで動くことは原理が分からないので何とも言えませんが、公式Docsがたまに全くあてにならない(どころか、変な先入観を持たせて来るせいで足を引っ張る)ので気を付けるという勉強になりました。

1
1
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
1
1