diegomura / react-pdf

📄 Create PDF files using React
https://react-pdf.org
MIT License
14.91k stars 1.18k forks source link

compat with react 19 #2756

Open joacub opened 5 months ago

joacub commented 5 months ago

React pdf is not compatible with react 19, will you make the library compat with this version ?

joacub commented 5 months ago

👀

ZipBrandon commented 5 months ago

Anything @eps1lon you can suggest? I have been poking around in the react-reconciler but it has drifted and largely undocumented.

eps1lon commented 5 months ago

react-three-fiber also had to update its reconciler implementation. One of the breaking changes that was hard to track down was around commitUpdate which is no longer called with an updatePayload.

Where is the code for the reconciler implementation? Maybe something stands out to me. But no promises for now since we're not using that library at Vercel.

ZipBrandon commented 5 months ago

@eps1lon Here is where @diegomura creates the reconciler. When I updated the deps on my fork, I couldn't get the document to be created from the updateContainer call here

joacub commented 5 months ago

Some advances ?

ZipBrandon commented 5 months ago

FWIW I have patched my version to use React 18. I only use the node version of the renderer so having a version of react@18.3.1 that is only used for that suits my purpose.

I'm aliasing react-18 with "react-18": "npm:react@^18.3.1" in my package.json.

This uses a patch I made with patch-package where the renderer code thenimport React from "react-18".

I had to use the escape hatch of "use no memo" in my components to opt-out the compiler.

I use the pragma /** @jsxImportSource react-18 */ at the top of all files that are associated with the PDF rendering so it goes through the correct createElement().

That being said, this is just duct tape to get by until we have true React 19 compatability.

cipriancaba commented 5 months ago

That's a very interesting aproach @ZipBrandon but I feel like vercel and react will need to come up with a better solution than this since any 3rd party lib you might be using that is not updated will simply prevent you from upgrading to next 15 and react 19.

What is the suggested path here @eps1lon ? I've spent the time migrating to next 15, loved the wait everything felt until one of our agents told me the pdf generation page was buggered so had to revert to latest stable next

cipriancaba commented 5 months ago

Hi @ZipBrandon , do you mind sharing the patch you used to make this work?

eps1lon commented 5 months ago

I don't see what else we can do. This is just inherent to breaking changes in a library.

What is the suggested path here @eps1lon ?

The suggested path for libraries to ensure compatibility during the alpha period which we announced on the 25th of April. But we also encourage libraries to ensure continuous compatibility by regularly testing Canary.

But we also spent resources at Vercel to ensure the libraries are compatible we use:

or helped these libraries when upgrading:

This is a community effort though so we need all the help we can get

cipriancaba commented 5 months ago

Thanks for the reply @eps1lon and your efforts are obviously much appreciated

I've been tracking your issue here https://github.com/eps1lon/react/issues/10

I guess when I meant suggested path I meant more like this is literally a blocker for any kind of upgrade to react 19 / next 15. Is there potential for a more generic temporary fix (maybe similar to what @ZipBrandon suggested) until react 19 is fully adopted by lib authors? In every real life project there's this obscure library that you absolutely have to use and then if that blocks your entire upgrade path, you're basically stuck.

ZipBrandon commented 5 months ago

@cipriancaba Sure! Here's the the gist of the patch for @react-pdf/renderer https://gist.github.com/ZipBrandon/b6c3848a400feff9741d739b7544d4fe. This is only for rendering on the Node side. I didn't do anything for browser rendering.

Caveats to remember:

alexandernanberg commented 4 months ago

I've done some investigations and the library is incompatible with react-reconciler 0.27.0 and later (React 19 requires ^0.31.0).

The library expect reconciler.createContainer to mutate the document property of the container.

https://github.com/diegomura/react-pdf/blob/f64f3bd26c9ac1cdb0d894d4621cf2f985c8a64b/packages/renderer/src/index.js#L26-L28

which is then accessed here

https://github.com/diegomura/react-pdf/blob/f64f3bd26c9ac1cdb0d894d4621cf2f985c8a64b/packages/renderer/src/index.js#L37-L38

In 0.27.0 the container.document is always null

I've tried finding workarounds, but I'm not familiar with the internals of the reconciler. @eps1lon thankful for any pointers!

Edit:

~Seems like newer version of the reconciler forces the container to be immutable, or that it clones the object passed into createContainer. The mutation part is done in appendChildToContainer~

https://github.com/diegomura/react-pdf/blob/f64f3bd26c9ac1cdb0d894d4621cf2f985c8a64b/packages/renderer/src/renderer.js#L103-L109

