获取React应用程序的屏幕截图并将其生成为PDF

时间:2017-04-13 10:17:55

标签: javascript reactjs pdf-generation screenshot

我想从我的React应用程序生成PDF,最简单的方法可能是截取当前我的应用程序状态的屏幕截图/理想情况下为div并将其另存为PDF ...我只是不这样做似乎能够找到最佳方法。

有什么想法吗?

3 个答案:

答案 0 :(得分:1)

如何组合:

html2canvas:https://html2canvas.hertzen.com/

jsPDF:https://parall.ax/products/jspdf

在html2canvas提供的画布中,您可以使用.toDataUrl()将其转换为图像,然后使用需要base64图像的.addImage()方法将其提供给jsPDF。

答案 1 :(得分:1)

对于阅读此pdfkit的任何人,也可以在浏览器中生成pdf ...很好!

您需要访问pdfkit网站,特别是我只能使用pdfkit和blob-stream的浏览器版本来使它工作

https://github.com/devongovett/pdfkit/releases https://github.com/devongovett/blob-stream/releases

我的代码看起来像

import PDFDocument from 'pdfkit'
import BlobStream from 'blob-stream'
import FileSaver from 'file-saver'

let doc = new PDFDocument()
    let stream = doc.pipe(BlobStream())
    addHeader(doc, 'My Report.....')
    doc.moveDown(0.5).fontSize(8)
   // render you doc
   // then add a stream eventListener to allow download
stream.on('finish', ()=>{
      let blob = stream.toBlob('application/pdf')
      FileSaver.saveAs(blob, 'myPDF.pdf')

    })
    doc.end()

答案 2 :(得分:0)

使用html2canvasjsPDF创建了一个react组件,该组件将div及其子组件导出为pdf和Image

react组件定义如下

        import React from 'react'
        import html2canvas from 'html2canvas'
        import { jsPDF } from "jspdf";
    
        class Exporter extends React.Component {
           constructor(props) {
             super(props)
           } 
    
        export =(type, name)=>{
    
        html2canvas(document.querySelector(`#capture`)).then(canvas => {
          let dataURL = canvas.toDataURL('image/png');
    
          if (type === 'pdf') {
            const pdf = new jsPDF({
              orientation: "landscape",
              unit: "in",
              format: [14, 10]
            });
    
            pdf.addImage(dataURL, 'PNG', .6, .6);
            pdf.save(`${name}.pdf`);
    
          } else if (type === 'png') {
            var link = document.createElement('a');
            link.download = `${name}.png`;
            link.href = dataURL;
            link.click();
          }
        });
     }
     render() { 
        return (
          <div>
            <button onClick={()=>this.export("pdf", "my-content")}></button>
            <div id={`capture`} >
              Content to export as pdf/png
              {this.props.children} //any child Component render here will be exported as pdf/png
            </div>
          </div>
        )
      }
    }

export default Exporter