Search code examples
pythonexcelpdfopenpyxlreportlab

Generate pdf with reportlab using python


I'm generating PDF files through ReportLab, input file is in excel, if cell value as blank generated as NONE in pdf. I want to convert NONE value into blank.

Any Solution regarding this according to my code. This Pdf built through reportlab using python

code

import openpyxl
from reportlab.pdfgen import canvas
wb = openpyxl.load_workbook (r'Input.xlsx', data_only=True )
sheet = wb['Sheet1']
ws = wb.active

y1= 100
x= 200
x1 = 700

    def main():
        for i in range ( 2, 42 ):
           amount1 = sheet.cell(row=i, column=1).value
           amount2 = sheet.cell(row=i, column=2).value
           amount3 = sheet.cell(row=i, column=3).value
           amount4 = sheet.cell(row=i, column=4).value
           amount5 = sheet.cell(row=i, column=5).value
           c = canvas.Canvas('output.pdf')
    
           y =1500
           c.setFont ( 'Helvetica', 12 )
           c.drawString ( x,y, 'Component1' )
           c.drawString ( x1, y, str ( amount1 ) )
           y -= y1

           c.drawString ( x,y, 'Component2' )
           c.drawString ( x1,y, str ( amount2 ) )
           y -= y1

           c.drawString ( x,y, 'Component3' )
           c.drawString ( x1, y, str ( amount3) )
           y -= y1

           c.drawString ( x,y, Component4' )
           c.drawString ( x1, y, str ( amount4 ) )
           y -= y1
        
           c.drawString ( x, y, 'Component5' )
           c.drawString ( x1, y, str ( amount5 ) )
           y -= y1

    if __name__ == "__main__":
       main ()

My output

In pdf value generated as None, but want to convert as blank output


Solution

  • When there's a function that does almost what you need but not exactly it's common practice to write your own function, that calls original function generally, but under some conditions behaves differently. Those behaviour can be introduced with conditional statements.

    def str_(value):
        if value is None:
            return ''
        return str(value)
    
    c.drawString ( x,y, 'Component2' )
    c.drawString ( x1,y, str_( amount2 ) )