react-pdf
react-pdf copied to clipboard
renderToString don't catch fonts
Describe the bug
renderToString don't catch custom fonts
To Reproduce
- Implement custom fonts
Font.register({
family: "Yantramanav",
fonts: [
{ src: "https://fonts.gstatic.com/s/yantramanav/v11/flU8Rqu5zY00QEpyWJYWN6f0.ttf", fontWeight: 400 },
{ src: "https://fonts.gstatic.com/s/yantramanav/v11/flUhRqu5zY00QEpyWJYWN59IeMNZ.ttf", fontWeight: 700 }
]
})
- Add it to StyleSheet
const styles = StyleSheet.create({
page: {
fontFamily: "Yantramanav"
})
const Invoice = () => (
<Document>
<Page size="A4" style={styles.page} dpi="96">
<Header />
<View />
<Footer />
</Page>
</Document>
)
- Generate invoice via renderToString
console.log(await renderToString(<Invoice />))
- write stdout to file
node ./index.js >> my-doc.pdf
- open my-doc.pdf, it's not open
Expected behavior my-doc.pdf opens with custom fonts
Way to fix it Im fix it using with piping stream into stdout, it works for me
import { pdf } from "@react-pdf/renderer"
const instance = pdf(<Invoice />)
const output = await instance.toBuffer()
output.pipe(process.stdout)
I'm having it too #1922
Does it help if you await Font.load({ fontFamily: 'Yantramanav', fontWeight: 400 }) after registering the font? This has helped in some other cases where a font would sometimes not render when reloading the page (https://github.com/diegomura/react-pdf/issues/1494#issuecomment-1059049772).
I'm having a similar issue when using react-pdf in Node. I noticed, renderToString() fails to render custom fonts (no text shows up), but renderToFile() works correctly.
The await Font.load() trick didn't help in my case. It had no effect.
Using @ArseniySushCorp's toBuffer() trick works as a workaround. For those coming across this issue that want to see a bit of code, here's what worked for me:
// This doesn't render custom fonts
import { renderToString } from "@react-pdf/renderer"
const pdf = await renderToString(<MyComponent />);
return res.status(200).setHeader('Content-Type', 'application/pdf').send(pdf);
// But this does
import { pdf } from "@react-pdf/renderer"
const instance = pdf(<MyComponent />);
const output = await instance.toBuffer();
return res.status(200).setHeader('Content-Type', 'application/pdf').send(output);
I'm also facing issues with react-pdf-testing-library, I cannot get any text rendered on the pdf. I assumed this has to do with this renderToStream, but I'm also using renderToStream in my application which works fine...
I have worked on a fix on the testing library. I have open a PR.
I've tried installing your version, but that doesn't solve the issue for me. No texts are rendered.
I will soon open source current testing library we are using. Hopefully it will fix it as it works well in our setup.