作業環境
・Angualr8.0
・Windows10
・Vscode
ライブラリのインストール
# ライブラリのインストール $ npm install jspdf@1.4.1 --save $ npm install html2canvas --save $ npm install @types/jspdf --save $ npm install @types/html2canvas --save # コンポ-ネントの作成 $ ng generate component pdf-sample
<>
import { NgModule } from "@angular/core";
import { Routes, RouterModule } from "@angular/router";
~~~~
import { PdfSampleComponent } from "./pdf-sample/pdf-sample.component";//これを追加!
const routes: Routes = [
  { path: "pdf-generater", component: PdfSampleComponent },//これを追加!
  
];
pdf出力機能の実装
<index.html>
<head> ~~~~ <script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.4.1ze/jspdf.min.js"></script> ~~~~ </head>
<pdf-sample.component.ts>
import { Component, OnInit, ElementRef, ViewChild } from "@angular/core";
import * as jspdf from "jspdf";
import html2canvas from "html2canvas";
declare var jsPDF: any;
@Component({
  selector: "app-pdf-sample",
  templateUrl: "./pdf-sample.component.html",
  styleUrls: ["./pdf-sample.component.css"],
})
export class PdfSampleComponent implements OnInit {
  @ViewChild("screen", { static: true }) screen: ElementRef;
  @ViewChild("canvas", { static: true }) canvas: ElementRef;
  @ViewChild("downloadLink", { static: true }) downloadLink: ElementRef;
  captureScreen() {
    const data = document.getElementById("contentToConvert");
    html2canvas(data).then((canvas) => {
      // Few necessary setting options
      const imgWidth = 308;
      const imgHeight = (canvas.height * imgWidth) / canvas.width + 50;
      const contentDataURL = canvas.toDataURL("image/png");
      const pdf = new jspdf("p", "mm", "a4"); // A4 size page of PDF
      const position = 0;
      pdf.addImage(contentDataURL, "PNG", 0, position, imgWidth, imgHeight);
      pdf.save("MYPdf.pdf"); // Generated PDF
    });
  }
  constructor() {}
  ngOnInit() {}
  htmlToPdf() {
    const doc = new jsPDF("letter");
    const ta = document.getElementById("pdfSink");
    doc.fromHTML(
      ta,
      0,
      0,
      {
        // options
      },
      setTimeout(function () {
        doc.save(`fileName`);
      }, 3000)
    );
  }
}
ViewChildの書き方がAngular6.0以降変わっているので注意。
doc.saveはdoc.fromHTMLの中に組み込んで同期的に処理する方法にせずそのまま記述すると非同期処理になっているので、画像など出力に時間が掛かる画面をPDF出力する際にタイムアウトとなり白紙のPDFが出力されてしまうので、このように記述する必要がある。
<pdf-sample.component.html>
<div id="contentToConvert"> <h2>職務経歴書</h2> <h3>【職務概要】</h3> <p>○○○○○○○○○○○○○○○○○○○○○○</p> <p>○○○○○○○○○○○○○○○○○○○○○○</p> <h3>【職務経歴】</h3> <p>AngularUniversityに通いながらボディーガードをやっていました</p> <p>○○○○○○○○○○○○○○○○○○○○○○</p> <p>○○○○○○○○○○○○○○○○○○○○○○</p> <h3>【期間】</h3> <p>1999〜2020</p> <p>○○○○○○○○○○○○○○○○○○○○○○</p> <h3>【自己アピール】</h3> <p>○○○○○○○○○○○○○○○○○○○○○○</p> <br /><br /> </div> <button (click)="captureScreen()">PDFをダウンロード</button>
参照:https://tech.windii.jp/frontend/angular/html-to-pdf
  
  
  
  
コメント