Embedding and Using Custom Fonts in PDF with Python ReportLab



How to Embed and Use Custom TrueType Fonts in PDFs with Python ReportLab #ArabicFont

Part I : using drawString 🔝

We will learn how to embed and use custom TrueType fonts in our PDF documents using Python's ReportLab library.

Step-by-Step Guide

  1. Import the necessary modules:
    import os  # to handle our font dir and path to font files.
    import reportlab
    from reportlab.pdfgen import canvas
    from reportlab.lib.pagesizes import letter
    from reportlab.pdfbase import pdfmetrics
    from reportlab.pdfbase.ttfonts import TTFont
  2. Get the folder containing the ReportLab library and add the fonts directory to the path:
    folder = os.path.dirname(reportlab.__file__)  # get the folder with path
    folder_font = os.path.join(folder, 'fonts')  # add fonts folder to path 
    print(folder_font)  # print the full path of font dir
  3. Define the path to the custom font file:
    custom_font = os.path.join(folder_font, 'Arabic.ttf')  # Path to the font file
  4. Register the custom font with ReportLab:
    c_font = TTFont('Arabic', custom_font)
    pdfmetrics.registerFont(c_font)
  5. Define the output file path and create a canvas object:
    my_path = 'D:\\testing\\my_pdf\\my_pdf.pdf'  # output file path
    c = canvas.Canvas(my_path, pagesize=letter, bottomup=0)
  6. Set the custom font and font size for the canvas:
    c.setFont('Arabic', 16)
  7. Write text using the custom font on the PDF canvas:
    msg = 'Welcome to plus2net'
    c.drawString(200, 200, msg)  # write text in page
  8. Save the current page and close the canvas to store the file:
    c.showPage()  # saves current page
    c.save()  # stores the file and closes the canvas

By following these steps, you can successfully embed and use custom TrueType fonts in your PDF documents using Python ReportLab. This technique allows for greater flexibility and customization when creating PDF files.

Full code is here
import os # to handle our font dir and path to font files.
import reportlab
from reportlab.pdfgen import canvas
from reportlab.lib.pagesizes import letter
from reportlab.pdfbase import pdfmetrics
from reportlab.pdfbase.ttfonts import TTFont

folder = os.path.dirname(reportlab.__file__) # get the folder with path
folder_font = os.path.join(folder, 'fonts') # add fonts folder to path 
print(folder_font) # print the full path of font dir 

custom_font=os.path.join(folder_font,'Arabic.ttf') # Path to the font file

c_font=TTFont('Arabic',custom_font) 
pdfmetrics.registerFont(c_font) 

my_path='D:\\testing\\my_pdf\\my_pdf.pdf'# output file path
c = canvas.Canvas(my_path,pagesize=letter,bottomup=0)
c.setFont('Arabic', 16)
msg ='Welcome to plus2net'
c.drawString(200,200,msg) # write text in page 
c.showPage() # saves current page
c.save() # stores the file and close  the canvas

