How to embed fonts in PDFs produced by Matplotlib

To embed fonts in PDFs produced by Matplotlib, we use plt.rcParams['pdf.fonttype'] = 42. This ensures fonts are embedded as TrueType fonts, making PDFs portable and maintaining consistent appearance across different systems.

Setting Font Embedding Parameters

The key parameter pdf.fonttype = 42 embeds TrueType fonts directly into the PDF. Alternative value 3 converts fonts to Type 3 fonts, but 42 preserves better quality ?

import matplotlib.pyplot as plt

# Enable font embedding
plt.rcParams['pdf.fonttype'] = 42
plt.rcParams['ps.fonttype'] = 42  # For EPS files too

print("Font embedding enabled for PDF export")
Font embedding enabled for PDF export

Complete Example with Custom Font

Here's how to create a scatter plot with embedded fonts using a custom font file ?

import numpy as np
import matplotlib.pyplot as plt
from matplotlib import font_manager as fm

# Configure figure and font embedding
plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True
plt.rcParams['pdf.fonttype'] = 42

# Create sample data
x = np.random.rand(50)
y = np.random.rand(50)

# Create the plot
fig, ax = plt.subplots()
ax.scatter(x, y, c=y, marker="o", alpha=0.7)

# Set title with system font
ax.set_title('Scatter Plot With Embedded Fonts', 
            fontsize=16, fontweight="bold")

ax.set_xlabel('X Values')
ax.set_ylabel('Y Values')

plt.tight_layout()
plt.show()

Using System Fonts

You can specify system fonts by name without needing the full file path ?

import matplotlib.pyplot as plt
import numpy as np

plt.rcParams['pdf.fonttype'] = 42

# Sample data
data = np.random.normal(0, 1, 1000)

# Create histogram
plt.figure(figsize=(8, 5))
plt.hist(data, bins=30, alpha=0.7, color='skyblue', edgecolor='black')

# Use specific font family
plt.title('Distribution with Embedded Font', fontfamily='serif', fontsize=14)
plt.xlabel('Values', fontfamily='sans-serif')
plt.ylabel('Frequency', fontfamily='sans-serif')

plt.tight_layout()
plt.show()

Font Type Comparison

Font Type Value Description Quality
Type 3 3 Bitmap fonts Lower quality, larger files
TrueType 42 Vector fonts embedded High quality, scalable

Key Benefits

  • Portability: PDFs display correctly on any system
  • Quality: Fonts remain crisp at any zoom level
  • Consistency: Text appears identical across different viewers
  • Professional: Essential for publications and presentations

Conclusion

Setting plt.rcParams['pdf.fonttype'] = 42 embeds TrueType fonts in PDFs, ensuring consistent appearance across systems. This is essential for professional documents and publications where font consistency matters.

Updated on: 2026-03-25T23:01:01+05:30

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements