react-pdf icon indicating copy to clipboard operation
react-pdf copied to clipboard

Image rendering on Node backend does not work

Open Spartano opened this issue 5 years ago • 19 comments

Describe the bug I am generating the pdf on the backend using the example from the website await renderToFile(<MyDocument />, ${__dirname}/my-doc.pdf);

but i am unable to use the Image component. I have tried to use external images and also internal images but i see an empty space. I have tried the same code on the frontend with React and the Pdf is generated correctly, i have tried even with the PdfDownloadLink and it correctly renders the image.

To Reproduce

  1. generate an express app with nodejs
  2. generate a route where you return or generate the Pdf
const router = express.Router();

router.post(
  "/api/printTest",
  asyncHandler(async (req: Request, res: Response) => {
    try {
      const { source } = req.body as { source: any};

      const string = await renderToString(<DocumentWithImage source={source} />);
      // or       await renderToFile(<DocumentWithImage source={source} />, `${__dirname}/my-doc.pdf`);

      res.send(string);
    } catch (error) {
    
      res.status(400).send(new Error("PDF Error Generation"));
    }
  })
);

export { router as printRouter};

Expected behavior I should see the image inside the Pdf

Desktop (please complete the following information):

  • OS: [ Windows 10]
  • Browser [ chrome,]
  • React-pdf version [ v2.0.4]

Spartano avatar Apr 13 '21 14:04 Spartano

Can you share the piece of code where you use the Image component?

gabrielvincent avatar Apr 13 '21 16:04 gabrielvincent

yes sure, i have created a repo

Spartano avatar Apr 13 '21 19:04 Spartano

I just ran your code. What exactly is the expected output? Your code renders this 1-page PDF:

image

The images are rendered correctly, aren't they?

Edit: Sorry, I ran the code as it was when I cloned the repo. I now uncommented

const str = await renderToString(<ImageDocument />)
res.send(str)

and was able to reproduce the error. I now get a PDF with the empty images. Let me check this up.

The expected behaviour here is to send the PDF as the body of the request response, is that correct?

gabrielvincent avatar Apr 13 '21 19:04 gabrielvincent

I was able to achieve what you want by rendering using the renderToStream function:

// print.tsx

import { renderToStream } from '@react-pdf/renderer'
import express, { Request, Response } from 'express'
import asyncHandler from 'express-async-handler'
import React from 'react'
import { ImageDocument } from '../documents/ImageDocument'

import type { DocumentNode } from '@react-pdf/types'

const router = express.Router()

async function convertDocumentToBuffer(
  document: DocumentNode
): Promise<Buffer> {
  const stream = await renderToStream(document)
  return new Promise((resolve, reject) => {
    let buffers: Uint8Array[] = []
    stream.on('data', data => {
      buffers.push(data)
    })
    stream.on('end', () => {
      resolve(Buffer.concat(buffers))
    })
    stream.on('error', reject)
  })
}

router.post(
  '/api/print',
  asyncHandler(async (req: Request, res: Response) => {
    try {
      const document = await convertDocumentToBuffer(<ImageDocument />)
      res.send(document)
    } catch (error) {
      res.status(400).send(new Error('PDF Error Generation'))
    }
  })
)

export { router as printRouter }

gabrielvincent avatar Apr 13 '21 19:04 gabrielvincent

yes, i confirm it is working too. just for curiosity, i have read on previous issues that renderToStream was blocking the eventloop until it had finished rendering, is this the case with the 2.0 version ?

Spartano avatar Apr 13 '21 21:04 Spartano

I just did some tests using your code. I created a route GET /api/test and to the ImageDocument component I added a very long text that results in a document with many pages. This forces renderToStream to render a lot of pages so the request takes about 10 seconds to complete. While I waited for that request to complete, I made multiple calls to /api/test. All of them had to wait for renderToStream to free the event loop before they could be ran. So, yes, renderToStream, as well as the two other rendering functions, still blocks the event loop on react-pdf v2.

gabrielvincent avatar Apr 14 '21 14:04 gabrielvincent

@gabrielvincent thanks for taking care of this!

Unfortunately v2 still renders in the main thread. There are solutions to fix that on top of react-pdf but nothing shipped by us yet. Open to suggestions there.

Please close this ticket when you think it's done :)

diegomura avatar Apr 15 '21 23:04 diegomura

correct me if i'm wrong but onyl renderToStream works in a Nodejs backend, and the other 2 methods dont.

Do you think i still should close the issue?

Spartano avatar Apr 16 '21 14:04 Spartano

I think I didn't understand your question. All the following functions work in a Node backend:

  • renderToStream
  • renderToString
  • renderToFile

gabrielvincent avatar Apr 16 '21 19:04 gabrielvincent

yes, you are correct, my bad for not beeing more explicit, its the rendering of images that doesnt work on the other 2 methods.

Spartano avatar Apr 19 '21 07:04 Spartano

Both renderToStream and renderToFile seem to be rendering images correctly. In fact, renderToFile renders the document by calling renderToStream and then pipes its output into a file, so whatever works render-wise with one will work with the other.

gabrielvincent avatar Apr 20 '21 14:04 gabrielvincent

I tested it a couple of days ago and it was working fine (actually, for fixing the renderToString method). @Spartano what version are you running?

diegomura avatar Apr 20 '21 23:04 diegomura

yes indeed the only method that does not renders the images is renderToString, @diegomura i am using the 2.0.5 version, and i have updated the repo with a simple html so you can test it easily

Spartano avatar Apr 21 '21 10:04 Spartano

This should be fixed in the latest version

diegomura avatar Aug 17 '21 05:08 diegomura

@diegomura I'm able to reproduce the same issue in the latest version 2.0.20 as well. The renderToString does not render the images at all.

Here is a screenshot of the output PDF: Screenshot 2021-10-24 at 1 02 22 PM

ravvis avatar Oct 24 '21 07:10 ravvis

@diegomura ... Hi Diego... I'm on 2.1.1 and am not seeing images using renderToString. Do you know for sure if a fix has been included for this?

goobalives avatar Mar 29 '22 05:03 goobalives

This is still broken - can we re-open? My workaround was to go via the stream and then use this gist to convert to base64: https://gist.github.com/luan0ap/521325c619413a02a798482e2c06af90

charliematters avatar Jun 08 '22 14:06 charliematters

I am also seeing this issue.

zeeglenn avatar Jun 24 '22 01:06 zeeglenn

Same issue. <Image debug cache={false} src="https:/example/logo.png" style={{ width: 100, height: 50 }} /> image

Thumendes avatar Oct 27 '23 20:10 Thumendes