0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

jsPDFで日本語が文字化けする問題を解消する方法

Posted at

こんにちは、hidepon4649 です。
jsPDF で日本語データが文字化けしてハマったのでメモします。

事象

  • JavaScript ライブラリ jsPDF を使用して PDF を生成する際に、日本語を含むテキストが文字化けした。
  • jsPDF は文字を描画するためにフォントを必要としますが、デフォルトで日本語フォントが含まれていないようです。

解決策

結論から申しますと、以下2点で解決します。

  1. フォント登録
  2. フォント指定

それぞれの手順を説明します。

1.フォント登録

1-1. フォント取得

  • 日本語対応フォント取得します。(例:NotoSansJP-Regular.ttf)
  • Google Fonts でダウンロード
    画面上部の「Get font」ボタン押下
  • ダウンロードした「Noto_Sans_JP.zip」を展開
  • 展開した資材の「NotoSansJP-Regular.ttf」が今後の作業対象となります。

1-2. base64 形式へ変換

  • 下記 getbase64.js ファイルを作成し、「NotoSansJP-Regular.ttf」と同じフォルダに配置する。
// getbase64.js
const fs = require("fs");

const fontFilePath = "./NotoSansJP-Regular.ttf"; // 元のフォントファイル
const outputFilePath = "./NotoSansJP-Regular-base64.txt"; // 出力先

fs.readFile(fontFilePath, (err, data) => {
  if (err) {
    console.error("フォントファイルの読み込みに失敗しました:", err);
    return;
  }

  const base64Data = data.toString("base64");
  fs.writeFile(outputFilePath, base64Data, (err) => {
    if (err) {
      console.error("Base64ファイルの書き込みに失敗しました:", err);
      return;
    }
    console.log("Base64変換が完了しました!ファイル:", outputFilePath);
  });
});
  • getbase64.js を実行する。base64 形式の「NotoSansJP-Regular-base64.txt」が出力されます。

1-3. base64 データをコードに登録

  • [NotoSansJP-Regular-base64.js]ファイルを作成します。
// NotoSansJP-Regular-base64.js

const NotoSansJP = "Base64データ"; // "Base64データ"の部分に「NotoSansJP-Regular-base64.txt」の中身を貼り付けます。
export default NotoSansJP;

2. フォント指定

  1. jsPDF でフォント指定
// アプリケーションプログラム
import jsPDF from "jspdf";
import "jspdf-autotable";
import NotoSansJP from "./NotoSansJP-Regular-base64.js"; // パスはご自身の環境に合わせて下さい。

const doc = new jsPDF();

// フォントを登録
doc.addFileToVFS("NotoSansJP-Regular.ttf", NotoSansJP);
doc.addFont("NotoSansJP-Regular.ttf", "NotoSansJP", "normal");
doc.setFont("NotoSansJP");

// 日本語を含むPDFを作成
doc.text("備考: テストデータ", 10, 10);

// テーブル作成時にもフォントを指定
doc.autoTable({
  head: [["ID", "備考"]],
  body: [[1, "サンプルデータ"]],
  startY: 20,
  styles: { font: "NotoSansJP" }, // フォントを指定
});

// PDFを出力
doc.save("sample.pdf");

以上

誰かのお役に立てれば幸いです。

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?