I want to create a set of pdfs for different subjects, all with the same basic structure. After constructing a working chunk of code, I moved that into a function.

As soon as the function is called I get

"FPDF Exception: Content cannot be added on a finalized document, after calling output()"

I thought it was something to do with creating multiple pdf docs, but it seems not. The exact same code put into the loop works fine.

any ideas what is going on here?

  pdf = FPDF(orientation='L', unit='mm', format='A4')
  pdf.add_page()
  pdf.set_font('helvetica', size=12)

  # Margin
  m = 10
  # Page width: Width of A4 is 210mm
  pw = 210 - 2*m
  # Cell height
  ch = 50
  pdf = FPDF(orientation='P', unit='mm', format='A4')
  pdf.add_page()
  pdf.set_font('helvetica', 'B',size=16)
  pdf.cell(w=0, h=ch/2, txt=subject, border=1, new_x=XPos.LMARGIN, new_y=YPos.NEXT)
  pdf.set_font('helvetica', 'B',size=10)

  pdfTablePrep(hotspot_df)

  pdf.set_font('helvetica', 'B',size=16)
  pdf.cell(w=0, h=ch/4, txt= "Behaviour Distribution", border=0, new_x=XPos.LMARGIN, new_y=YPos.NEXT)
  pdf.cell(w=0, h=ch/4, txt= "Behaviour incidents", border=0, new_x=XPos.LMARGIN, new_y=YPos.NEXT)
  pdf.set_font('helvetica', 'B',size=8)
  pdfTablePrep(filtered_sub_df)

  pdf.output(f'./{subject}.pdf')

so the only difference is that there a

def create_doc(subject):

at the beginning of the function version, called by

create_doc('Science')

I really cant work out why it would be different when the whole chunk is just put inside the main loop, instead of the function call.

1

There are 1 best solutions below

0
On

turned out to be really poor programming style - I didn't pass the pdf to the table generating functions, just ran them on their own.

Changing the signature to

pdfTablePrep(subject, pdf)

fixed the problem