How to render an svg logo in React-pdf document in the dom?

Viewed 1047

I have a project, where I am using React-pdf to generate a document. I want to add an SVG logo to this document. According to the React-pdf documentation, they have an element called Svg that is a container that defines a new coordinate system and viewport, and it is used as the outermost element of SVG documents. From what I understand I should somehow convert a normal svg to the type of element that React-pdf uses, in order to make it work? (If so, how could I accomplish this? Can I use some sort of external library?). My code is below(Now it gives me an error because I can`t use the Image from React-pdf to render svg. If I use the Image element with src of an image that is in the format .jpeg or .png it works.

import {
  Page,
  Text,
  View,
  Document,
  StyleSheet,
  Image,
  Svg,
  PDFViewer,
} from "@react-pdf/renderer";

...
  return (
    <div>
      <PDFViewer style={{ width: "98vw", height: "98vh" }}>
        <Document title="TITLE" author="AUTHOR">
          <Page size="A4" style={styles.page}>
            <View style={styles.section}>
              <Svg>
                <Image src={logoUrl} style={styles.logo} />
              </Svg>
              <Text>My PDF</Text>
            </View>
          </Page>
        </Document>
      </PDFViewer>
    </div>
  );
...
3 Answers

An easy way to do this is to put your SVG file in a folder in your React Project. And then import it into your app.js or wherever you need it using an img tag

import myIcon from 'icons/myIcon.svg';

import {
  Page,
  Text,
  View,
  Document,
  StyleSheet,
  Image,
  Svg,
  PDFViewer,
} from "@react-pdf/renderer";
import myIcon from 'icons/myIcon.svg'
...
  return (
    <div>
      <PDFViewer style={{ width: "98vw", height: "98vh" }}>
        <Document title="TITLE" author="AUTHOR">
          <Page size="A4" style={styles.page}>
            <View style={styles.section}>
              //CALL YOUR SVG USING IMG TAG
              <img src={myIcon} />

              <Text>My PDF</Text>
            </View>
          </Page>
        </Document>
      </PDFViewer>
    </div>
  );
...

I replaced your SVG TAG with <img src={myIcon} />

This is very old but, as far as I can see the Element from react pdf expects actual svg code, you are giving it and img tag which is invalid.

Related