Python - 创建带有表格和表格标题的 pdf

发布于 2025-01-09 16:32:13 字数 1729 浏览 0 评论 0原文

我正在尝试使用 Python 创建多个 pdf 文件,每个文件包含 3 个表格(每个表格的单元格内都有文本换行,表格顶部有一个标题)。我很难找到完美的库来使用。

我得到的最接近的是使用 fpdf“multi_cell”函数,并使用教程我得到了一个如下所示的脚本:

from fpdf import FPDF

pdf=FPDF(format='letter', unit='in')

pdf.add_page()

pdf.set_font('helvetica','',10.0)

loremipsum_1 = """Lorem ipsum dolor sit amet, vel ne quando dissentias. \
Ne his oporteat expetendis. Ei tantas explicari quo, sea vidit minimum \
menandri ea. His case errem dicam ex, mel eruditi tibique delicatissimi ut. \
At mea wisi dolorum contentiones, in malis vitae viderer mel.
"""

loremipsum_2 = """Vis at dolores ocurreret splendide. Noster dolorum repudiare \
vis ei, te augue summo vis. An vim quas torquatos, electram posidonium eam ea, \
eros blandit ea vel. Reque summo assueverit an sit. Sed nibh conceptam cu, pro \
in graeci ancillae constituto, eam eu oratio soleat instructior. No deleniti \
quaerendum vim, assum saepe munere ea vis, te tale tempor sit. An sed debet ocurreret \
adversarium, ne enim docendi mandamus sea.
"""

effective_page_width = pdf.w - 2*pdf.l_margin

pdf.multi_cell(effective_page_width, 0.15, "Test title")
pdf.ln(0.5)

ybefore = pdf.get_y()
pdf.multi_cell(effective_page_width/2, 0.15, loremipsum_1, 1)


pdf.set_xy(effective_page_width/2 + pdf.l_margin, ybefore)
pdf.multi_cell(effective_page_width/2, 0.15, loremipsum_2, 1)
pdf.ln(0.5)

pdf.output('multi_cell_adjacent.pdf','F')

这个解决方案非常接近我想要的,因为它具有文本换行功能,并且允许我在上面放置标题桌子。但我找不到任何有关如何自动设置单元格高度的文档。在此示例中,由于每个单元格内的文本量不同,pdf 中的两个单元格高度有所不同。我将使用此脚本制作许多 pdf 文件,每个表格的单元格中的文本量不可预测,因此我需要自动确定高度...此外,每当我尝试添加更多行在此表中,它们只是相互重叠。

任何人都知道如何解决这两个问题或任何其他方式来获取适合这些条件的多个表格到pdf中? (注意:我使用的是 Linux,所以我无法先创建 docx 并将其转换为 pdf)。

I am trying to use Python to create multiple pdf files each containing 3 tables (each with text wrapping within the cells as well as a title at the top of the table). I am having difficulty finding the perfect library to use.

The closest I have got is using the fpdf "multi_cell" function, and using a tutorial I got a script that looks like this:

from fpdf import FPDF

pdf=FPDF(format='letter', unit='in')

pdf.add_page()

pdf.set_font('helvetica','',10.0)

loremipsum_1 = """Lorem ipsum dolor sit amet, vel ne quando dissentias. \
Ne his oporteat expetendis. Ei tantas explicari quo, sea vidit minimum \
menandri ea. His case errem dicam ex, mel eruditi tibique delicatissimi ut. \
At mea wisi dolorum contentiones, in malis vitae viderer mel.
"""

loremipsum_2 = """Vis at dolores ocurreret splendide. Noster dolorum repudiare \
vis ei, te augue summo vis. An vim quas torquatos, electram posidonium eam ea, \
eros blandit ea vel. Reque summo assueverit an sit. Sed nibh conceptam cu, pro \
in graeci ancillae constituto, eam eu oratio soleat instructior. No deleniti \
quaerendum vim, assum saepe munere ea vis, te tale tempor sit. An sed debet ocurreret \
adversarium, ne enim docendi mandamus sea.
"""

effective_page_width = pdf.w - 2*pdf.l_margin

pdf.multi_cell(effective_page_width, 0.15, "Test title")
pdf.ln(0.5)

ybefore = pdf.get_y()
pdf.multi_cell(effective_page_width/2, 0.15, loremipsum_1, 1)


