I can generate a PDF on a Nextjs api route with the library react-pdf, by using the data sent via request.
But the issue arises with the method ReactPDF.renderToStream(), which requires the type below:
'ReactElement<DocumentProps, string | JSXElementConstructor>'.
When I try to pass the props to make a PDF on demand, typescript complains about the types like below:
'FunctionComponentElement' is not assignable to parameter of type 'ReactElement<DocumentProps, string | JSXElementConstructor>'. Types of property 'props' are incompatible. Type 'PdfBudgetProps' has no properties in common with type 'DocumentProps'.
The command that created this type issue was:
const pdfStream = await ReactPDF.renderToStream(
React.createElement(PdfBudget, {month: "jan"})
);
Below is how I created the component:
import { Document, Page, Text } from '@react-pdf/renderer'
import React from 'react'
interface PdfBudgetProps {
month: string;
}
const PdfBudget: React.FC<PdfBudgetProps> = ({month}) => {
return (
<Document>
<Page>
<Text>{month}</Text>
</Page>
</Document>
)
}
export default PdfBudget
And below is the api route:
import { NextApiRequest, NextApiResponse } from "next"
import { renderToStream } from "@react-pdf/renderer"
import PdfBudget from '../../../components/PdfBudget'
export default async function handler(
req: NextApiRequest,
res: NextApiResponse
) {
if (req.method != "POST") {
res.status(405).json({message: "invalid method"})
}
// Stream the PDF directly to the response
res.setHeader('Content-Disposition', 'attachment; filename="example.pdf"')
res.setHeader('Content-Type', 'application/pdf')
const pdfStream = await renderToStream(
React.createElement(PdfBudget, {month: "jan"})
)
pdfStream.pipe(res)
}
How to solve the type issue?
I appreciate any help!