IgxGrid ではバージョン 21 にて PDF へのエクスポート機能が導入されました。
以下のように IgxGridToolbarExporterComponent より機能を有効に設定すると、IgxGrid のツールバーに「PDF へのエクスポート」オプションを表示させることができます。

<igx-grid-toolbar>
    <igx-grid-toolbar-exporter [exportPDF]="true">
    </igx-grid-toolbar-exporter>
</igx-grid-toolbar>

PDF へのエクスポートにはデフォルトでラテン文字のみをサポートする Helvetica フォントが使用されており、そのままエクスポートを行うと日本語文字は文字化けした状態で表示されてしまいます。

日本語など、ラテン文字以外の文字をエクスポートする場合は IgxPdfExporterOptions の customFont プロパティより日本語をサポートするTTF(TrueType Font)を設定します。
フォントデータは TTF ファイルの内容を Base64 エンコードした文字列として指定する必要があります。

ここでは、Noto Sans JP を使用して日本語文字を文字化けせずにエクスポートするようにします。

Noto Sans JP の TTF ファイルはこちらのサイトよりダウンロードすることができます。

https://fonts.google.com/noto/specimen/Noto+Sans+JP

ダウンロードした Noto Sans JP の TTF ファイルを src/assets/fonts フォルダに配置しておきます。

上記の TTF ファイルを読み込み、Base64 形式の文字列に変換するメソッドを定義します。

private fontBase64: string | null = null;

constructor() {
  this.loadFont();
}
  
private async loadFont() {
  const response = await fetch('/assets/fonts/NotoSansJP-Regular.ttf');
  const buffer = await response.arrayBuffer();
  const bytes = new Uint8Array(buffer);
  let binary = '';
  for (let i = 0; i < bytes.length; i++) {
    binary += String.fromCharCode(bytes[i]);
  }
  this.fontBase64 = btoa(binary);
}

IgxGridToolbarExporterComponent の exportStarted イベントを実装し、IgxPdfExporterOptions の customFont プロパティに読み込んでおいた Noto Sans JP のフォントデータを設定します。

<igx-grid-toolbar>
  <igx-grid-toolbar-actions>
	<igx-grid-toolbar-exporter ..... [exportPDF]="true" (exportStarted)="onExportStarted($event)"></igx-grid-toolbar-exporter>
  </igx-grid-toolbar-actions>
</igx-grid-toolbar>
protected onExportStarted(event: IgxExporterEvent) {
  const options = event.options;
  if (options instanceof IgxPdfExporterOptions && this.fontBase64) {
    options.customFont = {
	  name: 'NotoSansJP',
	  data: this.fontBase64,
    };
  }
}

日本語が文字化けせずに表示されました。

Tagged:

製品について

Ignite UI for Angular