首页 > 解决方案 > 如何打印反应条形码组件

问题描述

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

我试过使用这个问题这个问题中描述的方法,但我似乎无法打印条形码。

这可能是因为 react-barcode 正在渲染 SVG。我也尝试过react-to-printreact-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;

标签: reactjspdfprinting

解决方案


这是我使用的,它对我有用。您将需要 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;

这会起作用


推荐阅读