首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何打印react-barcode组件

如何打印react-barcode组件
EN

Stack Overflow用户
提问于 2019-01-18 20:30:51
回答 1查看 1.7K关注 0票数 0

我正在尝试打印由react-barcode创建的条形码。

我尝试过使用this questionthis中描述的方法,但似乎无法打印条形码。

这可能是因为SVG是由react-barcode呈现的。我也尝试过react-to-printreact-easy-print,但它们似乎也让我失败了。

我也希望使条形码可下载,但似乎没有任何work.The代码,我有下面的代码,我到目前为止。

从‘react’导入React,{ BarCode };从‘react-barcode’导入条形码;

代码语言:javascript
复制
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;
EN

回答 1

Stack Overflow用户

发布于 2019-06-13 07:49:15

这就是我使用的方法,它对我很有效。您将需要html2canvas。

我将使用React钩子来实现这一点,如果你愿意的话,你可以把它转换成基于类的组件。

代码语言:javascript
复制
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;

这将会起作用

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/54254092

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档