如何在PDF的底部(页脚)添加多行?

2024-03-29 04:38:07 发布

您现在位置:Python中文网/ 问答频道 /正文

我必须创建需要在左下角添加行(如页脚)的PDF文件。

以下代码正在工作:

import StringIO
from reportlab.pdfgen import canvas
import uuid

def test(pdf_file_name="abc.pdf", pdf_size=(432, 648), font_details=("Times-Roman", 9)):
    # create a new PDF with Reportla 
    text_to_add = "I am writing here.."
    new_pdf = "test_%s.pdf"%(str(uuid.uuid4()))

    packet = StringIO.StringIO() 
    packet.seek(0)

    c = canvas.Canvas(pdf_file_name, pagesize = pdf_size)
    #- Get the length of text in a PDF. 
    text_len = c.stringWidth(text_to_add, font_details[0], font_details[1])
    #- take margin 20 and 20 in both axis 
    #- Adjust starting point on x axis according to  text_len
    x = pdf_size[0]-20  -  text_len
    y = 20 
    #- set font.
    c.setFont(font_details[0], font_details[1])
    #- write text,
    c.drawString(x, y, text_to_add)

    c.showPage()
    c.save()
    return pdf_file_name

现在,若文本有多行,那个么这是不起作用的,因为文本的长度大于页面大小的宽度。理解。在

我尝试使用Frameparagraph,但仍然无法在PDF中正确的位置写入文本

代码如下:

^{pr2}$

不明白为什么页面大小会改变,因为我设置了(432, 648),但却是显示(288.0, 504.0)

doc.leftMargin: 72.0
doc.bottomMargin: 72.0
doc.width: 288.0
doc.height: 504.0

还有帧大小:

w, h: 288.0 96
doc.leftMargin: 72.0

不知道如何解决这个问题。 我引用this链接


Tags: totextname文本importaddsizedoc
1条回答
网友
1楼 · 发布于 2024-03-29 04:38:07

首先,关于doc.width的谜团,doc.width不是文档的实际宽度。它是页边距之间区域的宽度,因此在本例中doc.width + doc.leftMargin + doc.rightMargin等于实际页面的宽度。在

你为什么不想把整个页脚的宽度改成现在的样子。这是因为与上述相同的问题,即doc.width不是实际的纸张宽度。在

假设整个页面

def footer(canvas, doc):
    canvas.saveState()

    P = Paragraph("This is a multi-line footer.  It goes on every page.  " * 10, styleN)

    # Notice the letter[0] which is the width of the letter page size
    w, h = P.wrap(letter[0] - 20, doc.bottomMargin)

    P.drawOn(canvas, 10, 10)
    canvas.restoreState()

假设您希望页脚跨越可写区域的宽度

注意:默认设置的边距非常大,所以边上有那么多空白。在

^{pr2}$

编辑:

因为知道正常文本应该从哪里开始可能会有用。我们需要计算出我们脚的高度。在正常情况下,我们不能使用P.height,因为它取决于文本的宽度,调用它将引发AttributeError。在

在我们的例子中,我们实际上可以直接从P.wrap(即h)或在调用P.wrap之后调用P.height来获得页脚的高度。在

从页脚的高度开始我们的Frame,我们就不会有重叠的文本。但是,记住将Frame的高度设置为doc.height - footer.height,以确保文本不会被放在页面之外。在

相关问题 更多 >