How to add image to pdf file and print in react native expo

Viewed 1445

I want to print a pdf file with an html image embedded on it in react native expo mobile application. And when I tried generating the pdf file, image is not included on the generated pdf file. Any help on how to include image in my pdf file.

createPDF = async (html) => {    
      try {
        const {uri} = await Print.printToFileAsync(html);
        Print.printAsync({ uri });
        this.setState({callPrint: false});
      } catch(err) {
        console.error(err);
        this.setState({callPrint: false});
      }
  };

 const html = "
        <html>
            
            <body>
                <div class='title-container'>
                  <img source="asset/omnix.png" />
                   
                </div>
            </body>
        </html>
    ";

1 Answers

This is a known problem on iOS for expo, adding a fetchImageData function to convert the image to a Base64 string is the recommended fix

createPDF = async (html) => {...};

fetchImageData = (uri) => { // fetch Base64 string of image data
 const data = await FileSystem.readAsStringAsync('file://' + uri, {
  encoding: FileSystem.EncodingType.Base64,
 });
 return imageData = 'data:image/png;base64,' + data;
};

const html = "
<html>
 <body>
  <div class='title-container'>
   <img source=${fetchImageData('asset/omnix.png')} />
  </div>
 </body>
</html>";

If you use fetchImageData to fill all your images they will print correctly

Related