Not able to change the QR code size in react-to-print

1.3k Views Asked by At

I am using https://www.npmjs.com/package/react-qr-code to generate QR code on my website.

I want to change the size of this qr code when I print this qr code in PDF file. can I change the size of qr code in pdf file without changing the size on react page? I have tried changing the size using state but issue is that updating the state also updates the size on DOM container.

I am using https://github.com/gregnb/react-to-print to print the qr code.

import QRCode from 'react-qr-code';
import ReactToPrint from 'react-to-print';


  const getPageMargins = () => {
    return `@page { margin: '1000px' '10' '10 '10' !important; }`;
  };

  const onBeforeGetContent = () => {
    setSize(200);
    setIsLoading(true);
    return Promise.resolve();
  };

  const onBeforePrint = () => {
    setSize(100);
    return Promise.resolve();
  };

  const onAfterPrint = () => {
    setSize(100);
    setIsLoading(true);
    return Promise.resolve();
  };

// this is what I am rendering
     <div ref={QRRef}>
      <QRCode
          value={`{ "_id": "${unit.id}" }`}
          size={size}
      />
      <p className="hide-unit-id">{unit.id}</p>
      </div>
      <ReactToPrint
          pageStyle={getPageMargins}
          onBeforePrint={onBeforePrint}
          onBeforeGetContent={onBeforeGetContent}
          onAfterPrint={onAfterPrint}
          trigger={() => (
              <PrinterFilled />
            )}
          content={() => QRRef.current}>
      </ReactToPrint>

Any help is much appreciated. Thanks in advance.

2

There are 2 best solutions below

0
On

Better cleaner solution for this would be to use Print CSS. Adjust the size of the targeted element by setting CSS width and height properties, in following example I have set the width and height of the QR code's svg element to 50%

const pageStyle = `
@media print {
    @page{
      size: A4;
    }
    svg {
      width:50%;
      height: 50%;
    }
}
  `

and passing pageStyle property to useReactToPrint hook

const handlePrint = useReactToPrint({
   content: () => qrRef.current,
   pageStyle,
})
5
On

Try this with onAfterPrint

const promiseRef = useRef(null);
const [size, setSize] = useState(10);

useEffect(() => {
  // Check both that there is a promise to resolve AND that the state has actually changed
  if (promiseRef.current && size === 100) {
    // Resolve the promise, causing react-to-print to continue
    promiseRef.current();
  }
}, [promiseRef.current, size]);

const onBeforeGetContent = () => {
  return new Promise((resolve) => {
    // This is async: we don't know when React will actually make the state change
    setSize(100);
    promiseRef = resolve;
  });
};

const onAfterPrint = () => {
  setSize(10);
};