Generating a PDF file from React Components

后端 未结 8 1945
無奈伤痛
無奈伤痛 2020-12-02 10:45

I have been building a polling application. People are able to create their polls and get data regarding the question(s) they ask. I would like to add the functionality to l

相关标签:
8条回答
  • 2020-12-02 11:04

    You can use ReactDOMServer to render your component to HTML and then use this on jsPDF.

    First do the imports:

    import React from "react";
    import ReactDOMServer from "react-dom/server";
    

    then:

    var doc = new jsPDF();
    doc.fromHTML(ReactDOMServer.renderToStaticMarkup(this.render()));
    doc.save("myDocument.pdf");
    

    Prefer to use:

    renderToStaticMarkup

    instead of:

    renderToString

    As the former include HTML code that react relies on.

    0 讨论(0)
  • 2020-12-02 11:05

    You can use ReactPDF

    Lets you convert a div into PDF with ease. You will need to match your existing markup to use ReactPDF markup, but it is worth it.

    0 讨论(0)
  • 2020-12-02 11:11

    I used jsPDF and html-to-image.

    You can check out the code on the below git repo.

    Link

    If you like, you can drop a star there✌️

    0 讨论(0)
  • 2020-12-02 11:15

    React-PDF is a great resource for this.

    It is a bit time consuming converting your markup and CSS to React-PDF's format, but it is easy to understand. Exporting a PDF and from it is fairly straightforward.

    To allow a user to download a PDF generated by react-PDF, use their on the fly rendering, which provides a customizable download link. When clicked, the site renders and downloads the PDF for the user.

    Here's their REPL which will familiarize you with the markup and styling required. They have a download link for the PDF too, but they don't show the code for that here.

    0 讨论(0)
  • 2020-12-02 11:18

    you can user canvans with jsPDF

    import jsPDF from 'jspdf';
    import html2canvas from 'html2canvas';
    
     _exportPdf = () => {
    
         html2canvas(document.querySelector("#capture")).then(canvas => {
            document.body.appendChild(canvas);  // if you want see your screenshot in body.
            const imgData = canvas.toDataURL('image/png');
            const pdf = new jsPDF();
            pdf.addImage(imgData, 'PNG', 0, 0);
            pdf.save("download.pdf"); 
        });
    
     }
    

    and you div with id capture is:

    example

    <div id="capture">
      <p>Hello in my life</p>
      <span>How can hellp you</span>
    </div>
    
    0 讨论(0)
  • 2020-12-02 11:19

    Rendering react as pdf is generally a pain, but there is a way around it using canvas.

    The idea is to convert : HTML -> Canvas -> PNG (or JPEG) -> PDF

    To achieve the above, you'll need :

    1. html2canvas &
    2. jsPDF

    import React, {Component, PropTypes} from 'react';
    
    // download html2canvas and jsPDF and save the files in app/ext, or somewhere else
    // the built versions are directly consumable
    // import {html2canvas, jsPDF} from 'app/ext';
    
    
    export default class Export extends Component {
      constructor(props) {
        super(props);
      }
    
      printDocument() {
        const input = document.getElementById('divToPrint');
        html2canvas(input)
          .then((canvas) => {
            const imgData = canvas.toDataURL('image/png');
            const pdf = new jsPDF();
            pdf.addImage(imgData, 'JPEG', 0, 0);
            // pdf.output('dataurlnewwindow');
            pdf.save("download.pdf");
          })
        ;
      }
    
      render() {
        return (<div>
          <div className="mb5">
            <button onClick={this.printDocument}>Print</button>
          </div>
          <div id="divToPrint" className="mt4" {...css({
            backgroundColor: '#f5f5f5',
            width: '210mm',
            minHeight: '297mm',
            marginLeft: 'auto',
            marginRight: 'auto'
          })}>
            <div>Note: Here the dimensions of div are same as A4</div> 
            <div>You Can add any component here</div>
          </div>
        </div>);
      }
    }

    The snippet will not work here because the required files are not imported.

    An alternate approach is being used in this answer, where the middle steps are dropped and you can simply convert from HTML to PDF. There is an option to do this in the jsPDF documentation as well, but from personal observation, I feel that better accuracy is achieved when dom is converted into png first.

    Update 0: September 14, 2018

    The text on the pdfs created by this approach will not be selectable. If that's a requirement, you might find this article helpful.

    0 讨论(0)
提交回复
热议问题