react-pdf icon indicating copy to clipboard operation
react-pdf copied to clipboard

Request for a simple example using nextjs app router

Open jpainam opened this issue 1 year ago • 2 comments

Hi I wasn't able to find any simple example using nextjs app router.

My file structure look like this

app
-----pdfs
---------page.tsx

and I access localhost:3000/pdfs I have a layout.tsx The content of page.tsx is simple

"use client";

import React from "react";
import {
  Document,
  Page,
  PDFViewer,
  StyleSheet,
  Text,
  View,
} from "@react-pdf/renderer";

const styles = StyleSheet.create({
  page: {
    padding: 10,
    fontSize: 14,
  },
});
const MyDocument = () => {
  return (
    <Document>
      <Page size="A4" style={styles.page}>
        <View>
          <View>
            <Text
              style={{
                fontFamily: "Canela",
                fontSize: 30,
              }}
            >
              Title for document
            </Text>
          </View>
        </View>
      </Page>
    </Document>
  );
};

export default function Receipt() {
  return (
    <PDFViewer>
      <MyDocument />
    </PDFViewer>
  );
}

Yet, I get this error,

Something went wrong! from PDFViewer is a web specific API. You're either using this component on Node, or your bundler is not loading react-pdf from the appropriate web build.

And after adding use client I get this error

 ⨯ Internal error: Error: PDFViewer is a web specific API. You're either using this component on Node, or your bundler is not loading react-pdf from the appropriate web build.
    at throwEnvironmentError (/node_modules/@react-pdf/renderer/lib/react-pdf.js:4348:9)
    at PDFViewer (/node_modules/@react-pdf/renderer/lib/react-pdf.js:4354:3)

can someone help with a minimal working example?

I have added this to next.config.js

  experimental: {
    serverComponentsExternalPackages: ["@react-pdf/renderer"],
  },

jpainam avatar Sep 29 '24 19:09 jpainam

@jpainam here you go: https://github.com/myrddral/reactpdf-example-next-app

Next.js pre-renders components on the server side, even ones marked with the 'use client' directive. For this reason if a package uses Web APIs only present in browser environments, you have to make sure that the component doesn't even pre-render on the server. Using next/dynamic with SSR set to false worked for me, you even get to add a custom loader to it while the module fires up.

myrddral avatar Oct 04 '24 23:10 myrddral

Someone can create an example of use for nextjs server action ?

I have already this error.. :(

thibault60000 avatar Oct 20 '24 09:10 thibault60000

Try importing it with next/dynamic and setting ssr: false: https://github.com/diegomura/react-pdf/issues/2913#issuecomment-2433500357

rago4 avatar Oct 23 '24 21:10 rago4

The final solution I adopted is based on this. https://midday.ai/updates/invoice-pdf

it's allow server-side rendering of the PDF. What i needed.

jpainam avatar Oct 25 '24 01:10 jpainam