diegomura / react-pdf

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

NextJS 14 - Font.register issue on server component #2816

Open nemoeric opened 3 months ago

nemoeric commented 3 months ago

Hey there,

I have looked at many posts but none seem to be discussing this situation.

Font.register() seems not to be properly working when used inside a React Server Component. Although when using the directive "use client", the font is working.

But my goal is to fetch data in a async server component, generate a PDF, and save it to vercel Blob to get a URL I will use for an e-signature later in my workflow. That's why I would like not to use "use client" and remain a server component.

I am using :

I made a simple test page to illustrate (./app/test/page.tsx)

import React from "react";
import {
  Page,
  Text,
  View,
  Document,
  StyleSheet,
  Font,
} from "@react-pdf/renderer";
import ViewerForPDF from "@/components/PDFViewer";
import canelaFont from "@/fonts/Canela-Medium.ttf";
Font.register({
  family: "Canela",
  src: canelaFont,
});
const styles = StyleSheet.create({
  page: {
    padding: 10,
    fontSize: 14,
    fontFamily: "Canela",
  },
});
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 OrdersPdfPage({
  params,
}: {
  params: {
    orderRecordId: string;
  };
}) {
  const { orderRecordId } = params;
  return <ViewerForPDF pdfDocument={<MyDocument />} />;
}

DOES NOT WORK

Capture d’écran 2024-07-14 à 19 57 33

When I declare "use client" directive at the top of this exact same code and custom font is loaded

Capture d’écran 2024-07-14 à 19 58 26

And of course, if I do not declare "use client" and do not use custom font, it does work

Thanks for your help

chrisDeFouRire commented 3 months ago

I don't know what version of react-pdf you're using, but I'm battling with fontFamily too because a regression in 3.4.4 has broken them entirely... Search for fontFamily in issues...

luudv commented 2 months ago

I had the same problem when using server-side render pdf.

key641 commented 1 month ago

I had the same problem when using server-side render pdf.I wonder if you or anyone have solved this problem?

nemoeric commented 1 month ago

So far no solutions... Workaround was to move to pdf-make for server side pdf rendering (and it's really lovely pdf generation library if you ask me)