Edit 2:

Okay so looks like updateContainer now schedules an update instead of doing it sync. And library code relies on the sync behavior.

  const updateContainer = (doc, callback) => {
    renderer.updateContainer(doc, mountNode, null, callback);
  };

  if (initialValue) updateContainer(initialValue);

  setTimeout(() => {
    console.log(container);
    // container.document is set now
  }, 0);
alexandernanberg commented 4 months ago

Got it working in #2783.

If you want to try it out early you can:

  1. Install @alexandernanberg/react-pdf-renderer
  2. Replace all references of @react-pdf/renderer with alexandernanberg/react-pdf-renderer
karlhorky commented 4 months ago

@alexandernanberg thanks for this!

Tried @alexandernanberg/react-pdf-renderer out just now and it works in some circumstances!

However, it is hanging with our Express app which uses:

We do also have this pragma, not sure if that's relevant:

/** @jsxRuntime automatic @jsxImportSource react */
alexandernanberg commented 4 months ago

@karlhorky Custom fonts and stylesheets work for me, although I'm using Next.js.

I suspect that I broke something in this commit ed62fa6 (#2783). I'll see if I can revert those changes

karlhorky commented 4 months ago

Custom fonts and stylesheets work for me

Interesting, are you also using the same configuration?

If you could post an example of your code, then that would be helpful to track down working / not working configurations.

I'll see if I can revert those changes

Thanks!

alexandernanberg commented 4 months ago

Only .ttf fonts are supported AFAIK https://react-pdf.org/fonts

Example ```tsx import { Document, Font, Page, StyleSheet, View, renderToStream, } from "@alexandernanberg/react-pdf-renderer"; const fontFamily = { sans: "Inter", }; Font.register({ family: fontFamily.sans, fonts: [ { src: "https://storage.googleapis.com/.../fonts/Inter-Regular.ttf", fontWeight: "normal", }, ], }); export function renderCertificate() { return renderToStream(); } export function Certificate() { return ( ); } const styles = StyleSheet.create({ text: { fontFamily: fontFamily.sans, fontWeight: "normal", fontSize: 14, }, }); ```
karlhorky commented 4 months ago

Only .ttf fonts are supported AFAIK

WOFF fonts are also supported, this is just undocumented. I've opened a PR to document that here:

karlhorky commented 4 months ago

Interesting, WOFF is not the problem after all, this .woff font works from Google Fonts (Inter font):

Font.register({
  family: 'Inter',
  format: 'woff',
  src: 'https://fonts.gstatic.com/s/inter/v12/UcCO3FwrK3iLTeHuS_fvQtMwCp50KnMw2boKoduKmMEVuGKYAZ9hjp-Ek-_EeA.woff',
});

All fonts on Google Fonts seem to work.

It seems to be a problem with my own font files (both TTF and WOFF) being unusable in some way. Maybe something in some dependency is being more strict with certain font files.

karlhorky commented 4 months ago

Ohh looks like this hanging behavior is a known problem with custom fonts and react-pdf and fontkit (caused by the transitive dependency restructure@3.0.1):

Downgrading to restructure@3.0.0 as mentioned in the issues above resolves the issue.


Thus, I can confirm that @alexandernanberg/react-pdf-renderer@4.0.0-canary-2 is working with React 19. 🙌 🎉

ZipBrandon commented 4 months ago

I'm using it now too! Thanks so much @alexandernanberg!

Timothylp commented 3 months ago

Hello,

while trying with @alexandernanberg/react-pdf-renderer package, I can't get the PDF rendering to work, I still get the following error:

⨯ ..\node_modules\react-reconciler\cjs\react-reconciler.development.js (15700:59) @ module.exports
⨯ TypeError: Cannot read properties of undefined (reading 'S')
    at Results (./app/(frontend)/results/page.tsx:41:107)
digest: "3784830825"
  15698 |         _currentRenderer2: null
  15699 |       },
