reactjs - 如何打印反应条形码组件
问题描述
我正在尝试打印由 react-barcode 创建的条形码。
我试过使用这个问题和这个问题中描述的方法,但我似乎无法打印条形码。
这可能是因为 react-barcode 正在渲染 SVG。我也尝试过react-to-print和react-easy-print,但它们似乎也让我失望了。
我也希望使条形码可下载,但似乎没有任何效果。我下面的代码是我到目前为止所得到的。
从'react'导入反应,{组件};从'react-barcode'导入条码;
class App extends Component {
state= {
value:''
}
onChange=(e)=>{
this.setState({value:e.target.value})
}
onClick=(e)=>{
// LOGIC TO PRINT BARCODE COMES HERE
}
render() {
const { value } = this.state;
return (
<div className="App">
<input type="text" onChange={this.onChange} value={value} />
<BarCode
value={value}
/>
<button onClick={this.onClick}>Print Barcode</button>
</div>
);
}
}
export default App;
解决方案
这是我使用的,它对我有用。您将需要 html2canvas。
我将为此使用 React 钩子,如果您愿意,可以随意将其转换为基于类的组件。
const App=(props)=>{
const [value,setValue] = React.useState('');
const wrapper_ref = React.useRef();
const onChange=(e)=>{
setValue(e.target.value)
}
const onClick=(e)=>{
const opt = {
scale: 4
}
const elem = wrapper_ref.current;
html2canvas(elem, opt).then(canvas => {
const iframe = document.createElement('iframe')
iframe.name = 'printf'
iframe.id = 'printf'
iframe.height = 0;
iframe.width = 0;
document.body.appendChild(iframe)
const imgUrl = canvas.toDataURL({
format: 'jpeg',
quality: '1.0'
})
const style=`
height:100vh;
width:100vw;
position:absolute;
left:0:
top:0;
`;
const url = `<img style="${style}" src="${imgUrl}"/>`;
var newWin = window.frames["printf"];
newWin.document.write(`<body onload="window.print()">${url}</body>`);
newWin.document.close();
});
}
return (
<div className="App">
<input type="text" onChange={onChange} value={value} />
{/**This wrapper is important*/}
<div ref={wrapper_ref}>
<BarCode
value={value}
/>
</div>
<button onClick={onClick}>Print Barcode</button>
</div>
);
}
export default App;
这会起作用
推荐阅读
- iframe - &ytp-pause-overlay=0 不再有效
- mysql - 事务不持久 - 带有 Hibernate 的 Spring MVC
- jdbc - TNS:在 NSWMARKER 数据包中收到错误的数据类型
- git - 如何在 Git 中删除远程引用?
- python - 我通过使用 python beautifulsoup 提交帖子请求来获取医生链接
- python - 如何切换x和y轴?
- typescript - IDE 以 TypeScript 格式识别 Cucumber 步骤
- asp.net-mvc - 在 DropDownListFor html 帮助程序中选择默认值不起作用 - ASP .NET MVC
- java - 线程“主”java.lang.IndexOutOfBoundsException 中的 Netbeans 异常:索引:2,大小:2
- python - 单击时 Tkinter 窗口崩溃,可能是由于无限循环。Python 3.7.1