Create PDF file from HTML text React
Asked Answered
N

3

11

I am beginner in react-redux.

I trying create a function like exporting a html text to pdf with Javascript and it works with html, but when I apply it to react component, it doesn't work.

This is my code:

import React from 'react';

class App extends React.Component {
  constructor(props){
    super(props);
    this.pdfToHTML=this.pdfToHTML.bind(this);
  }

  pdfToHTML(){
    var pdf = new jsPDF('p', 'pt', 'letter');
    var source = $('#HTMLtoPDF')[0];
    var specialElementHandlers = {
      '#bypassme': function(element, renderer) {
        return true
      }
    };

    var margins = {
      top: 50,
      left: 60,
      width: 545
    };

    pdf.fromHTML (
      source // HTML string or DOM elem ref.
      , margins.left // x coord
      , margins.top // y coord
      , {
          'width': margins.width // max width of content on PDF
          , 'elementHandlers': specialElementHandlers
        },
      function (dispose) {
        // dispose: object with X, Y of the last line add to the PDF
        // this allow the insertion of new lines after html
        pdf.save('html2pdf.pdf');
      }
    )
  }

  render() {
    return (
      <div>
        <div classID="HTMLtoPDF">
          <center>
            <h2>HTML to PDF</h2>
           <p>Lorem ipsum dolor sit amet, consectetur adipisicing </p>
          </center>
        </div>
        <button onClick={this.pdfToHTML}>Download PDF</button>
      </div>
    );
  } 
}

export default App;

Javascript with HTML: https://www.youtube.com/watch?v=HVuHr-Q7HEs

Nonpareil answered 8/1, 2017 at 3:21 Comment(6)
<div classID="HTMLtoPDF"> ? Shouldn't it be <div id="HTMLtoPDF">Allodial
thanks. it works. I thought classID and id are the same. But Why doesn't classID work.?Nonpareil
The style is not showing upSenhauser
@Nonpareil classID is the HTML attribute classid which applies to <Object> only, has nothing to do with CSSHooker
Just to answer the question about why "classID" doesn't work... It's because "classID" doesn't exist. "class" is used when you want to select multiple tags with the same distinction, whereas "id" is used when you only want to select ONLY ONE thing. You must've mixed the two up to make "classID".Ejaculate
It seems that jsPDF package has deprecated fromHTML method and this solution is no longer of use.Jabot
D
5

React don't have "classID" property in html tags, it's passed to div as props, which will never be resolved. className was only implemented because it's reserved word in JS, perhabs you need to replace your "classID" by only "id" property and it will work

P.s. JQuery is bad practice when all what you need is DOM manipulation. javascript have document.getElementById() and dependency is not needed

P.p.s. small tip for you is "pdfToHTML(){}" can be replaced to lambda as "pdfToHTML = () => {}", and your function will have "this" from class instance, binding will be removed and constructor will become useless.

Des answered 26/1, 2018 at 12:1 Comment(1)
changing classID to id doesn't work. You get the following error: `Error: addImage does not support files of type 'UNKNOWN', please ensure that a plugin for 'UNKNOWN' support is added.Jabot
G
0

You could use the html2canvas http://html2canvas.hertzen.com/ and jspdf https://github.com/parallax/jsPDF libraries to create/download a PDF file from React Js like this answer https://mcmap.net/q/194512/-generating-a-pdf-file-from-react-components

Here is a sample of using the html2canvas and jspdf libraries with the functional component:

import html2canvas from 'html2canvas';
import { jsPDF } from 'jspdf';

const App = () => {
  const printRef = React.useRef();

  const handleDownloadPdf = async () => {
    const element = printRef.current;
    const canvas = await html2canvas(element);
    const data = canvas.toDataURL('image/png');

    const pdf = new jsPDF();
    const imgProperties = pdf.getImageProperties(data);
    const pdfWidth = pdf.internal.pageSize.getWidth();
    const pdfHeight =
      (imgProperties.height * pdfWidth) / imgProperties.width;

    pdf.addImage(data, 'PNG', 0, 0, pdfWidth, pdfHeight);
    pdf.save('print.pdf');
  };

  return (
    <div>
      <button type="button" onClick={handleDownloadPdf}>
        Download as PDF
      </button>

      <div>I will not be in the PDF.</div>
      <div ref={printRef}>I will be in the PDF.</div>
    </div>
  );
};

Reference: https://www.robinwieruch.de/react-component-to-pdf/

Guildsman answered 21/7, 2022 at 16:9 Comment(0)
F
-1

This is my way

- You can use that package in pure javascript file or server 
side(Backend)
- When you use it with the ReactJS(Frontend), it doesn't work.
- So I didn't use that.
- With html2canvas and jsPDF, I could build pdf.
- First build component, then save(download) it.
Faena answered 19/4, 2018 at 11:30 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.