我是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;
Javascript with HTML: https://www.youtube.com/watch?v=HVuHr-Q7HEs
React 在 html 标签中没有 "classID" 属性,它作为 props 传递给div,这永远不会被解析。className 之所以被实现,只是因为它是 JS 中的保留字,也许你需要用"id"属性替换你的"classID",它会起作用
附言:JQuery 是一种不好的做法,当你所需要的只是 DOM 操作时。 javascript 有 document.getElementById() 并且不需要依赖关系
P.p.s. 给你的小提示是 "pdfToHTML(){}" 可以替换为 lambda 作为 "pdfToHTML = () => {}",你的函数将从类实例中得到 "this",绑定将被删除,构造函数将变得无用。
的方式
- 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.
html2canvas
http://html2canvas.hertzen.com/和jspdf
https://github.com/parallax/jsPDF 库从 React Js 创建/下载 PDF 文件,如下所示 https://stackoverflow.com/a/45017234/8339172
下面是将 html2canvas
库和jspdf
库与功能组件一起使用的示例:
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>
);
};
参考资料:https://www.robinwieruch.de/react-component-to-pdf/