Search code examples
pythonreportlab

drawString doesn't print


I try to use enter link description here this to generate page nums.

The most important part:

   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
                           )

And it works:

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)

But if I uncomment the NextPageTemplate line - page number disappears BUT LINE IS STILL VISIBLE....

Have no idea why NextpageTemplate vanish page number....


Solution

  • The problem is that you are setting the fill color to that bluish gray when you draw the background, and leaving it there. The "fill color" is what is used to draw strings, so your text IS being drawn, it's just being drawn in your background color.

    Add

            self.setFillGray(0)
    

    in your draw_page_number routine before drawing the text. Or, perhaps do that in your setBackground function just before exiting, to restore the default.