简体   繁体   中英

allowing user to export react web page as pdf

How do I allow users to export a customized react web page as pdf, image or share it using gmail. I created a template for a CV with editable components, and I'm trying to find a way for the user to export them as they are, so using jsPDF is not suitable.

You can ue html2canvas for converting your page to a canvas then you can conver the canvas to pdf or img.Advantage of using html2canvas is you won't miss any styles applied to the content.

here is a sample for generating img.

import html2canvas from 'html2canvas';
import { saveAs } from 'file-saver';
GetImg() {
    html2canvas(document.querySelector("#root")).then(canvas => {
      var img = canvas.toDataURL()
      saveAs(img, "pretty image.png");
    });
  }

for pdf you can use jspdf along with html2canvas. here is a sample

import * as jsPDF from 'jspdf';
getPdf(){
input= document.querySelector("#root")
html2canvas(input)
      .then((canvas) => {
        const imgData = canvas.toDataURL('image/png');
        const pdf = new jsPDF({
          orientation: 'landscape',
        });
        const imgProps= pdf.getImageProperties(imgData);
        const pdfWidth = pdf.internal.pageSize.getWidth();
        const pdfHeight = (imgProps.height * pdfWidth) / imgProps.width;
        pdf.addImage(imgData, 'PNG', 0, 0, pdfWidth, pdfHeight);
        pdf.save('download.pdf');
      });}

So basically you need to convert HTML and CSS into a pdf. Javascript doesn't have anything to do with the pdf, and React is javascript, so we need to extract the HTML actually.

What you could do is keep a ref on the wrapper element that wraps the CV, then do a ref.current.innerHTML to get the HTML code of your CV. Also get your CSS, and use jsPDF to convert the HTML and the CSS into a pdf.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM