乐闻世界logo
搜索文章和话题

How to add custom font in react pdf

1个答案

1

Adding custom fonts to PDF in a React project typically involves using libraries to generate PDF files, such as react-pdf. Here, I will detail how to use the @react-pdf/renderer library to add custom fonts to PDF documents.

Step 1: Installing @react-pdf/renderer

First, ensure that @react-pdf/renderer is installed in your React project. If not, install it using npm or yarn:

bash
npm install @react-pdf/renderer # or yarn add @react-pdf/renderer

Step 2: Download and Import Your Custom Fonts

Ensure you have the copyright permissions to use these fonts. After downloading the font files (typically in .ttf or .otf format), place them in your project, such as in the src/fonts directory.

Step 3: Register Fonts

In your project, use the Font.register method to register fonts. You can do this in a centralized configuration file, such as src/pdfFontSetup.js:

javascript
import { Font } from '@react-pdf/renderer'; Font.register({ family: 'OpenSans', src: require('./fonts/OpenSans-Regular.ttf'), }); Font.register({ family: 'OpenSans Bold', src: require('./fonts/OpenSans-Bold.ttf'), });

Step 4: Using Custom Fonts in PDF Documents

In your PDF component file, ensure that the custom font configuration file is imported, and then use font-family to specify the font in the document:

javascript
import React from 'react'; import { Document, Page, Text, StyleSheet } from '@react-pdf/renderer'; import './pdfFontSetup'; // Import font configuration const styles = StyleSheet.create({ body: { fontFamily: 'OpenSans', // Use registered font }, title: { fontFamily: 'OpenSans Bold', // Use registered bold font fontSize: 24, } }); const MyDocument = () => ( <Document> <Page size="A4" style={styles.body}> <Text style={styles.title}>This is a title using custom fonts.</Text> <Text>This is the body text, using regular OpenSans font.</Text> </Page> </Document> ); export default MyDocument;

Important Notes

  • Ensure you have the copyright permissions for custom fonts; only use fonts permitted for your project.
  • Verify that the paths and font file names are correct.
  • Ensure the path to the font configuration is correct.

By following these steps, you can use custom fonts in PDF files within your React project, making the documents align better with personal or corporate branding.

2024年6月29日 12:07 回复

你的答案