Python3 使用 PyMuPDF 库提取pdf中的字体文件

先安装 PyMuPDF 库:

pip install PyMuPDF

 

示例:

import fitz

def extract_fonts(pdf_path):
    with fitz.open(pdf_path) as doc:
        num_pages = doc.page_count
        fonts = []

        for page_number in range(num_pages):
            font_info = doc.get_page_fonts(page_number, True)
            for font_tuple in font_info:
                # 打印所有字体信息
                # print(font_tuple)

                font_xref = font_tuple[0]
                font_ext  = font_tuple[1]
                font_type = font_tuple[2]
                font_name = font_tuple[3]

                if font_type != 'Type3':
                    if fonts.count(font_name) == 0:
                        font_data = doc.extract_font(font_xref)
                        # print(font_data)
                        with open(f"{font_name}.{font_ext}", 'wb') as font_file:
                            font_file.write(font_data[3])
                            fonts.append(font_name)
                        
        print(fonts)

pdf_path = 'sample.pdf'
extract_fonts(pdf_path)

 

 

 

文档:https://pymupdf.readthedocs.io/en/latest/index.html

 

posted @ 2024-01-15 17:29  kjcy8  阅读(248)  评论(0编辑  收藏  举报