Muljayan
Muljayan

Reputation: 3886

How to print a react-barcode component

I am trying to print a barcode created by react-barcode.

I have tried using methods described in this question and this but i cant seem to print the barcodes.

This is probably because an SVG is being rendered by react-barcode. I have also tried react-to-print and react-easy-print but they seem to fail me too.

I also hope to make the barcode downloadable but nothing seems to work.The code i have below is what i have got so far.

import React, { Component } from 'react'; import BarCode from '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;

Upvotes: 1

Views: 3551

Answers (1)

OLATOMIDE
OLATOMIDE

Reputation: 103

This is what i used and it worked for me. You will need html2canvas.

I'll be using React hooks for this, feel free to convert it to class based component if you want.

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;

This would work

Upvotes: 2

Related Questions