首页 > 解决方案 > Python FPDF如何在2列中显示并且在创建新页面时不拆分地址

问题描述

''' 模块应该从文本文件中读取地址,将它们分成两列,准备在 A4 不干胶纸上打印。

我的代码没问题。但是,我需要它在 2 列中显示,并且在创建新页面时不拆分地址。

地址的大小从 4 到 7 行文本不等。

我检查了其他人的代码,但不知道如何实现我的目标。任何帮助将非常感激。'''

import os,sys
from fpdf import FPDF

pdf = FPDF()
pdf.add_page()
pdf.set_font('arial', '', 14)
w = 80

file = open(os.path.join(sys.path[0], 'addressbookMultiPrint.txt'))
for i, line in enumerate(file.readlines()):
    
    if i == 0:
        pdf.cell(w, 3, '', 'TLR', 1)
        
    pdf.cell(w, 7, line, 'LR', 1)
    
    if line == '\n':
        pdf.cell(w, 1, '', 'BLR', 1)
        pdf.cell(w, 3, ' ', 0, 1)
        pdf.cell(w, 3, '', 'TLR', 1)

pdf.output('single.pdf')
os.startfile('single.pdf')#,'print')

标签: pythonfpdf

解决方案


最好的方法是使用HTML

您需要在 HTML 中制作一个表格。

  1. 导入 HTMLMixin。不要忘记安装 FPDF2

    点安装 fpdf2

    from fpdf import FPDF, HTMLMixin

  2. 现在我们需要包含所有 HTML 代码的变量

    html = '''
    <table width="100%">
    <tr><th width="50%">Header #1</th><th width="50%">Header #2</th></tr>
    '''

如果您不想让它变得那么宽,您可以在表格中更改 100%。

如果某些列应该更宽,您也可以更改 50%,但总的来说它必须是 100 %。(即使你的桌子不是 100%)

  1. 您的代码与数据
html += "<tr><td>" + name + "</td><td>" + surname + "</td></tr>"
  1. 不要忘记关闭表格标签
html += "</table>"
  1. 现在,当所有 HTML 准备就绪后,将其传递给新类
class PDF(FPDF, HTMLMixin):
    pass

pdf = FPDF()
pdf.add_page()
pdf.set_font('arial', '', 14)
pdf.write_html(html)
pdf.output('single.pdf', 'F')

有关更多信息,请查看


推荐阅读