Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Take screenshot of React app and generate it as PDF

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?

like image 779
Michaela Avatar asked Apr 13 '17 10:04

Michaela


People also ask

How do I download a screen as a PDF in React JS?

Making a Screenshot from the DOM (HTML => Canvas => Image => PDF) Here's another straightforward solution: just take a screenshot of the page or element and convert it to a PDF document with Canvas and image transformation: html2canvas for creating a screenshot from HTML and generating Canvas from it.

How do I create a React component PDF?

Generating a pdf on the client side is a 3 step process :Convert the DOM into svg. Convert the svg into png. Convert the png into pdf.

How do I save an Image in React?

Any images that you import in your React components should be stored close to where they are used (preferably in the same directory). Any images that you do not import in your React components (e.g. favicons ) should be stored in your public/ directory, e.g. under a favicons/ folder.


2 Answers

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()
like image 172
dorriz Avatar answered Oct 22 '22 07:10

dorriz


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.

like image 34
Sam Foot Avatar answered Oct 22 '22 08:10

Sam Foot