drawString 不打印

drawString doesn't print

我尝试使用enter link description here这个来生成页码。

最重要的部分:

   class PageNumCanvas(canvas.Canvas):
        """
        http://code.activestate.com/recipes/546511-page-x-of-y-with-reportlab/
        http://code.activestate.com/recipes/576832/
        """
        #----------------------------------------------------------------------
        def __init__(self, *args, **kwargs):
            """Constructor"""
            super().__init__(*args, **kwargs)
            self.pages = []

        #----------------------------------------------------------------------
        def showPage(self):
            """
            On a page break, add information to the list
            """
            self.pages.append(dict(self.__dict__))
            self._startPage()

        #----------------------------------------------------------------------
        def save(self):
            """
            Add the page number to each page (page x of y)
            """
            page_count = len(self.pages)

            for page in self.pages:
                self.__dict__.update(page)
                self.draw_page_number(page_count)
                super().showPage()

            super().save()

        #----------------------------------------------------------------------
        def draw_page_number(self, page_count):
            """
            Add the page number
            """
            self.line(10*mm, 78, 200*mm, 78)
            if (self._pageNumber % 2) == 0:
                self.drawString(15*mm, 15*mm, '{}'.format(self._pageNumber))
            else:
                self.drawRightString(195*mm, 15*mm, '{}'.format(self._pageNumber))

  class MyDocTemplate(SimpleDocTemplate):
        def __init__(self, filename, **kw):
            self.allowSplitting = 1
            super().__init__(filename, **kw)

            def setBackground(canvas, doc):
                color = PCMYKColor(5,3,0,8)
                canvas.setFillColor(color)
                canvas.rect(0,0,doc.width+doc.leftMargin+doc.rightMargin,doc.height+doc.topMargin+doc.bottomMargin, fill=True, stroke=False)


            #Two Columns
            frame1 = Frame(self.leftMargin, self.bottomMargin, self.width/2-6, self.height, id='col1')
            frame2 = Frame(self.leftMargin+self.width/2+6, self.bottomMargin, self.width/2-6, self.height, id='col2')
            frameT = Frame(self.leftMargin, self.bottomMargin, self.width, self.height, id='normal')

            frame1a = Frame(self.leftMargin, self.bottomMargin, self.width/2-6, self.height/2-6, id='col1a')
            frame2a = Frame(self.leftMargin+self.width/2+6, self.bottomMargin, self.width/2-6, self.height/2-6, id='col2a')
            frameTa = Frame(self.leftMargin, self.bottomMargin+self.height/2+6, self.width, self.height/2-6, id='normala')

            self.addPageTemplates([
                PageTemplate(id='OneCol',frames=frameT, onPage=setBackground),
                PageTemplate(id='TwoCol',frames=[frame1,frame2], onPage=setBackground),
                PageTemplate(id='OneAndTwoCol',frames=[frameTa,frame1a,frame2a], onPage=setBackground),
            ])

        def afterFlowable(self, flowable):
            "Registers TOC entries."

            if flowable.__class__.__name__ == 'Paragraph':
                text = flowable.getPlainText()
                style = flowable.style.name

                if style == 'TOCheading':
                    key = 'h2-%s' % self.seq.nextf('TOCheading')
                    self.canv.bookmarkPage(key)
                    self.notify('TOCEntry', (0, text, self.page, key))

    doc = MyDocTemplate(buffer,showBoundary=0, leftMargin=2*cm, rightMargin=2*cm, topMargin=2*cm, bottomMargin=2*cm)
    styles=getSampleStyleSheet()

    heading= ParagraphStyle('heading',
                           parent=styles['Heading2'],
                           fontName = 'LiberationSansBold',
                           textColor = PCMYKColor(98,46,0,84),
                           spaceAfter=5
                           )

有效:

Story= []
Story.append(Paragraph("First Page", heading))
#Story.append(NextPageTemplate('OneCol'))
Story.append(PageBreak())

Story.append(Paragraph("Middle Page", heading))
#Story.append(NextPageTemplate('OneCol'))
Story.append(PageBreak())
Story.append(Paragraph("Last Page", heading))

#start the construction of the pdf
doc.multiBuild(Story, canvasmaker=PageNumCanvas)

但是,如果我取消注释 NextPageTemplate 行 - 页码消失,但该行仍然可见....

不知道为什么 NextpageTemplate 会消失页码....

问题是您在绘制背景时将填充颜色设置为蓝灰色,并将其保留在那里。 “填充颜色”是用来绘制字符串的,所以你的文本正在被绘制,它只是被绘制成你的背景颜色。

添加

        self.setFillGray(0)

在您的 draw_page_number 例程中绘制文本之前。或者,也许在退出之前在 setBackground 函数中执行此操作以恢复默认值。