首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何使用pyfpdf生成目录?

如何使用pyfpdf生成目录?
EN

Stack Overflow用户
提问于 2022-09-07 09:42:05
回答 1查看 123关注 0票数 0

我希望你过得很好。

我想要生成一个PDF使用pyfpdf。

我需要在第一页生成一个目录。

如您所知,在PDF的末尾创建了新的页面。因此,我的内容表是在PDF的末尾生成的。

我无法在进程开始时生成内容表,因为它包含要转到页面的链接。要做到这一点,我需要知道什么是页码,所以我需要在目录之前生成所有其他页面。

为此,我尝试在开头创建一个空白页,然后创建其他页面,最后返回到第一页,以添加目录。但第一页仍然是空白的。

代码语言:javascript
复制
from fpdf import FPDF
from datetime import date

today = date.today()
today = today.strftime("%Y/%m/%d")

hardwareModel = ["hardwareModel1", "hardwareModel2", "hardwareModel3"]
snapshotNumber = ["N13100","N13101","N13102"]
firmwareVersion = ["1.8.0","1.8.1","1.8.2"]
websiteVersion = ["2.4.0","2.4.0","2.4.0"]
unifiedPackage = ["#38-20220624","#39-20220701","#40-20220829"]
stageDatabaseVersion = ["4.3.12","4.3.13","4.3.13"]
dateArray = ["2022/06/24","2022/07/01",today]

tableOfContents = []

class PDF(FPDF):
    def __init__(self):
        super().__init__()
        self.currentIndex = -1
        
    def titlePage(self, redScale, greenScale, blueScale, string):
        pdf.set_text_color(redScale, greenScale, blueScale)
        #Title
        self.cell(0, 10, txt = string , align = "L")
        self.drawLine(128, 196, 28, 1, 10, 50, 200, 50)

    def drawLine(self, redScale, greenScale, blueScale, lineWidth, x1, y1, x2, y2):
        pdf.set_draw_color(redScale, greenScale, blueScale)
        pdf.set_line_width(lineWidth)
        pdf.line(x1, y1, x2, y2)
    
    def tableOfContentsGenerator(self):
        self.page = 1
        print(self.page_no())
        self.set_y(0)
        self.set_text_color(0, 0, 0)
        print(self.get_y())
        self.ln(50)
        print(self.get_y())
        for elem in tableOfContents:
            newLink = self.add_link()
            self.set_link(newLink,y=0.0,page=elem[0])
            self.cell(0,10,elem[1],link=newLink)
            self.ln(5)
        
    def header(self):
        if self.currentIndex > -1 and self.currentIndex <= len(snapshotNumber)-1:
            tableOfContents.append((pdf.page_no(), hardwareModel[self.currentIndex] + "_" + snapshotNumber[self.currentIndex] + " (" + dateArray[self.currentIndex] + ")"))
            self.image('image.jpg', 0 , 0 , 210)
            pdf.set_font("helvetica", size = 20)
            self.ln(30)
            self.titlePage(0, 84, 136, hardwareModel[self.currentIndex] + "_" + str(snapshotNumber[self.currentIndex]) + " (" + today + ")")
            if self.currentIndex == len(snapshotNumber)-1:
                self.tableOfContentsGenerator()
        elif self.currentIndex == -1:
            pass
            
        self.currentIndex += 1

pdf = PDF()

pdf.set_title("titleTest")

pdf.add_page()
for elem in snapshotNumber:
    pdf.add_page()

pdf.output("test.pdf")

任何帮助都将不胜感激。

诚挚的问候

EN

回答 1

Stack Overflow用户

发布于 2022-09-13 23:57:51

使用fpdf2可以很容易地做到这一点

代码语言:javascript
复制
from fpdf import FPDF, TitleStyle


def p(pdf, text, **kwargs):
    "Inserts a paragraph"
    pdf.multi_cell(
        w=pdf.epw,
        h=pdf.font_size,
        txt=text,
        new_x="LMARGIN",
        new_y="NEXT",
        **kwargs,
    )

def render_toc(pdf, outline):
    pdf.y += 50
    pdf.set_font("Helvetica", size=16)
    pdf.underline = True
    p(pdf, "Table of contents:")
    pdf.underline = False
    pdf.y += 20
    pdf.set_font("Courier", size=12)
    for section in outline:
        link = pdf.add_link()
        pdf.set_link(link, page=section.page_number)
        p(pdf, f'{" " * section.level * 2} {section.name} {"." * (60 - section.level*2 - len(section.name))} {section.page_number}', align="C", link=link)

pdf = FPDF()
pdf.set_font("Helvetica")
pdf.set_section_title_styles(
    # Level 0 titles:
    TitleStyle(
        font_family="Times",
        font_style="B",
        font_size_pt=24,
        color=128,
        underline=True,
        t_margin=10,
        l_margin=10,
        b_margin=0,
    ),
)
pdf.add_page()
pdf.set_y(50)
pdf.set_font(size=40)
p(pdf, "Doc Title", align="C")
pdf.set_font(size=12)
pdf.insert_toc_placeholder(render_toc)
for i in range(10):
    pdf.start_section(f"Title {i}")
    p(pdf, "Lorem ipsum dolor sit amet, consectetur adipiscing elit,"
           " sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.")
pdf.output("toc-example.pdf")
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/73633254

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档