Take screenshot of React app and generate it as PDF

16,721

Solution 1

For anyone reading this pdfkit can also generate pdfs in the browser...nice!

You'll need to check out pdfkit website and specifically I only got it to work using the browser releases for pdfkit and blob-stream

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

My code looked like

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()

Solution 2

How about a combination of:

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

and

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

From the canvas provided by html2canvas, you can convert it to an image with .toDataUrl() and then feed that into jsPDF with the .addImage() method which wants a base64 image.

Share:
16,721
Michaela
Author by

Michaela

Front-end dev and JS enthusiast committed to make things pretty and functional at the same time. Currently in love with ReactJS and its composable nature.

Updated on June 14, 2022

Comments

  • Michaela
    Michaela almost 2 years

    I'd like to generate a PDF from my React App, the easiest way would probably be to take a screenshot of the current state of my app / ideally a div and save it as PDF...I just don't seem to be able to find the best way how to do it.

    Any ideas?

  • Michaela
    Michaela about 7 years
    that sounds like a good idea...just not sure how to include libraries as such into my reactjs app...bit of a newbie :)
  • Sam Foot
    Sam Foot about 7 years
    No problem, If you are using webpack both are available on npm: html2canvas jspdf If you are just including React on the page both have CDN links on the links above.
  • Shivek Khurana
    Shivek Khurana almost 7 years
    I just posted a detailed answer about the same here. Hope it helps.
  • Aleksej Shovgenja
    Aleksej Shovgenja almost 6 years
    There is a problem with jsPDF wich I bumped into. The addImage method do its stuff in sync manner and the whole app just hangs. And it can't be moved into web worker because it relies on the DOM. It's not very user-friendly. So I used html2canvas on the client and pdfkit on the backend to solve the similar task. It's pretty much pain in the ass in either case though.
  • A.com
    A.com over 5 years
    In the context of a react app (think react-router-dom route page), what happens for in "render your doc"?
  • user3472360
    user3472360 almost 4 years
    How do you download the "browser releases" of pdfkit and blob-stream?