> 15700 |       prevOnStartTransitionFinish = ReactSharedInternals.S;
        |                                                           ^
  15701 |     ReactSharedInternals.S = function (transition, returnValue) {
  15702 |       "object" === typeof returnValue &&
  15703 |         null !== returnValue &&

Is it maybe because there was an update of the beta version of react 19?

mamlzy commented 2 weeks ago

@alexandernanberg can you fix this bugs in your forked repo? https://github.com/diegomura/react-pdf/pull/2878/files

alexandernanberg commented 2 weeks ago

I've rebased on main and released a new 4.0.0-canary-3 version of @alexandernanberg/react-pdf-renderer. Haven't had time to test much yet so let me know if it's working as expected

mamlzy commented 2 weeks ago

Thank you @alexandernanberg , for responding to my request. Now i go back to Next.js 14, which uses React 18. There is so much unsupported libraries in react 19, and your forked repo probably only work on react 18 right?, maybe I'll try it later on Next.js 15!

karlhorky commented 2 weeks ago

@mamlzy I think there are a few misconceptions here:

mamlzy commented 2 weeks ago

@karlhorky i'm using next 15 app router not pages router so it will uses react 19, am i correct?

Jussinevavuori commented 1 week ago

Hello,

while trying with @alexandernanberg/react-pdf-renderer package, I can't get the PDF rendering to work, I still get the following error:

⨯ ..\node_modules\react-reconciler\cjs\react-reconciler.development.js (15700:59) @ module.exports
⨯ TypeError: Cannot read properties of undefined (reading 'S')
    at Results (./app/(frontend)/results/page.tsx:41:107)
digest: "3784830825"
  15698 |         _currentRenderer2: null
  15699 |       },
