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?
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.
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.
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.
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()
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With