2

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 />);
1
  • can you try to import it like this import { renderToBuffer } from "@react-pdf/renderer" Commented Dec 5, 2024 at 17:20

2 Answers 2

2

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();
Sign up to request clarification or add additional context in comments.

2 Comments

the renderToBuffer function exists, see here. it's re-exported as a named export and there is no mention of it in the documentation which is confusing. I think this will be fixed in a future update.
thank you for mentioning this it seems weird I added your info in the answer.
0

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'],
          }
        };

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.