生成一页PDF

#coding=utf-8
import fitz

doc = fitz.open()
page = doc.new_page()
font = "SimHei"
text = "你好,世界!"

page.insert_text((100, 100), text, fontname=font)
doc.save("example.pdf")

给pdf添加页码

#coding=utf-8

import fitz

def add_pagnums(pdfpath, outpath):

    pdf_doc = fitz.open(pdfpath)

    for pg in range(pdf_doc.page_count):
        page = pdf_doc[pg]

        pagenum = pg+1
        pos = fitz.Point(580, 450) # 页面右下角
        text = f"Page {pagenum} of {pdf_doc.page_count}"
        arrows = '[]'
        # 绘制文本
        page.insert_text(pos, text, fontsize=10, fill=(0,0,0), fontname="helv", render_mode=0, rotate=90)


    pdf_doc.save(outpath)
    pdf_doc.close()

if __name__ == "__main__":
    add_pagnums("input.pdf", "example_with_page_number.pdf")

在pdf的第一页生成目录

#coding=utf-8

import fitz

def add_pagnums(pdfpath, outpath):
    pdf_doc = fitz.open(pdfpath)

    # 创建一个空的目录
    toc = []

    for pg in range(pdf_doc.page_count):
        page = pdf_doc[pg]

        pagenum = pg+1
        pos = fitz.Point(580, 450) # 页面右下角
        text = f"Page {pagenum} of {pdf_doc.page_count}"
        arrows = '[]'
        # 绘制文本
        page.insert_text(pos, text, fontsize=10, fill=(0,0,0), fontname="helv", render_mode=0, rotate=90)

        # 查找“金奖”、“银奖”、“铜奖”所在的页面
        if "金奖" in page.get_text("text").lower():
            title = "金奖"
            toc.append([title, None, pg])
        elif "银奖" in page.get_text("text").lower():
            title = "银奖"
            toc.append([title, None, pg])
        elif "铜奖" in page.get_text("text").lower():
            title = "铜奖"
            toc.append([title, None, pg])

    if len(toc) > 0:
        first_page = pdf_doc[0]
        first_pos = fitz.Point(50, 800) # 页面左上角
        first_text = "目录\n\n"
        for i, item in enumerate(toc):
            title, _, pg = item
            page_num = pg + 1
            text = "{:<4}{}{:^10}\n".format(i+1, title, page_num)
            first_text += text
        # 绘制文本
        first_page.insert_text(first_pos, first_text, fontsize=20, fill=(0,0,0), fontname="helv", rotate=90)
    pdf_doc.save(outpath)
    pdf_doc.close()
if __name__ == "__main__":
    add_pagnums("input.pdf", "example_with_toc.pdf")

fitz库的遗憾

中文经常不支持,以“…”来代替,非常遗憾。
尝试其他办法,仍不能解决,如需用到中文字体,可以用其他库代替。。。
font = “SimHei”

Logo

腾讯云面向开发者汇聚海量精品云计算使用和开发经验,营造开放的云计算技术生态圈。

更多推荐