本文介绍了使用PyPDF将页码居中放置在页脚中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用PyPDF创建格式化的报告.我希望页码(例如第1页,共3页)位于页脚的中心,几乎完全与PyPDF教程的显示方式相同. 这是我正在参考的教程

I'm using PyPDF to create a formatted report. I want the page number (e.g. Page 1 of 3) to be centered in the footer, pretty much exactly how the PyPDF tutorial shows. Here's the tutorial I'm referencing.

下面是我在页脚方法中输入的代码:

Below is the code I put in the footer method:

def footer(self):
    genDateTime = "Report generated on: " + datetime.datetime.now().strftime('%m/%d/%Y %I:%M:%S %p')
    page = 'Page ' + str(self.page_no()) + '/{nb}'

    self.set_y(-10)
    self.set_font('Arial', '', 9)

    self.cell(0, 5, "Clinical Report: Confidential", 0, 0, 'L')
    self.cell(0, 5, page, 0, 0, 'C')
    self.cell(0, 5, genDateTime, 0, 0, 'R')

这是页面底部的屏幕截图.如您所见,机密"和日期时间"标签按预期显示,但是页面#"标签是正确的:

Here is a screenshot of the bottom of the page. As you can see, the Confidential and DateTime labels are showing up as expected, but the Page # label is right justified:

感谢您的帮助.

推荐答案

我认为问题在于您如何设置像元宽度.默认情况下,PyPDF从先前放置的单元格的最右边开始顺序放置单元格.调用self.cell()时,第一个参数是width -默认情况下,如果width为0,它将使宽度扩展到页面的最右边.因此,当您放置self.cell(0, 5, "Clinical Report: Confidential", 0, 0, 'L')时,该文本框将一直扩展到页面右侧.然后,当您尝试放置self.cell(0, 5, page, 0, 0, 'C')时,它将其居中在该行上的剩余空间中-但没有剩余空间,因此只能将其放置在末尾.尝试为第一个单元格设置一些宽度,如下所示:

I think the issue is with how you are setting cell width. PyPDF by default places cells sequentially, starting at the far right of the previously placed cell. When you call self.cell(), the first argument is width -- by default if width is 0, it makes the width extend to the far right of the page. So when you place self.cell(0, 5, "Clinical Report: Confidential", 0, 0, 'L'), that text box is extending all the way to the right of the page. Then when you try to place self.cell(0, 5, page, 0, 0, 'C'), it is centering it in the remaining space on that line -- but there is no space left so it just places it at the end. Try giving your first cell some width like this:

def footer(self):
    genDateTime = "Report generated on: " + datetime.datetime.now().strftime('%m/%d/%Y %I:%M:%S %p')
    page = 'Page ' + str(self.page_no()) + '/{nb}'

    self.set_y(-10)
    self.set_font('Arial', '', 9)

    self.cell(5, 5, "Clinical Report: Confidential", 0, 0, 'L')
    self.cell(0, 5, page, 0, 0, 'C')
    self.cell(0, 5, genDateTime, 0, 0, 'R')

您可能必须使宽度大于5才能显示所有文本,但是您可以使用它.

You might have to make the width greater than 5 to display all your text, but you can play with that.

这篇关于使用PyPDF将页码居中放置在页脚中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-16 04:03