Skip to content

Commit

Permalink
text_inserter: improve arrangement of parameters
Browse files Browse the repository at this point in the history
Separate harfbuzz and pdfium parameters.
  • Loading branch information
mara004 committed May 9, 2022
1 parent dfeb613 commit 25869c1
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 28 deletions.
42 changes: 17 additions & 25 deletions src/pypdfium2/_helpers/text_inserter.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,54 +16,46 @@

class FontInfo:
"""
Object to load font data and store associated information.
Object to cache harfbuzz font data.
Parameters:
path (str):
font_path (str):
File path of the font to use.
type (int):
Type of the given font (``FPDF_FONT_TYPE1`` or ``FPDF_FONT_TRUETYPE``).
is_cid (bool):
:data:`True` if the font is a CID font, :data:`False` otherwise.
"""

def __init__(self, path, type, is_cid):

def __init__(self, font_path):
if not have_harfbuzz:
raise RuntimeError("Font helpers require uharfbuzz to be installed.")

self.path = path
self.type = type
self.is_cid = is_cid

with open(self.path, "rb") as fh:
self.data = fh.read()

self.hb_blob = harfbuzz.Blob.from_file_path(self.path)
self.hb_blob = harfbuzz.Blob.from_file_path(font_path)
self.hb_face = harfbuzz.Face(self.hb_blob)
self.hb_font = harfbuzz.Font(self.hb_face)
self.hb_scale = self.hb_font.scale[0]


def open_pdffont(pdf, font_info):
def open_pdffont(pdf, font_path, type, is_cid):
"""
Create a PDFium font object handle. When you have finished working with the font, call :func:`.close_pdffont`.
Parameters:
pdf (``FPDF_DOCUMENT``):
PDFium document handle.
font_info (FontInfo):
Font data and information.
font_path (str):
File path of the font to use.
type (int):
Type of the given font (``FPDF_FONT_TYPE1`` or ``FPDF_FONT_TRUETYPE``).
is_cid (bool):
:data:`True` if the font is a CID font, :data:`False` otherwise.
Returns:
``FPDF_FONT``
"""
with open(font_path, "rb") as fh:
data = fh.read()
return pdfium.FPDFText_LoadFont(
pdf,
ctypes.cast(font_info.data, ctypes.POINTER(ctypes.c_uint8)),
len(font_info.data),
font_info.type,
font_info.is_cid,
ctypes.cast(data, ctypes.POINTER(ctypes.c_uint8)),
len(data),
type,
is_cid,
)


Expand Down
7 changes: 4 additions & 3 deletions tests/helpers/test_textinserter.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,12 +15,13 @@ def test_insert_text():
pdf = pdfium.FPDF_CreateNewDocument()
pdfium.FPDFPage_New(pdf, 0, 500, 800)

font_info = pdfium.FontInfo(
join(ResourceDir, "NotoSans-Regular.ttf"),
NotoSans = join(ResourceDir, "NotoSans-Regular.ttf")
font_info = pdfium.FontInfo(NotoSans)
pdf_font = pdfium.open_pdffont(
pdf, NotoSans,
type = pdfium.FPDF_FONT_TRUETYPE,
is_cid = True,
)
pdf_font = pdfium.open_pdffont(pdf, font_info)

pdfium.insert_text(
pdf, 0,
Expand Down

0 comments on commit 25869c1

Please sign in to comment.