我正在尝试将 React 组件转换为 pdf,但没有成功。
我有一个名为“automatic-report.js”的文件:出于演示目的,我有两个名为“printDocument()”的函数。一个使用 html2canvas,另一个使用 dom-to-image。
...
import html2canvas from 'html2canvas';
import JSpdf from 'jspdf';
//import domToImage from 'dom-to-image'
class AutomaticReport extends Component {
componentDidMount() {
this.printDocument = this.printDocument.bind(this);
...
}
printDocument() { //with html2canvas
const input = document.getElementById('divToPrint');
html2canvas(input)
.then((canvas) => {
const imgData = canvas.toDataURL('image/png');
const pdf = new JSpdf();
pdf.addImage(imgData, 'PNG', 0, 0);
pdf.save('download.pdf');
})
;
}
printDocument() { //with html2canvas
const input = document.getElementById('elementId');
domtoimage.toPng(input)
.then((dataUrl) => {
const pdf = new jsPDF();
const width = pdf.internal.pageSize.width;
const height = pdf.internal.pageSize.height;
pdf.addImage(dataUrl, 'PNG', 0, 0, width, height);
pdf.save('download.pdf');
})
.catch((error) => {
console.error('something went wrong!', error);
});
}
render() {
panelContent = (
<Panel title="Report" header={true} href={panelStyle}>
<div className="row">
...
<div className="col-md-6">
<div style={{height: 100, width: 100}}>
<img className="img-responsive" src={this.client.picture_url}/>
</div>
</div>
..
<div className="row">
<RefrigerationPieChart />
<RegenerativeBrakingPieChart />
<VehicleTable />
...
</div>
</panel>);
return (
<div
id="divToPrint"
style={{
width: '20cm',
minHeight: '29.7cm',
border: '1px #D3D3D3 solid',
borderRadius: '5px',
background: 'white',
boxShadow: '0 0 5px rgba(0, 0, 0, 0.1)',
size: 'A4',
margin: 'auto'
}}>
{panelContent}
</div>
);
}
两个图书馆都没有正确打印 pdf。这里打印 3 张:
html2canvas - 不显示图像,无论是外部 css。仅内联 css。
dom-to-imag - 虽然 css os 可以,但 pdf 模糊并且无法打印图像。
有谁能帮我弄清楚如何使用这两个库之一正确转换?
最佳答案
你非常接近,试试这个方法。 我正在使用 html2canvas 和 pdf maker
// Generate the pdf based on a component
printToPdf = () => {
html2canvas(document.getElementById("print_to_pdf")).then(canvas => {
var data = canvas.toDataURL();
var pdfExportSetting = {
content: [
{
image: data,
width: 500
}
]
};
pdfMake.createPdf(pdfExportSetting).download("test_file.pdf");
});
};
关于javascript - 将 React 组件转换为 pdf 没有成功(html2canvas 和 dom-to-image),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50066243/