12
11

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

TypeScriptでPDFを生成して、FirebaseのStorageに格納する

Posted at

Gakuです。
PDF系の生成処理が実装できるようになると、幅が広がるかなと思って勉強中です。
そんな中、PDFKitの初期設定で結構ハマったので、やり方記載しておきます。

パッケージのinstall

TypeScriptになるので、PDFKit本体と型定義パッケージをインストールしておきます。

install
npm install pdfkit
npm install @types/pdfkit

使い方

sample.ts
import * as pdf from 'pdfkit';
import * as fs from 'fs';

export default function(){
    const stream = fs.createWriteStream('test.pdf');

    const doc = new pdf({ margin: 20 });
    doc.pipe(stream);
    doc.registerFont('regular', 'fonts/mplus-1p-regular.ttf'); // ここらへんはお好きなfontを指定
    doc.registerFont('bold', 'fonts/mplus-1p-bold.ttf');

    // title
    doc.font('bold').fontSize(25)
    .text('テ ス ト');

    doc.end();
};

このような感じで実装することで、プロジェクト内にPDFが生成されます。
注意点としては、PDFKitのデフォルトfontだと日本語が文字化けしてしまうので、日本語対応のfontを指定して使うようにしましょう。
記述方法はPDFKitに詳しく記載されております。

Firebase Storageに格納

PDFKitでは、doc.read()でBufferが取得できるのですが、日本語対応のfontを指定した場合、なぜか「壊れたPDFドキュメント」が生成されます。
なので、以下のようにstreamを取得し、doc.pipeで指定する形で実装します。
(S3等に保存する場合でも、同じような手順になるかと思います。)

sample2.ts
import * as pdf from 'pdfkit';
import * as fs from 'fs';
import * as admin from 'firebase-admin';

export default function(){
    const filename =  'test.pdf';
    const file = admin.storage().bucket().file(filename);
    const stream = file.createWriteStream({
        metadata: {
            contentType: 'application/pdf',
        },
    });

    const doc = new pdf({ margin: 20 });
    doc.pipe(stream);
    doc.registerFont('regular', 'fonts/mplus-1p-regular.ttf'); // ここらへんはお好きなfontを指定
    doc.registerFont('bold', 'fonts/mplus-1p-bold.ttf');

    // title
    doc.font('bold').fontSize(25)
    .text('テ ス ト');

    doc.end();
};

これで、firebase storageに生成したPDFが格納されます🎉

おわりに

PDFの生成が実装できるようになると、紙ベースでのやり取りが中心な日本社会ではいろいろ捗るかと思います。
面倒な書類作成業務はどんどんプログラム化して、楽していきましょう(/・ω・)/

12
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
12
11

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?