React-pdf: render to a Buffer

Created on 23 Apr 2019  路  3Comments  路  Source: diegomura/react-pdf

hey! this project is great.

when running this in node, is it possible to render a pdf to a Buffer in memory, rather than writing to the file system? i'd like to render a document in one process and immediately upload it to a remote endpoint. going thru the file system seems roundabout.

thanks!

Most helpful comment

thanks!! i couldn't find renderToStream on my own.

for anyone who comes across this, i ended up with a function that looks something like this:

async function getBuffer (data) {
  const stream = ReactPDF.renderToStream(<MyPDF data={data} />)

  return new Promise(function(resolve, reject) {
    const buffers = []
    stream.on('data', (data) => {
      buffers.push(data)
    })
    stream.on('end', () => {
      resolve(Buffer.concat(buffers))
    })
    stream.on('error', reject)
  })
}

All 3 comments

it seems as tho i can't immediately read the file actually

ReactPDF.render(<MyPDF />, filename)
let buffer = fs.readFileSync(filename)
console.log(buffer.length)
// => 0

i'd rather directly get a Buffer, but if that's not possible, is there a way to be notified when the "render" has completed?

@brandly I believe you have the functionality there althought it doesn't seem to be in the docs.

const pdfStream = ReactPDF.renderToStream(<MyPDF />)

Might do the trick?

thanks!! i couldn't find renderToStream on my own.

for anyone who comes across this, i ended up with a function that looks something like this:

async function getBuffer (data) {
  const stream = ReactPDF.renderToStream(<MyPDF data={data} />)

  return new Promise(function(resolve, reject) {
    const buffers = []
    stream.on('data', (data) => {
      buffers.push(data)
    })
    stream.on('end', () => {
      resolve(Buffer.concat(buffers))
    })
    stream.on('error', reject)
  })
}
Was this page helpful?
0 / 5 - 0 ratings