Part II : using Paragraph 🔝

  1. Import Necessary Modules

    First, we import the required modules. These modules help us handle file paths, generate PDFs, and work with custom fonts and styles.

    import os  # to handle our font directory and path to font files.
    import reportlab
    from reportlab.pdfgen import canvas
    from reportlab.lib.pagesizes import letter, A4
    from reportlab.pdfbase import pdfmetrics
    from reportlab.pdfbase.ttfonts import TTFont
    from reportlab.lib.styles import ParagraphStyle
    from reportlab.platypus import Paragraph

    Explanation:

    • os: Handles file and directory paths.
    • reportlab: Provides the main library functions for PDF generation.
    • canvas: The object used to create the PDF.
    • pdfmetrics and TTFont: Handle the registration and usage of custom TrueType fonts.
    • ParagraphStyle and Paragraph: Allow you to apply custom styles to text in the PDF.
  1. Locate and Register the Custom Font

    We locate the folder where ReportLab's files are stored, find the fonts directory, and register our custom font.

    folder = os.path.dirname(reportlab.__file__)  # Get the directory where ReportLab is installed
    folder_font = os.path.join(folder, 'fonts')  # Path to the fonts directory
    print(folder_font)  # Optionally, print the font directory path
    
    custom_font = os.path.join(folder_font, 'AmrHindi Regular.ttf')  # Path to the custom font file
    c_font = TTFont('Hindi', custom_font)  # Register the font with an alias name 'Hindi'
    pdfmetrics.registerFont(c_font)  # Register the font in ReportLab

    Explanation:

    • os.path.dirname(reportlab.__file__): Gets the directory where the ReportLab module is located.
    • os.path.join(folder, 'fonts'): Constructs the full path to the fonts directory.
    • TTFont('Hindi', custom_font): Registers the custom font under the name 'Hindi'.
    • pdfmetrics.registerFont(c_font): Registers the font with ReportLab so it can be used in the PDF.
  1. Create the PDF Canvas

    We specify the output file path and create a canvas object that will be used to draw elements onto the PDF.

    my_path = 'D:\\testing\\my_pdf\\my_pdf.pdf'  # Path to save the generated PDF
    c = canvas.Canvas(my_path, pagesize=letter, bottomup=1)  # Create a canvas for the PDF with Letter size

    Explanation:

    • canvas.Canvas(my_path, pagesize=letter, bottomup=1): Creates a new PDF document at the specified path, with Letter size and the origin at the bottom-left corner.
  1. Define a Custom Paragraph Style

    We define a custom paragraph style to apply to the text in the PDF. This style includes the font, background color, border, padding, and alignment.

    my_Style = ParagraphStyle('My Para style',
                              fontName='Hindi',
                              backColor='#F1F1F1',
                              fontSize=10,
                              borderColor='#FFFF00',
                              borderWidth=2,
                              borderPadding=(20, 20, 20),
                              leading=20,
                              alignment=0)

    Explanation:

    • ParagraphStyle: Defines various styling properties for the paragraph.
    • fontName='Hindi': Specifies the custom font to be used.
    • backColor='#F1F1F1': Sets the background color.
    • fontSize=10': Sets the font size.
    • borderColor='#FFFF00': Defines the color of the border around the text.
    • borderWidth=2': Specifies the thickness of the border.
    • borderPadding=(20, 20, 20): Adds padding inside the border.
    • leading=20: Sets the line spacing (leading).
    • alignment=0: Aligns the text to the left.
  1. Define a Custom Paragraph Style

    We define a custom paragraph style to apply to the text in the PDF. This style includes the font, background color, border, padding, and alignment.

    my_Style = ParagraphStyle('My Para style',
                              fontName='Hindi',
                              backColor='#F1F1F1',
                              fontSize=10,
                              borderColor='#FFFF00',
                              borderWidth=2,
                              borderPadding=(20, 20, 20),
                              leading=20,
                              alignment=0)

    Explanation:

    • ParagraphStyle: Defines various styling properties for the paragraph.
    • fontName='Hindi': Specifies the custom font to be used.
    • backColor='#F1F1F1': Sets the background color.
    • fontSize=10': Sets the font size.
    • borderColor='#FFFF00': Defines the color of the border around the text.
    • borderWidth=2': Specifies the thickness of the border.
    • borderPadding=(20, 20, 20): Adds padding inside the border.
    • leading=20: Sets the line spacing (leading).
    • alignment=0: Aligns the text to the left.
  1. Save and Close the PDF

    Finally, we save the PDF and close the canvas, finalizing the document.

    c.save()  # Save and close the PDF document

    Explanation:

    • c.save(): Finalizes and writes the PDF to the file system, completing the document creation process.
Full code is here .
import os # to handle our font dir and path to font files.
import reportlab
from reportlab.pdfgen import canvas
from reportlab.lib.pagesizes import letter,A4
from reportlab.pdfbase import pdfmetrics
from reportlab.pdfbase.ttfonts import TTFont

from reportlab.lib.styles import ParagraphStyle
from reportlab.platypus import Paragraph

folder = os.path.dirname(reportlab.__file__) # get the folder with path
folder_font = os.path.join(folder, 'fonts') # add fonts folder to path 
print(folder_font) # print the full path of font dir 

custom_font=os.path.join(folder_font,'AmrHindi Regular.ttf') # Path to the font file
c_font=TTFont('Hindi',custom_font) 
pdfmetrics.registerFont(c_font) 

my_path='D:\\testing\\my_pdf\\my_pdf.pdf'# output file path
c = canvas.Canvas(my_path,pagesize=letter,bottomup=1)

my_Style=ParagraphStyle('My Para style',
fontName='Hindi',
backColor='#F1F1F1',
fontSize=10,
borderColor='#FFFF00',
borderWidth=2,
borderPadding=(20,20,20),
leading=20,
alignment=0
)

width,height=A4

p1=Paragraph('''<b>About this online classes </b><BR/>\
     Welcome to our online classes.<BR/> \
	 You can learn Python, PHP, database like MySQL \
SQLite and many more \
<font face="Hindi" color="blue">We are creating \
PDF by using ReportLab</font> \
<i>This is part of our Final report.</i>''',my_Style)

p1.wrapOn(c,300,50)
p1.drawOn(c,width-550,height-350)
c.save() # stores the file and close  the canvas
PDF Table from different data sources to PDF file
Bar charts in PDF Line charts in PDF Pie Charts Paragraph
Python

Subscribe to our YouTube Channel here


Subscribe

* indicates required
Subscribe to plus2net

    plus2net.com



    Post your comments , suggestion , error , requirements etc here





    Python Video Tutorials
    Python SQLite Video Tutorials
    Python MySQL Video Tutorials
    Python Tkinter Video Tutorials
    We use cookies to improve your browsing experience. . Learn more
    HTML MySQL PHP JavaScript ASP Photoshop Articles FORUM . Contact us
    ©2000-2024 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer