How to make responsive pdf in react js using react-to-print library?

1.5k Views Asked by At
  [demo][1]

    [1]: https://codesandbox.io/s/react-to-print-rzdhd

I'm using react-to-print library to generate pdf from html. But the problem is that when I try to generate pdf in my mobile(small screen size), it does not work for me however, it works in desktop(large screen size) view.

1

There are 1 best solutions below

7
On

This package uses window.print(), which won't work on mobile devices. You can use the following workaround:

  class Example extends React.Component {
    printPDF(e) {
      return new Promise((resolve: any) => {
        e.preventDefault()
        var ua = navigator.userAgent.toLowerCase()
        var isAndroid = ua.indexOf('android') > -1 //&& ua.indexOf("mobile");
        if (isAndroid) {
          // https://developers.google.com/cloud-print/docs/gadget
          var gadget = new cloudprint.Gadget()

          gadget.openPrintDialog()
        } else {
          window.print()
        }
        resolve(true)
      })
    }

    render() {
      return (
        <div>
          <ReactToPrint
            trigger={() => <button>Print this out!</button>}
            print={e => this.printPDF(e)} // HANDLE PRINT FUNCTION
            content={() => this.componentRef}
          />
          <ComponentToPrint ref={el => (this.componentRef = el)} />
        </div>
      )
    }
  }