web-dev-qa-db-ja.com

PDF HTMLテキストからファイルを作成React

私は、react-reduxの初心者です。

Javascriptを使用してhtmlテキストをpdfにエクスポートするような関数を作成しようとすると、htmlで機能しますが、reactコンポーネントに適用すると機能しません。

これは私のコードです:

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;

HTMLを使用したJavascript: https://www.youtube.com/watch?v=HVuHr-Q7HEs

10
Longdo

Reactにはhtmlタグに「classID」プロパティがありません。propとしてdivに渡されますが、これは解決されません。 classNameは、JSの予約語であるため、「classID」を「id」プロパティのみで置き換える必要があるため、実装されただけで、機能します

追伸必要なものがすべてDOM操作である場合、JQueryは悪い習慣です。 javascriptにはdocument.getElementById()があり、依存関係は必要ありません

P.p.s.あなたのための小さなヒントは、「pdfToHTML(){}」を「pdfToHTML =()=> {}」としてラムダに置き換えることができ、関数はクラスインスタンスから「this」を持ち、バインディングは削除され、コンストラクタは役に立たなくなります。

4

これが私のやり方です

- 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.
0
smartworld-dm