从HTML文本React创建PDF文件

Lon*_*gdo 10 reactive-programming reactjs

我是react-redux的初学者.

我尝试创建一个函数,如使用Javascript将html文本导出为pdf,并且它与html一起使用,但是当我将它应用于反应组件时,它不起作用.

这是我的代码:

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;
Run Code Online (Sandbox Code Playgroud)

带有HTML的JavaScript:https://www.youtube.com/watch?v = HVuHr-Q7HEs

小智 5

React 在 html 标签中没有“classID”属性,它作为 props 传递给 div,永远不会被解析。className 之所以被实现,是因为它是 JS 中的保留字,也许你只需要用“id”属性替换“classID”,它就可以工作

Ps 当您需要的只是 DOM 操作时,JQuery 是一种不好的做法。javascript 有 document.getElementById() 并且不需要依赖

Pps 给您的小提示是“pdfToHTML(){}”可以替换为 lambda,如“pdfToHTML = () => {}”,并且您的函数将从类实例中获取“this”,绑定将被删除,构造函数将变为无用。