Ade N
Ade N

Reputation: 145

React-pdf - image renders twice

I am using https://react-pdf.org/styling and I would like to display the loaded images when I hit the print button. However, when I print the image renders twice.

import React from "react";
import phoneLogo from "./images/phone.png";

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


const MyDoc = () => (
  <Document>
    <Page wrap>
      <Image src={phoneLogo} />
    </Page>
  </Document>
);

class App extends React.Component {
  render() {
    return (
      <div className="w-full">
        <div className="text-center py-12">
          <BlobProvider document={MyDoc()}>
            {({ url }) => (
              <a href={url} target="_blank">
                Print
              </a>
            )}
          </BlobProvider>
        </div>
      </div>
    );
  }
}

export default App;

I have tried to load the image like this, but it doesn't show up at all.

const MyDoc = () => (
  <Document>
    <Page wrap>
      <Image src='/images/phone.png />
    </Page>
  </Document>
);

Any suggestions? Thank you!!

Upvotes: 3

Views: 16246

Answers (2)

Tharzeez
Tharzeez

Reputation: 1343

I converted the .png file to base64 encoding and added to the @react-pdf/renderer and it is working fine for me now.

<Image
 style={styles.header_image}
 src={`data:image/png;base64, the-base-64-encoded-string-goes-here`}
/> 

Upvotes: 0

Ade N
Ade N

Reputation: 145

Sorted!!!

The png is indeed rendered twice when importing the images like this

const MyDoc = () => (
  <Document>
    <Page wrap>
      <Image src={phoneLogo} />
    </Page>
  </Document>
);

But it works with an image address, where it renders only once.

const MyDoc = () => (
  <Document>
    <Page wrap>
      <Image src="https://img.icons8.com/android/96/000000/phone.png" />
    </Page>
  </Document>
);

Upvotes: 1

Related Questions