> 15700 |       prevOnStartTransitionFinish = ReactSharedInternals.S;
        |                                                           ^
  15701 |     ReactSharedInternals.S = function (transition, returnValue) {
  15702 |       "object" === typeof returnValue &&
  15703 |         null !== returnValue &&

Is it maybe because there was an update of the beta version of react 19?

Any update on this? I'm still experiencing this on @alexandernanberg/react-pdf-renderer@4.0.0-canary-3.

alexandernanberg commented 1 week ago

@Jussinevavuori Are you on Next.js 15 and React RC? My guess it's something with multiple or incorrect version of React

Jussinevavuori commented 1 week ago

@alexandernanberg My React versions are listed below

"dependencies": {
  "react": "19.0.0-rc-69d4b800-20241021",
  "react-dom": "19.0.0-rc-69d4b800-20241021",
  "next": "15.0.1"
},
"devDependencies": {
  "@types/react": "npm:types-react@19.0.0-rc.1",
  "@types/react-dom": "npm:types-react-dom@19.0.0-rc.1"
}
sam3d commented 1 week ago

@alexandernanberg I'm also getting the same error on the same versions of the packages as @Jussinevavuori

ringge commented 1 week ago

@alexandernanberg I'm also getting the same error on the same versions of the packages as @Jussinevavuori

same here

jpainam commented 1 week ago

@alexandernanberg I'm also getting the same error on the same versions of the packages as @Jussinevavuori

Same here, on react 19 and nextjs 15

alexandernanberg commented 6 days ago

Are you rendering the pdf client side? It's working for me server side with Nextjs 15

jpainam commented 6 days ago

Rendering server side. here is my code.

import type { NextRequest } from "next/server";

import { PdfExample, renderToStream } from "@repo/reports";

export async function GET(req: NextRequest) {
    const requestUrl = new URL(req.url);
    const stream = await renderToStream(
      await PdfExample(),
    );
    const blob = await new Response(stream).blob();

    const headers: Record<string, string> = {
      "Content-Type": "application/pdf",
      "Cache-Control": "no-store, max-age=0",
    };
    if (!preview) {
      headers["Content-Disposition"] =
        `attachment; filename="filename.pdf"`;
    }
    return new Response(blob, { headers });
}

renderToStream is exported from @alexandernanberg/react-pdf-renderer

I'm getting this error

ypeError: Cannot read properties of undefined (reading 'S')
    at module.exports (//.next/server/chunks/08b5e_@alexandernanberg_react-pdf-renderer_lib_react-pdf_1362ba.js:14494:67)
    at createRenderer /.next/server/chunks/08b5e_@alexandernanberg_react-pdf-renderer_lib_react-pdf_1362ba.js:14980:12)
    at pdf (/.next/server/chunks/08b5e_@alexandernanberg_react-pdf-renderer_lib_react-pdf_1362ba.js:15180:28)
    at renderToStream (/.next/server/chunks/08b5e_@alexandernanberg_react-pdf-renderer_lib_react-pdf_1362ba.js:15311:22)
    at GET (/.next/server/chunks/[root of the server]__03a291._.js:10336:252)
    at async AppRouteRouteModule.do (//next/dist/compiled/next-server/app-route.runtime.dev.js:10:32801)
    at async AppRouteRouteModule.handle (/node_modules/next/dist/compiled/next-server/app-route.runtime.dev.js:10:38302)
sam3d commented 6 days ago

@alexandernanberg any chance you could share your working project's lockfile? I have a suspicion there is some kind of really specific dependency tree required to make this work properly

alexandernanberg commented 6 days ago

I'm able to reproduce the issue outside my actual app https://github.com/alexandernanberg/react-pdf-renderer-nextjs , I'll look into it whenever I get time. Can't make any promises.

I can't share the whole lockfile but I'm using pnpm and I've locked the React versions to these + nextjs@15.0.1

catalogs:
  react19:
    react: 19.0.0-rc-69d4b800-20241021
    react-dom: 19.0.0-rc-69d4b800-20241021
    '@types/react': npm:types-react@rc
    '@types/react-dom': npm:types-react-dom@rc

Tried changing to those in my repro but still got the same issue. We might have to inline to react-reconciler into the renderer package instead of using it as a dep

sam3d commented 6 days ago

AFAICT react-reconciler is already inlined into the render package? The entire source of react-reconciler.production.js is present in the resulting outputs of react-pdf-renderer/lib

alexandernanberg commented 6 days ago

You're right, had a brief experiment keeping it as a dep but removed that later https://github.com/diegomura/react-pdf/pull/2783/commits/7c24f1427811f0497ebc1b13a6c57f364f5993de.

So digging into this a bit more, React.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE is undefined which the reconciler depends on.

There is however React.__SERVER_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE, so looks like the React pkg adapts based on the env 🤔

diegopluna commented 2 days ago

Rendering server side. here is my code.

import type { NextRequest } from "next/server";

import { PdfExample, renderToStream } from "@repo/reports";

export async function GET(req: NextRequest) {
    const requestUrl = new URL(req.url);
    const stream = await renderToStream(
      await PdfExample(),
    );
    const blob = await new Response(stream).blob();

    const headers: Record<string, string> = {
      "Content-Type": "application/pdf",
      "Cache-Control": "no-store, max-age=0",
    };
    if (!preview) {
      headers["Content-Disposition"] =
        `attachment; filename="filename.pdf"`;
    }
    return new Response(blob, { headers });
}

renderToStream is exported from @alexandernanberg/react-pdf-renderer

I'm getting this error

ypeError: Cannot read properties of undefined (reading 'S')
    at module.exports (//.next/server/chunks/08b5e_@alexandernanberg_react-pdf-renderer_lib_react-pdf_1362ba.js:14494:67)
    at createRenderer /.next/server/chunks/08b5e_@alexandernanberg_react-pdf-renderer_lib_react-pdf_1362ba.js:14980:12)
    at pdf (/.next/server/chunks/08b5e_@alexandernanberg_react-pdf-renderer_lib_react-pdf_1362ba.js:15180:28)
    at renderToStream (/.next/server/chunks/08b5e_@alexandernanberg_react-pdf-renderer_lib_react-pdf_1362ba.js:15311:22)
    at GET (/.next/server/chunks/[root of the server]__03a291._.js:10336:252)
    at async AppRouteRouteModule.do (//next/dist/compiled/next-server/app-route.runtime.dev.js:10:32801)
    at async AppRouteRouteModule.handle (/node_modules/next/dist/compiled/next-server/app-route.runtime.dev.js:10:38302)

How are you not getting the:

Argument of type 'ReadableStream' is not assignable to parameter of type 'BodyInit | null | undefined'.ts(2345)

Typescript error on the blob definition?

jpainam commented 2 days ago

Rendering server side. here is my code.

import type { NextRequest } from "next/server";

import { PdfExample, renderToStream } from "@repo/reports";

export async function GET(req: NextRequest) {
    const requestUrl = new URL(req.url);
    const stream = await renderToStream(
      await PdfExample(),
    );
    const blob = await new Response(stream).blob();

    const headers: Record<string, string> = {
      "Content-Type": "application/pdf",
      "Cache-Control": "no-store, max-age=0",
    };
    if (!preview) {
      headers["Content-Disposition"] =
        `attachment; filename="filename.pdf"`;
    }
    return new Response(blob, { headers });
}

renderToStream is exported from @alexandernanberg/react-pdf-renderer I'm getting this error

ypeError: Cannot read properties of undefined (reading 'S')
    at module.exports (//.next/server/chunks/08b5e_@alexandernanberg_react-pdf-renderer_lib_react-pdf_1362ba.js:14494:67)
    at createRenderer /.next/server/chunks/08b5e_@alexandernanberg_react-pdf-renderer_lib_react-pdf_1362ba.js:14980:12)
    at pdf (/.next/server/chunks/08b5e_@alexandernanberg_react-pdf-renderer_lib_react-pdf_1362ba.js:15180:28)
    at renderToStream (/.next/server/chunks/08b5e_@alexandernanberg_react-pdf-renderer_lib_react-pdf_1362ba.js:15311:22)
    at GET (/.next/server/chunks/[root of the server]__03a291._.js:10336:252)
    at async AppRouteRouteModule.do (//next/dist/compiled/next-server/app-route.runtime.dev.js:10:32801)
    at async AppRouteRouteModule.handle (/node_modules/next/dist/compiled/next-server/app-route.runtime.dev.js:10:38302)

How are you not getting the:

Argument of type 'ReadableStream' is not assignable to parameter of type 'BodyInit | null | undefined'.ts(2345)

Typescript error on the blob definition?

It works at runtime. just add // @ts-expect-error TODO: WTF Typescript right before const blob = await new Response(stream).blob();

This is due to TypeScript not recognizing ReadableStream as a valid arg to Response. I really don't know why.

BTW, it also works if you stream directly.

@diegopluna read https://midday.ai/updates/invoice-pdf This was working fine before react 19 and nextjs 15

diegopluna commented 2 days ago

Rendering server side. here is my code.

import type { NextRequest } from "next/server";

import { PdfExample, renderToStream } from "@repo/reports";

export async function GET(req: NextRequest) {
    const requestUrl = new URL(req.url);
    const stream = await renderToStream(
      await PdfExample(),
    );
    const blob = await new Response(stream).blob();

    const headers: Record<string, string> = {
      "Content-Type": "application/pdf",
      "Cache-Control": "no-store, max-age=0",
    };
    if (!preview) {
      headers["Content-Disposition"] =
        `attachment; filename="filename.pdf"`;
    }
    return new Response(blob, { headers });
}

renderToStream is exported from @alexandernanberg/react-pdf-renderer I'm getting this error

ypeError: Cannot read properties of undefined (reading 'S')
    at module.exports (//.next/server/chunks/08b5e_@alexandernanberg_react-pdf-renderer_lib_react-pdf_1362ba.js:14494:67)
    at createRenderer /.next/server/chunks/08b5e_@alexandernanberg_react-pdf-renderer_lib_react-pdf_1362ba.js:14980:12)
    at pdf (/.next/server/chunks/08b5e_@alexandernanberg_react-pdf-renderer_lib_react-pdf_1362ba.js:15180:28)
    at renderToStream (/.next/server/chunks/08b5e_@alexandernanberg_react-pdf-renderer_lib_react-pdf_1362ba.js:15311:22)
    at GET (/.next/server/chunks/[root of the server]__03a291._.js:10336:252)
    at async AppRouteRouteModule.do (//next/dist/compiled/next-server/app-route.runtime.dev.js:10:32801)
    at async AppRouteRouteModule.handle (/node_modules/next/dist/compiled/next-server/app-route.runtime.dev.js:10:38302)

How are you not getting the:

Argument of type 'ReadableStream' is not assignable to parameter of type 'BodyInit | null | undefined'.ts(2345)

Typescript error on the blob definition?

It works at runtime. just add // @ts-expect-error TODO: WTF Typescript right before const blob = await new Response(stream).blob();

This is due to TypeScript not recognizing ReadableStream as a valid arg to Response. I really don't know why.

BTW, it also works if you stream directly.

@diegopluna read https://midday.ai/updates/invoice-pdf This was working fine before react 19 and nextjs 15

Thanks, probabily will downgrade my project to next 14 while this isnt resolved!

eps1lon commented 22 hours ago

For people using @alexandernanberg/react-pdf-renderer: Is it only breaking in Next.js route handlers and React Server components or is it also breaking in Client components. Would be helpful to verify if adding use client at the top helps. This doesn't work for Next.js Route handlers but pages can leverage use client.

alexandernanberg commented 7 hours ago

@eps1lon AFAICT it's breaking only in Server component and route handlers. E.g. this is working https://github.com/alexandernanberg/react-pdf-renderer-nextjs/blob/main/src/app/page.tsx as expected.

Any plans on supporting use client for route handlers, or other ways to opt out of Server components?

eps1lon commented 6 hours ago

How does this work for a page? Isn't the server use case to just save it as a file i.e. only relevant for API endpoints?

There's currently no plan to support Client components in Next.js Route handlers. You can still use pages/api though in Next.js which does support Client components (but no React Server Components).