我想从我的 React 应用程序生成一个 PDF,最简单的方法可能是截取我的应用程序的当前状态/理想情况下是div 并将其另存为 PDF...我似乎找不到最好的方法。
有什么想法吗?
对于任何阅读此pdfkit的人也可以在浏览器中生成pdf...好!
您需要查看pdfkit网站,特别是我只能使用pdfkit和blob-stream的浏览器版本来工作
https://github.com/devongovett/pdfkit/releaseshttps://github.com/devongovett/blob-stream/releases
我的代码看起来像
import PDFDocument from 'pdfkit'
import BlobStream from 'blob-stream'
import FileSaver from 'file-saver'
let doc = new PDFDocument()
let stream = doc.pipe(BlobStream())
addHeader(doc, 'My Report.....')
doc.moveDown(0.5).fontSize(8)
// render you doc
// then add a stream eventListener to allow download
stream.on('finish', ()=>{
let blob = stream.toBlob('application/pdf')
FileSaver.saveAs(blob, 'myPDF.pdf')
})
doc.end()
如何组合:
HTML2canvas: https://html2canvas.hertzen.com/
和
JSPDF: https://parall.ax/products/jspdf
从html2canvas提供的画布中,您可以将其转换为带有.toDataUrl((的图像,然后使用.addImage((方法将其输入jsPDF,该方法需要base64图像。
使用 html2canvas 和 jsPDF 创建了一个 react 组件,将div 及其子组件导出为 pdf 和 Image
反应组件定义如下
import React from 'react'
import html2canvas from 'html2canvas'
import { jsPDF } from "jspdf";
class Exporter extends React.Component {
constructor(props) {
super(props)
}
export =(type, name)=>{
html2canvas(document.querySelector(`#capture`)).then(canvas => {
let dataURL = canvas.toDataURL('image/png');
if (type === 'pdf') {
const pdf = new jsPDF({
orientation: "landscape",
unit: "in",
format: [14, 10]
});
pdf.addImage(dataURL, 'PNG', .6, .6);
pdf.save(`${name}.pdf`);
} else if (type === 'png') {
var link = document.createElement('a');
link.download = `${name}.png`;
link.href = dataURL;
link.click();
}
});
}
render() {
return (
<div>
<button onClick={()=>this.export("pdf", "my-content")}></button>
<div id={`capture`} >
Content to export as pdf/png
{this.props.children} //any child Component render here will be exported as pdf/png
</div>
</div>
)
}
}
export default Exporter