Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

วิธีฝังฟอนต์ใน PDF ที่สร้างโดย Matplotlib

การฝังฟอนต์ (Embed Fonts) ใน PDF Output

ใช้ rcParams['pdf.fonttype'] = 42 เพื่อฝังฟอนต์เป็น TrueType (Type 42)

ขั้นตอนหลัก

  • ตั้งค่าขนาดรูปและ padding
  • ตั้งค่า plt.rcParams['pdf.fonttype'] = 42
  • สร้าง figure และ scatter plot
  • โหลดฟอนต์ TTF ด้วย font_manager.FontProperties
  • ตั้งค่า title ใช้ฟอนต์นั้น
  • บันทึกเป็น PDF ด้วย plt.savefig("demo.pdf")

ตัวอย่างโค้ด

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

plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True

plt.rcParams['pdf.fonttype'] = 42
fig, ax = plt.subplots()
x = np.random.rand(100)
y = np.random.rand(100)
ax.scatter(x, y, c=y, marker="v")

fprop = fm.FontProperties(fname=r'C:\Windows\Fonts\MISTRAL.TTF')
ax.set_title('Scatter Plot With Random Points',
             fontproperties=fprop, size=20, fontweight="bold")

plt.savefig("demo.pdf")

คำอธิบาย

  • pdf.fonttype=42: ใช้ TrueType fonts (editable ใน PDF)
  • pdf.fonttype=3: ใช้ Type 3 fonts (bitmap, ไม่แก้ไขได้)
  • fonttype=42 ทำให้ PDF สามารถค้นหา/คัดลอกข้อความได้