python - 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')
解决方案
最好的方法是使用HTML。
您需要在 HTML 中制作一个表格。
导入 HTMLMixin。不要忘记安装 FPDF2
点安装 fpdf2
from fpdf import FPDF, HTMLMixin
现在我们需要包含所有 HTML 代码的变量
html = '''
<table width="100%">
<tr><th width="50%">Header #1</th><th width="50%">Header #2</th></tr>
'''
如果您不想让它变得那么宽,您可以在表格中更改 100%。
如果某些列应该更宽,您也可以更改 50%,但总的来说它必须是 100 %。(即使你的桌子不是 100%)
- 您的代码与数据
html += "<tr><td>" + name + "</td><td>" + surname + "</td></tr>"
- 不要忘记关闭表格标签
html += "</table>"
- 现在,当所有 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')
有关更多信息,请查看此
推荐阅读
- amazon-ec2 - 从 ec2 实例连接 dynamodb 需要哪个 IAM 角色?
- c# - Quartz.net 3.4 - global.asax 中的开始工作不会触发
- javascript - 在加载时进行 jquery keyup 计算的最佳有效方法
- ios - AVPlayer HLS 直播 IOS
- iis - GCP 负载平衡器 502 服务器错误和“backend_connection_closed_before_data_sent_to_client”IIS 10
- java - @Formular 错误的解决方法
- batch-file - 批处理和如果错误
- angular - 如何将 matMenuTriggerFor 动态附加到 Angular 材质菜单中的 DOM 元素?
- sql - Excel 函数生成的 SQL 查询不起作用
- c++ - 是什么给了 std::future 一些共享状态