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

Cannot read properties of undefined (reading 'unitsPerEm')" in @react-pdf/renderer v4

Open Mario8419 opened this issue 1 year ago • 23 comments

Describe the bug After upgrading @react-pdf/renderer from v3.4.5 to v4, the following error occurs:

Cannot read properties of undefined (reading 'unitsPerEm') following no pdf rendering

e.g of font register

import font from '../../utils/montserrat-regular.ttf' import fontBold from '../../utils/montserrat-bold.ttf'

Font.register({ family: 'Montserrat', fonts: [ { src: font }, { src: fontBold, weight: 600 } ] })

Mario8419 avatar Mar 03 '25 19:03 Mario8419

the same issue comes up, Is there any solution of this issue?

ct-dixit avatar Mar 04 '25 06:03 ct-dixit

The same issue here. my font is Inter btw.

mAkifArs avatar Mar 04 '25 11:03 mAkifArs

Do you get any more extensive error message? Kind of hard to replicate or figure out with so little information

diegomura avatar Mar 04 '25 11:03 diegomura

It happens on `// Setup rendering queue useEffect(() => { const renderQueue = queue({ autostart: true, concurrency: 1 });

const queueDocumentRender = () => {
  setState((prev) => ({ ...prev, loading: true }));

  renderQueue.splice(0, renderQueue.length, () =>
    state.error ? Promise.resolve() : pdfInstance.current.toBlob(),
  );
};

const onRenderFailed = (error) => {
  console.error(error);
  setState((prev) => ({ ...prev, loading: false, error }));
};

const onRenderSuccessful = (blob) => {
  setState({
    blob,
    error: null,
    loading: false,
    url: URL.createObjectURL(blob),
  });
};

pdfInstance.current = pdf();
pdfInstance.current.on('change', queueDocumentRender);
if (document) {
  pdfInstance.current.updateContainer(document);
}

renderQueue.on('error', onRenderFailed);
renderQueue.on('success', onRenderSuccessful);

return () => {
  renderQueue.end();
  pdfInstance.current.removeListener('change', queueDocumentRender);
};

}, []);`

this part of renderers const onRenderFailed = (error) => { console.error(error); setState((prev) => ({ ...prev, loading: false, error })); }; part of code.

added the image of console also.

Image

mAkifArs avatar Mar 04 '25 11:03 mAkifArs

I have the same error since my last update.

I have tried to remove any custom fonts to see if the error could be resolved but with no success. I tried with previous versions 4.0.x / 4.1.x and the latest 4.3.0 but I still get this error.

Image
if (lastIndex < string.length) {
    const fontSize = getFontSize(last(runs));
    res.push({
      start: lastIndex,
      end: string.length,
      attributes: {
        font: [lastFont],
        scale: fontSize / lastFont.unitsPerEm
      }
    });
  }

Image

m4xleb avatar Mar 05 '25 02:03 m4xleb

Along with cannot read properties of undefined (reading 'unitsPerEm'), also Buffer is not defined since update to v4

/**

  • Resolves src to @react-pdf/image interface.
  • Also it handles factories and async sources.
  • @param src
  • @returns Resolved src */ const resolveSource = async (src) => { const source = typeof src === 'function' ? await src() : await src; return typeof source === 'string' ? { uri: source } : source; };

