Eddy Aguirre
Eddy Aguirre

Reputation: 83

Printing generated QR codes on a PDF file

I'm creating a ReactJS app that uses QR codes and I want to be able to print a PDF document with a batch of codes at once. I'm currently using both react-qr-svg to generate the codes and @react-pdf/renderer to create the document. The problem is that I haven't been able to show these QR Codes on the document.

First I tried using the Image tag from @react-pdf/renderer like this:

<Image
  src={<QRCode
    level="Q"
    style={{width: 256, marginBottom: 50 }}
    value={'hello world'}
  />}
/>

Whick of course didn't work, after that I tried to convert the SVG to a Data Buffer and had no results.

Is there any straightforward solution for this? Should I use other libraries for this project?

Upvotes: 8

Views: 18350

Answers (4)

IcyIcicle
IcyIcicle

Reputation: 765

The docs specify that Image supports promises of base64 strings. Source https://react-pdf.org/components#source-object

So, we can use the qrcode to generate it. I am using typescript here, so be sure to install @types/qrcode for this to work.

npm install qrcode @types/qrcode
import QRCode from "qrcode";
import { Image } from "@react-pdf/renderer";

export function QRCodeImage(props: { url: string }) {
  const urlPromise = QRCode.toDataURL(props.url);
  return <Image src={urlPromise} />;
}

Upvotes: 0

sergei
sergei

Reputation: 823

My solution does not write the initial svg to the DOM, instead it converts the react component to static markup. Then I parse that markup to use its properties in the Svg component that @react-pdf/renderer supports.

import React from 'react';
import { Text, View, Svg, Path } from '@react-pdf/renderer';
import { renderToStaticMarkup } from 'react-dom/server';
import ReactHtmlParser from 'react-html-parser';
import QRCode from 'qrcode.react';

const PdfWithQrCode = () => {
    const qrCodeComponent = (
        <QRCode
            value={ssf_id}
            renderAs="svg"
            size={80}
        />
    );

    const qrCodeComponentStaticMarkup = renderToStaticMarkup(qrCodeComponent);

    const parsedQrCodeSvg = parseQrCodeMarkup(qrCodeComponentStaticMarkup);
    if (! parsedQrCodeSvg) {
        return null;
    }

    return (
        <View>
            <Svg
                style={{ width: 50, height: 50 }}
                viewBox="0 0 29 29"
            >
                {parsedQrCodeSvg.props.children.filter(c => c.type === 'path').map((child, index) => (
                    <Path
                        key={index}
                        d={child.props.d}
                        fill={child.props.fill}
                    />
                ))}
            </Svg>
        </View>
    );
}

const parseQrCodeMarkup = (markup) => {
    let parsedQrCodeSvg = null;

    ReactHtmlParser(markup).forEach(el => {
        const { type } = el;
        if (type === 'svg') {
            parsedQrCodeSvg = el;
        }
    });

    return parsedQrCodeSvg;
};

export default PdfWithQrCode;

Upvotes: 1

Maksym Koshyk
Maksym Koshyk

Reputation: 563

I use qrcode.react with @react-pdf/renderer. First thing you need to do is to convert your QR canvas to base64

const qrCodeCanvas = document.querySelector('canvas');
const qrCodeDataUri = qrCodeCanvas.toDataURL('image/jpg', 0.3);

Then, pass base64 string (qrCodeDataUri) as a prop to your PDF component in source of @react-pdf/renderer image tag:

<Image source={ {uri: props.yourBase64Image} } />

Upvotes: 11

Alex L
Alex L

Reputation: 4241

Directly from the docs: https://www.npmjs.com/package/react-qr-svg

You don’t need to put it in an image tag.

My assumption is this library outputs <svg> ... </svg> (I.e. valid HTML tags to output directly)

You can just output the tag/element out directly?

  import React from "react";
  import { QRCode } from "react-qr-svg";

  class Demo extends React.Component {
      render() {
          return (
            <QRCode
            bgColor="#FFFFFF"
            fgColor="#000000"
            level="Q"
            style={{ width: 256 }}
            value="some text"
            />
          );
      }
  } 

UPDATE

If I understand correctly, we cannot simply output <svg>...</svg> on the page as the library @react-pdf/renderer will not work with svg tags. So I propose we serialize the svg to a base-64 string, assigning that to the src of the image tag and then it should work.

I put a simplified demo together without libraries:https://codepen.io/Alexander9111/pen/QWweYXO

HTML (simplified):

<svg>    
    <ellipse class="ground" fill="##787f6a" cx="283.5" cy="487.5" rx="259" ry="80"/>
    <path class="kiwi" fill="#94d31b" d="M210.333,65.331C104.367,...,203.01z"/>
</svg>
<div id="target">
    <!-- place to put our img tag -->
</div>

JS:

const svg = document.querySelector("svg");
const serializer = new XMLSerializer();
const svgStr = serializer.serializeToString(svg);

const img = document.createElement("img")
img.src = 'data:image/svg+xml;base64,'+ window.btoa(svgStr);

const target = document.querySelector("#target");
target.appendChild(img);
svg.parentNode.removeChild(svg);

Now, if we want to do this in React, I assume we can do it something like this:

import React from "react";
import { QRCode } from "react-qr-svg";

  class Demo extends React.Component {
      render() {
        const svg = function {
          return (<QRCode
                  level="Q"
                  style={{width: 256, marginBottom: 50 }}
                  value={'hello world'}
              />);
        };
        const serializer = new XMLSerializer();
        const svgStr = serializer.serializeToString(svg);
        const img_src = 'data:image/svg+xml;base64,'+ window.btoa(svgStr);

          return (
            <img src={ img_src }/>
          );
      }
  } 

OR we could probably do it with lifecycle hooks such as componentDidMount()

import React from "react";
import { QRCode } from "react-qr-svg";

  class Demo extends React.Component {
    componentDidMount() {
        const div = this.refs.target;
        const svg = div.querySelector("svg");
        const serializer = new XMLSerializer();
        const svgStr = serializer.serializeToString(svg);
        const img = this.refs.img;
        img.src = 'data:image/svg+xml;base64,'+ window.btoa(svgStr);
        svg.parentNode.removeChild(svg);
      }

    render() {                
      return (<div ref="target">
                <QRCode
                level="Q"
                style={{width: 256, marginBottom: 50 }}
                value={'hello world'}
                />
              <img ref="img"/>
              </div>
            ) 
      }
  } 

UPDATE - I have it working in React on CodePen: https://codepen.io/Alexander9111/pen/GRJKQQK

HTML: <div id="root"></div>

CSS: svg{border: 2px solid black;} img{border: 2px solid blue;}

React JS:

class Demo extends React.Component {
  componentDidMount() {
    const div = this.refs.target;
    const svg = div.querySelector("svg");
    console.log(svg);
    const serializer = new XMLSerializer();
    const svgStr = serializer.serializeToString(svg);
    const img = this.refs.img;
    console.log(img);
    img.src = 'data:image/svg+xml;base64,'+ window.btoa(svgStr);
    svg.parentNode.removeChild(svg);
  }
  render() {                
      return (
        <div ref="target">
          <svg width="400" height="400">
            <circle r="100" cx="200" cy="200" fill="red" />
          </svg>
          <img ref="img"/>
        </div>
      ); 
    }
} 

ReactDOM.render(
  <Demo/>,
  document.getElementById('root')
);

Upvotes: 3

Related Questions