- reactでコンポーネントを一回画像にしてそのままPDF生成してダウンロードする機能
- react-pdfは使わない
- コンポーネントを画像にしてその画像をpdfとして出力する方法
いろいろ検索してようやく実装した機能。 誰かのためになるのではと思い共有
import * as React from 'react'
import Button from '@atoms/Button'
function WithPDFAbleContent({ children, elementId, onClick }){
return (
<>
<Button onClick={() => onClick()}>PDFをダウンロードする</Button>
<div id={elementId}>
{ children }
</div>
</>
)
}
export default WithPDFAbleContent;
import html2canvas from 'html2canvas'
(window as any).html2canvas = html2canvas;
// https://github.com/MrRio/jsPDF/issues/1225
import * as jsPDF from 'jspdf'
import WithPDFAbleContent from '@molecules/WithPDFAbleContent'
function SomeComponent () { // 適当
/// 実装
onClickDownloadForPDF = (elementId: string, id: string) => () => {
const input = document.getElementById(elementId); // idを走査する
html2canvas(input, { scale: 2.5 }).then(canvas => {
const imgData = canvas.toDataURL('image/svg', 1.0); // 一度svgにする。pngでもjpegでもok
let pdf = new jsPDF(); // pdfを生成
pdf.addImage(imgData, 'SVG', 5, 10, canvas.width / 18, canvas.height / 18); // ここが大変だった
pdf.save(`${id}.pdf`); // ダウンロードが開始される // 実際はuserを受け取り名前.pdfにしてあげている
})
}
}
<WithPDFAbleContent elementId="sheet" onClick={this.onClickDownloadForPDF("sheet", "1")} >
<SomeComponent />
</WithPDFAbleContent>
childrenの中のどこかでこれは出力したくないなと思うところがあるかもしれない。
例えばボタンとか、ナビゲーションとか。
そのような無視したいコンポーネントに data-html2canvas-ignore="true
を付与してあげればいい
<IgnoreComponent data-html2canvas-ignore="true">
- ページをまたがる高さがあるコンポーネントの場合未実装
- https://stackoverflow.com/questions/28193487/how-to-use-addhtml-function-in-jspdf
- parallax/jsPDF#1225
- niklasvh/html2canvas#1593
- https://jsfiddle.net/vigneshncc/ncv56vwf/
- http://amaraimusi.sakura.ne.jp/sample/js/js_pdf/js_pdf_smp1.html
- parallax/jsPDF#695
- https://stackoverflow.com/questions/49916947/html2canvas-and-jspdf-genereted-blank-pdf?rq=1
- parallax/jsPDF#476
- https://stackoverflow.com/questions/27558516/prevent-some-elements-from-being-rendered-canvas
- http://html2canvas.hertzen.com/getting-started
- https://stackoverflow.com/questions/29578721/image-in-pdf-cut-off-how-to-make-a-canvas-fit-entirely-in-a-pdf-page
- https://github.com/MrRio/jsPDF