Reportlab:如何在纵向和横向之间切换?

发布于 2024-11-05 05:42:42 字数 2047 浏览 4 评论 0原文

我正在使用reportlab 从动态数据自动生成pdf 报告。由于内容有时太大而无法纵向显示,因此我尝试切换到横向以显示大内容。

以下是我的报告生成的工作原理:

主要功能:

doc = DocTemplate(...)           //Doctemplate is a customed BaseDocTemplate class
array = []
some_data= "Here is some data displayed in portrait" 

array.append(Paragraph(some_data))

large_data = "this data is too large to be displayed in portrait"
array.append(Paragraph(large_data))

... // Some more data is added after this

doc.build(array, canvasmaker=NumberedCanvas)

我正在寻找一种能够在每一步从纵向切换到横向的方法,因为我不知道显示它需要多少页数。我对reportlab还是个新手,甚至对python也有点陌生,所以我不知道如何正确使用reportlab(PageTemplates、flowables)提供的解决方案,因为我最后正在构建整个文档。

以下是针对这种情况的其他有用的类:

class DocTemplate(BaseDocTemplate, ):
def __init__(self, filename, **kw):
    apply(BaseDocTemplate.__init__, (self, filename), kw)
    f = Frame(2.6*cm, 2.8*cm, 16*cm, 22.7*cm, id='f')
    pt = PageTemplate('RectPage', [f], onPage=beforeDrawPage, onPageEnd=afterDrawPage)
    //beforeDrawPage and afterDrawPage fill the headers of the page (that also need to be in landscape)
    self.addPageTemplates(pt)

我想我应该添加另一个页面模板或框架,但我不知道如何在数据附加阶段从一个模板或框架切换到另一个。

class NumberedCanvas(canvas.Canvas):
def __init__(self, *args, **kwargs):
    canvas.Canvas.__init__(self, *args, **kwargs)

    self._saved_page_states = []

def showPage(self):
    self._saved_page_states.append(dict(self.__dict__))
    self._startPage()

def save(self):
    """add page info to each page (page x of y)"""
    num_pages = len(self._saved_page_states)
    for state in self._saved_page_states:
        self.__dict__.update(state)
        self.draw_page_number(num_pages)
        canvas.Canvas.showPage(self)
    self.setTitle("Title")
    canvas.Canvas.save(self)
    self._doc.SaveToFile(self._filename, self)

def draw_page_number(self, page_count):
    self.setFont("Helvetica", 11)
    self.drawRightString(18.5*cm, 26.8*cm,
        "PAGE %d / %d" % (self._pageNumber, page_count))

我希望我没有忘记任何需要澄清的事情。

非常感谢。

I am using reportlab to generate a pdf report automatically from dynamic data. As the content sometimes is too large to be displayed in portrait, I am trying to switch to landscape for large content.

Here is how my report generation works :

Main function :

doc = DocTemplate(...)           //Doctemplate is a customed BaseDocTemplate class
array = []
some_data= "Here is some data displayed in portrait" 

array.append(Paragraph(some_data))

large_data = "this data is too large to be displayed in portrait"
array.append(Paragraph(large_data))

... // Some more data is added after this

doc.build(array, canvasmaker=NumberedCanvas)

What I am looking for is a way to be able to switch from portrait to landscape at each step, as I don't know the number of pages that will be needed to display it. I am still new to reportlab and even a bit with python, so I do not see how I can use the solutions provided by reportlab (PageTemplates, flowables) properly as I am building the whole document at the end.

Here are my other useful classes for this case :

class DocTemplate(BaseDocTemplate, ):
def __init__(self, filename, **kw):
    apply(BaseDocTemplate.__init__, (self, filename), kw)
    f = Frame(2.6*cm, 2.8*cm, 16*cm, 22.7*cm, id='f')
    pt = PageTemplate('RectPage', [f], onPage=beforeDrawPage, onPageEnd=afterDrawPage)
    //beforeDrawPage and afterDrawPage fill the headers of the page (that also need to be in landscape)
    self.addPageTemplates(pt)

