【发布时间】:2018-10-08 12:37:27
【问题描述】:
我正在尝试将 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模糊,也不能打印图片。
谁能帮我弄清楚如何使用这两个库之一正确转换?
【问题讨论】:
标签: javascript reactjs pdf dom html2canvas