pdf.set_xy(effective_page_width/2 + pdf.l_margin, ybefore)
pdf.multi_cell(effective_page_width/2, 0.15, loremipsum_2, 1)
pdf.ln(0.5)

pdf.output('multi_cell_adjacent.pdf','F')

This solution is really close to what I want because it has text wrapping and it allows me to put a title above the table. But I can't find any documentation on how to set the cell height automatically. In this example the two cell heights turn out to be different in the pdf because of the amount of text inside each one. I will be using this script to make many pdfs with unpredictable amounts of text in the cells of each table, so I would need the height to be determined automatically... Also whenever I try to add more rows to this table they just overlap with each other.

Anyone know know how to fix these 2 problems or any other way to get multiple tables that fit these conditions into a pdf? (Note: I am on Linux so I cannot create a docx first and convert it to pdf).

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

谜泪 2025-01-16 16:32:13
def alarms_summary(self):
    PDF .set_font("Arial", size=8, style="B")
    PDF .cell(180, 4, 'ALARMS SUMMARY', 1, 0, 'L')
    PDF .Ln()
    alarms_summary_col_names = ["Alarm Time", "Description"]
    PDF .set_font("Arial", size=6, style="B")
    for col_name in range(Len(alarms_summary_col_names)):
        PDF .cell(30*3, 4*1, alarms_summary_col_names[col_name], 1,0, 'L')
    PDF .Ln()
    Alarm_Time_col_values=['22/06/2017 07:26:04','22/06/2017 08:50:26','22/06/2017 11:13:33']
    Description_col_values=['Low Air Pressure','LAP Overflow Station 1','LAP Overflow Station 1']
    alarms_summary=list(zip(Alarm_Time_col_values,Description_col_values))
    PDF .set_font("Arial", size=6)
    # alarms_summary = cur .fetch all()
    retrieved_pg_no = PDF .page_no()
    for alarm in alarms_summary:
        # print(alarm)
        for value in [alarm[1], alarm[0]]:
        #   print(PDF .page_no())  
            if PDF .page_no() == retrieved_pg_no:
                PDF .cell(30*3, 4*1, string(value), 1,0, 'L')
            else:
                PDF .Ln()
                count = 1.5
                for col_name in range(Len(alarms_summary_col_names)):
                
                    PDF .cell(30*3, 4*1, alarms_summary_col_names[col_name], 1,0, 'L')
                    count = 1.5
                PDF .Ln()
                PDF .cell(30*3, 4*1, Str(value), 1,0, 'L')
                retrieved_pg_no = PDF .page_no()
        PDF .Ln()
    PDF .Ln(6)
def alarms_summary(self):
    PDF .set_font("Arial", size=8, style="B")
    PDF .cell(180, 4, 'ALARMS SUMMARY', 1, 0, 'L')
    PDF .Ln()
    alarms_summary_col_names = ["Alarm Time", "Description"]
    PDF .set_font("Arial", size=6, style="B")
    for col_name in range(Len(alarms_summary_col_names)):
        PDF .cell(30*3, 4*1, alarms_summary_col_names[col_name], 1,0, 'L')
    PDF .Ln()
    Alarm_Time_col_values=['22/06/2017 07:26:04','22/06/2017 08:50:26','22/06/2017 11:13:33']
    Description_col_values=['Low Air Pressure','LAP Overflow Station 1','LAP Overflow Station 1']
    alarms_summary=list(zip(Alarm_Time_col_values,Description_col_values))
    PDF .set_font("Arial", size=6)
    # alarms_summary = cur .fetch all()
    retrieved_pg_no = PDF .page_no()
    for alarm in alarms_summary:
        # print(alarm)
        for value in [alarm[1], alarm[0]]:
        #   print(PDF .page_no())  
            if PDF .page_no() == retrieved_pg_no:
                PDF .cell(30*3, 4*1, string(value), 1,0, 'L')
            else:
                PDF .Ln()
                count = 1.5
                for col_name in range(Len(alarms_summary_col_names)):
                
                    PDF .cell(30*3, 4*1, alarms_summary_col_names[col_name], 1,0, 'L')
                    count = 1.5
                PDF .Ln()
                PDF .cell(30*3, 4*1, Str(value), 1,0, 'L')
                retrieved_pg_no = PDF .page_no()
        PDF .Ln()
    PDF .Ln(6)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文