skip to Main Content

I’m trying to generate a PDF using @react-pdf/renderer, and I want to directly render the PDF to a Buffer for further processing (e.g., saving it to a file or sending it as an HTTP response). However, when I call ReactPDF.renderToBuffer, I get the following error:

TypeError: _react_pdf_renderer__WEBPACK_IMPORTED_MODULE_8__.default.renderToBuffer is not a function

Used the following code to generate the PDF:

const buffer = await ReactPDF.renderToBuffer(<MyDocument />);

2

Answers


  1. That function exist as @mocherfaoui mentioned however isn’t mentioned in the documentation for some reason. Until this is fixed you can do:

    const pdfInstance = ReactPDF.pdf(<MyDocument />);
    const buffer = await pdfInstance.toBuffer();
    
    Login or Signup to reply.
  2. I’ll just leave it here, maybe you’ll find it helpful.

    Environment
    OS: MacOS
    Browser: Chrome
    Next.js : 14.2.10
    React-pdf version : 4.1.5

    The task is to generate a pdf on the server and send it in an HTTP response.

    Error I encountered

    Error: I.Component is not a constructor

    The code I used is in the route.ts file.

    
            /* eslint-disable @typescript-eslint/no-explicit-any */
        
        import InvoicePdfTemplate from '@/components/Template'
        import { renderToBuffer } from '@react-pdf/renderer'
        import { type NextRequest } from 'next/server'
        
        export async function POST (request: NextRequest): Promise<Response> {
          try {
            const body = await request.json()
            const pdfBuffer = await renderToBuffer(Template({ data: body }) as React.ReactElement)
        
            return new Response(pdfBuffer, {
              status: 200,
              headers: {
                'Content-Type': 'application/pdf',
                'Content-Disposition': `attachment; filename=invoice_${body.invoice_number}.pdf`
              }
            })
          } catch (error: any) {
            return new Response(`Error: ${error.message}`, {
              status: 400
            })
          }
        }
    
    

    The solution that helped me ( GitHub – https://github.com/diegomura/react-pdf/issues/2350#issuecomment-1914234934 )

    Add to the configuration file next.config.js

         const nextConfig = {
              experimental: {
                serverComponentsExternalPackages: ['@react-pdf/renderer'],
              }
            };
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search