I think I shall add another page template or frame, but I don't see how i can switch from one to the other during the data appending phase.

class NumberedCanvas(canvas.Canvas):
def __init__(self, *args, **kwargs):
    canvas.Canvas.__init__(self, *args, **kwargs)

    self._saved_page_states = []

def showPage(self):
    self._saved_page_states.append(dict(self.__dict__))
    self._startPage()

def save(self):
    """add page info to each page (page x of y)"""
    num_pages = len(self._saved_page_states)
    for state in self._saved_page_states:
        self.__dict__.update(state)
        self.draw_page_number(num_pages)
        canvas.Canvas.showPage(self)
    self.setTitle("Title")
    canvas.Canvas.save(self)
    self._doc.SaveToFile(self._filename, self)

def draw_page_number(self, page_count):
    self.setFont("Helvetica", 11)
    self.drawRightString(18.5*cm, 26.8*cm,
        "PAGE %d / %d" % (self._pageNumber, page_count))

I hope I did'nt forgot anything to be clear.

Many thanks in advance.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

把时间冻结 2024-11-12 05:42:42

使用页面大小模块中已有的横向和纵向功能。

from reportlab.lib.pagesizes import letter, landscape
c = canvas.Canvas(file, pagesize=landscape(letter))

Use the landscape and portrait functions that are already in the pagesizes module.

from reportlab.lib.pagesizes import letter, landscape
c = canvas.Canvas(file, pagesize=landscape(letter))
那一片橙海, 2024-11-12 05:42:42

我终于自己找到了最好的方法:

我在 DocTemplate 中添加了一个具有横向设置的新 PageTemplate,然后简单地使用了 reportlab.platypus 包中的 NextPageTemplate :

array.append(NextPageTemplate('landscape') )

为了恢复纵向,我使用:

array.append(NextPageTemplate('portrait'))

这提供了相当好的灵活性。

I finally figured out the best way to do it by myself :

I added a new PageTemplate in my DocTemplate with landscape settings, and then simply used NextPageTemplate from the reportlab.platypus package :

array.append(NextPageTemplate('landscape'))

To get back in portrait, i use :

array.append(NextPageTemplate('portrait'))

This allows a pretty nice flexibility.

秋千易 2024-11-12 05:42:42

这就是我在纵向和横向模式之间切换的方式,但我事先确定了哪个方向:

from reportlab.lib.pagesizes import letter, A4

lWidth, lHeight = letter

if orientation == 'landscape':
    canvas.setPageSize((lHeight, lWidth))
else:
    canvas.setPageSize((lWidth, lHeight))

This is how I switch between portrait and landscape modes, but I determine which orientation beforehand:

from reportlab.lib.pagesizes import letter, A4

lWidth, lHeight = letter

if orientation == 'landscape':
    canvas.setPageSize((lHeight, lWidth))
else:
    canvas.setPageSize((lWidth, lHeight))
格子衫的從容 2024-11-12 05:42:42
doc=SimpleDocTemplate(..., pagesize=(A4[1],A4[0]))
doc=SimpleDocTemplate(..., pagesize=(A4[1],A4[0]))
隔岸观火 2024-11-12 05:42:42

此外,如果有人正在寻找另一种在横向和纵向之间切换的方法,您还可以将旋转作为关键字参数传递给 BaseDocTemplate。

self._document = BaseDocTemplate(self._filename,
                                 pageSize=self._page_size,
                                 topMargin=1.5*cm,
                                 bottomMargin=1.5*cm,
                                 leftMargin=1*cm,
                                 rightMargin=1*cm,
                                 rotation=90,
                                 showBoundary=False
                                 )

Also if anyone was looking for another way to change between landscape and portrait, you can also pass in the rotation as a keyword argument to BaseDocTemplate.

self._document = BaseDocTemplate(self._filename,
                                 pageSize=self._page_size,
                                 topMargin=1.5*cm,
                                 bottomMargin=1.5*cm,
                                 leftMargin=1*cm,
                                 rightMargin=1*cm,
                                 rotation=90,
                                 showBoundary=False
                                 )
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文