Skip to main content
 首页 » 编程设计

python之reportlab之无法在实际打印的页面中将上边距设置为零

2025年05月04日8cyq1162

我正在使用 reportlab 3.0 生成付款表格,其中严格定义了每个项目的位置。即使我设置了 topMargin = 0,reportlab 也会强制设置 topMargin。我可以调整底部边距,但顶部边距(或我无法打印的区域)约为 12 毫米,如果它在代码中设置为零。如果我将上边距设置为负数,文本就会开始消失。我想知道,我错过了什么。我会张贴图片,但被张贴了一些帖子,我无法做到这一点。我在使用 SimpleDocTemplate 时遇到了这个问题,只是使用 Canvas 或从 BaseDocTemplate 制作文档。我为使最高边距正确所做的最新尝试:

from reportlab.lib.pagesizes import A4 
from reportlab.platypus import BaseDocTemplate,PageTemplate, Frame 
doc = BaseDocTemplate("pdf_file",showBoundary=1,leftMargin=0, rightMargin=0, topMargin=0, bottomMargin=0, pagesize=A4) 
frameT = Frame(self.doc.leftMargin, self.doc.bottomMargin, self.doc.width, self.doc.height,    topPadding=0, id='normal') 
time = Paragraph('16:37',self.styles["normal"]) 
doc.build([time])  

事情变得有趣了,因为我能够将底部边距设置为零并打印到边框,但是在顶部有一个不可打印的区域,这确实造成了麻烦

更新: 在使用多台打印机进行测试后,我注意到打印机驱动程序会根据自己的标准强制设置边距。例如,对于 HP deskjet,顶部有很大的余量。通过播放音阶设置,可以稍微调整边距,但不能太好。

请您参考如下方法:

也许是打印驱动程序...我有一份报告,我将我的 TopMargin 从 0.4 * 英寸更改为 0.0 * 英寸,它在顶部排成一行。

from reportlab.platypus import SimpleDocTemplate, Paragraph, Spacer, Table, TableStyle, Preformatted, XPreformatted 
from reportlab.rl_config import defaultPageSize 
from reportlab.lib.units import inch 
 
PAGE_HEIGHT = defaultPageSize[1]; PAGE_WIDTH = defaultPageSize[0] 
BottomMargin = 0.4 * inch 
TopMargin = 0.4 * inch 
LeftMargin = .1 * inch   
RightMargin = .1 * inch 
ContentBottomMargin = TopMargin + 0.25 * inch 
ContentTopMargin = BottomMargin + 0.35 * inch 
ContentLeftMargin = LeftMargin  
ContentRightMargin = RightMargin  

如您所见,这些是我的常规默认值,但我更改了 TopMargin = 0.0 * inch 并且它起作用了。

也许这是我为 PAGE_HEIGHT 导入 defaultPageSize[1] 和为页面大小导入 A4 之间的区别?