/**

  • Fetches image and append data to node
  • Ideally this fn should be immutable.
  • @param node */ const fetchImage = async (node) => { const src = getSource(node); const { cache } = node.props; if (!src) { console.warn(false, 'Image should receive either a "src" or "source" prop'); return; } try { const source = await resolveSource(src); if (!source) { throw new Error(Image's "src" or "source" prop returned ${source}); } node.image = await resolveImage(source, { cache }); if (Buffer.isBuffer(source) || source instanceof Blob) return; node.image.key = 'data' in source ? source.data.toString() : source.uri; } catch (e) { console.warn(e.message); } };

Mario8419 avatar Mar 05 '25 06:03 Mario8419

Having the same issue here!

gazi4430 avatar Mar 05 '25 13:03 gazi4430

Please fix this! I'm using this in my application and my customer success guys are on my back! Having the same issue

Aegeanm avatar Mar 05 '25 13:03 Aegeanm

I did not dig further in the issue to understand why, but I patch a quick fix that worked for me.

in @react-pdf/textkit/lib/textkit.js line 2834 lastFont throw an undefined at some point.

I changed from if (lastIndex < string.length) to if (lastIndex < string.length && lastFont)

if (lastIndex < string.length && lastFont) {
    const fontSize = getFontSize(last(runs));
    res.push({
        start: lastIndex,
        end: string.length,
        attributes: {
            font: [lastFont],
            scale: fontSize / lastFont.unitsPerEm,
        },
    });
}

Hope this helps to solve the issue.

From the source it's at line 90 in packages/textkit/src/engines/fontSubstitution/index.ts.

m4xleb avatar Mar 05 '25 14:03 m4xleb

applied this but did not work for me. also did change codes with patch module method but could not fix it.

mAkifArs avatar Mar 05 '25 15:03 mAkifArs

applied this but did not work for me. also did change codes with patch module method but could not fix it.

@mAkifArs , in my case I was using vite and had to use vite --force to make sure it was not running with an old cache.

On my production docker in exec -it into it, edited the line and ran tsc && vite build to have it worked.

What are you building it with?

m4xleb avatar Mar 05 '25 15:03 m4xleb

I did not dig further in the issue to understand why, but I patch a quick fix that worked for me.

in @react-pdf/textkit/lib/textkit.js line 2834 lastFont throw an undefined at some point.

I changed from if (lastIndex < string.length) to if (lastIndex < string.length && lastFont)

if (lastIndex < string.length && lastFont) { const fontSize = getFontSize(last(runs)); res.push({ start: lastIndex, end: string.length, attributes: { font: [lastFont], scale: fontSize / lastFont.unitsPerEm, }, }); } Hope this helps to solve the issue.

From the source it's at line 90 in packages/textkit/src/engines/fontSubstitution/index.ts.

I did the same by taking the renderer to new release 4.03 and changing the same part of @m4xleb said. it is working right now. as i said i used patching method.

mAkifArs avatar Mar 06 '25 05:03 mAkifArs

Upgrading react-pdf/renderer to version 4.3.0 solved the bug for me

dadiazp avatar Mar 07 '25 13:03 dadiazp

For me too, 4.3.0 solved the bug

Mario8419 avatar Mar 07 '25 18:03 Mario8419

We were still having the problem on 4.3.0. The culprit was some bad CSS, where we had fontStyle: "bold", which is not a valid option for fontStyle. Fixing that and changing it to fontWeight: "bold" resolved the issue.

zack avatar Mar 20 '25 20:03 zack

Still having this issue after updating to the latest version and removing all the custom styles for my pdf.

This is the code I currently have:

import { Font } from "@react-pdf/renderer";

// Font.register({
//   family: "Montserrat",
//   fonts: [
//     {
//       src: "/fonts/montserrat/Montserrat-Bold.ttf",
//       fontWeight: "bold",
//       fontStyle: "normal",
//     },
//     {
//       src: "/fonts/montserrat/Montserrat-Regular.ttf",
//       fontWeight: "normal",
//       fontStyle: "normal",
//     },
//     {
//       src: "/fonts/montserrat/Montserrat-BoldItalic.ttf",
//       fontWeight: "bold",
//       fontStyle: "italic",
//     },
//     {
//       src: "/fonts/montserrat/Montserrat-Italic.ttf",
//       fontWeight: "normal",
//       fontStyle: "italic",
//     },
//     {
//       src: "/fonts/montserrat/Montserrat-Black.ttf",
//       fontWeight: "heavy",
//       fontStyle: "normal",
//     },
//   ],
// });


const styles = StyleSheet.create({
  page: {
    // marginTop: 0,
    // padding: 40,
    // fontFamily: "Montserrat",
  },
  header: {
    // marginTop: 0,
    // fontSize: 12,
    // fontWeight: "bold",
  },
  subheader: {
    // fontSize: 12,
    // fontWeight: "bold",
  },

  section: {
    // marginTop: 20,
    // marginBottom: 10,
  },
  heading1: {
    // fontSize: 24,
    // marginTop: 20,
    // marginBottom: 10,
    // fontWeight: "bold",
  },
  heading2: {
    // marginTop: 10,
    // marginBottom: 5,
    // fontSize: 20,
    // fontWeight: "bold",
  },
  heading3: {
    // marginTop: 10,
    // marginBottom: 10,
    // fontSize: 18,
    // fontWeight: "bold",
  },
  heading4: {
    // marginTop: 10,
    // marginBottom: 5,
    // fontSize: 16,
    // fontWeight: "bold",
  },
  text: {
    // fontSize: 12,
    // marginBottom: 10,
  },
  bold: {
    // fontSize: 12,
    // fontWeight: "bold",
  },
  italic: {
    // fontStyle: "italic",
    // fontSize: 12,
  },
  link: {
    // color: "blue",
    // textDecoration: "underline",
    //  marginLeft: 20,
    // display: "flex",
    // flexWrap: "wrap",
    // flex: 1,
  },
  list: {
    // marginLeft: 15,
    // marginBottom: 10,
  },
  ol: {
    // marginLeft: 15,
    // marginBottom: 10,
    // listStyleType: "decimal",
  },
  listItem: {
    // fontSize: 12,
    // marginBottom: 5,
  },
  logo: {
    // position: "absolute",
    // top: -20,
    // right: 0,
    // width: 160,
    // height: 40,
  },
  whiteSpace: {
    // marginBottom: 30,
  },
});

fmonper1 avatar Apr 29 '25 00:04 fmonper1

We were still having the issue after trying to upgrade to 4.3.0 but it didn't fix the issue. Then we downgraded to 3.4.5 and it fixed the issue.

jobayed003 avatar Apr 29 '25 18:04 jobayed003

Why is this closed this still an issue

kevinlbatchelor avatar Jul 21 '25 22:07 kevinlbatchelor

in our case it was emojis being unable to render into the PDF. filtering the emojis out of text worked

alegian avatar Aug 18 '25 11:08 alegian

I've uploaded a simple fix Thanks to @m4xleb suggestion. Here you can find the issue: https://github.com/diegomura/react-pdf/issues/3237

Pasquale007 avatar Oct 30 '25 10:10 Pasquale007