Is it possible to load a custom font only when online? #1294
-
My app works offline as well as online. I'm hoping to be able to print a pdf while offline, but I'm running into a roadblock with the custom font, as I've tried registering the font ( Any ideas on how to approach this? I'm thinking maybe a font fallback would be a nice feature of the library, so I could submit an issue for it too. |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment
-
I kind of answered my own question. I tried put this logic in // This runs on every render in the document component
// font files are imported like: import nunitoRegular from './fonts/Nunito-Regular.ttf'
if(window.navigator.onLine){
Font.register({
family: 'Nunito',
fonts: [
{ src: nunitoRegular }, // font-style: normal, font-weight: normal
{ src: nunitoItalic, fontStyle: 'italic' },
{ src: nunitoSemiBold, fontWeight: 600 },
]
})
}
else{
// remove fontFamily attribute, to prevent throwing errors about not finding the font.
const newPageStyles = {...rawStyles.page}
delete newPageStyles.fontFamily
rawStyles.page = newPageStyles
}
const styles = StyleSheet.create(rawStyles)
return (
<Document title={`Document Title Here`}>
<Page size="LETTER" style={styles.page}>
// the rest... |
Beta Was this translation helpful? Give feedback.
I kind of answered my own question. I tried put this logic in
useEffect
so it would only run once. This was throwing errors about missing props fromreact-pdf
. So I had to move it out of the hook. I'm registering fonts and creating theStyleSheet
in the component on every render. Not ideal, but it works 🤷♂️. If anybody has a better idea, let me know! I think if there was a font fallback similar to how the browser behaves it would be best.