skip to Main Content

I’m trying to make a PDF that uses the courier font, but the file doesn’t change to it

const styles = StyleSheet.create({
    text: {
      fontFamily: "Courier"
    }
  });

const MakePDF = () => {
    return (<Document><Page size="A4"><View>
                    <Text style={styles.text}>test</Text>
                </View></Page></Document>)}

export default ExportPDF

it keeps just using the default font. I’ve already tried importing directly from a file on the computer, but it still doesn’t work

2

Answers


  1. React Native’s built-in stylesheet does not directly control the font behavior in generated PDFs.

    try installing the react-pdf package with

    npm i @react-pdf/renderer
    

    and import the stylesheet and Font:

    import {Document, Page, StyleSheet, Font} from '@react-pdf/renderer';
    

    make sure to download the font from google fonts https://fonts.google.com/

    place this code before your Stylesheet to use Courier as font

    import CourierRegular from './styles/pdfFonts/Courier.ttf';
    
     Font.register({
          family: 'Courier',
          fonts: [{ {src: CourierRegular}],
        });
    

    Maintain the existing styles. By following these steps, you should be able to successfully use the Courier font in your React Native PDF generation using @react-pdf/renderer.

    Login or Signup to reply.
  2. One of the simplest ways to check your React-PDF functions is via the repl.
    https://react-pdf.org/repl

    There is no such Font as Courier as it is an PDF Alias for Monospaced fonts provided by the Platform Hardware (Windows has that as a FON file not a TTF).

    Google fonts provide a substitute called CourierPrime and you can download that and use it rather than a CDN font.

    enter image description here
    enter image description here

    Here is the working code but do use your own local ttf.

    Font.register({
      family: 'CourierPrime',
      src: 'https://raw.githubusercontent.com/quoteunquoteapps/CourierPrime/master/fonts/ttf/CourierPrime-Regular.ttf',
     });
    
    const styles = StyleSheet.create({
      body: {
        paddingTop: 35,
        paddingBottom: 65,
        paddingHorizontal: 35,
      },
      title: {
        fontSize: 24,
        textAlign: 'center',
        fontFamily: 'CourierPrime',  
        color: 'red',
      },
      author: {
        fontSize: 12,
        textAlign: 'center',
        fontFamily: 'CourierPrime',
        marginBottom: 40,
      },
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search