How to get MultiCells in Pyfpdf Side by side?

Question:

I am making a table of about 10 cells with headings in them. They will not fit accross the page unless I use multi_cell option. However I cant figure out How to get a multi_cell side by side. When I make a new one it autmatically goes to the next line

from fpdf import FPDF
import webbrowser

pdf=FPDF()
pdf.add_page()
pdf.set_font('Arial','B',16)
pdf.multi_cell(40,10,'Hello World!,how are you today',1,0)

pdf.multi_cell(100,10,'This cell needs to beside the other',1,0)

pdf.output('tuto1.pdf','F')


webbrowser.open_new('tuto1.pdf')
Asked By: WAMPS

||

Answers:

You will have to keep track of x and y coordinates:

from fpdf import FPDF
import webbrowser

pdf=FPDF()
pdf.add_page()
pdf.set_font('Arial','B',16)

# Save top coordinate
top = pdf.y

# Calculate x position of next cell
offset = pdf.x + 40

pdf.multi_cell(40,10,'Hello World!,how are you today',1,0)

# Reset y coordinate
pdf.y = top

# Move to computed offset
pdf.x = offset 

pdf.multi_cell(100,10,'This cell needs to beside the other',1,0)

pdf.output('tuto1.pdf','F')

webbrowser.open_new('tuto1.pdf')
Answered By: Edwood Ocasio

NOTE : This is an alternate approach to the above problem

For my requirement, i need some of the columns to have higher column width and some columns with lower width. Fixed column width for all the columns is making my table to go out of the pdf margin. Multi cell wraps the text and increase the column height only for certain columns and not every column. So my approach was to use the enumerate function and dynamically adjust the column width according to the needs as shown below.

data1 = list(csv.reader(csvfile))
print(data1) ##[[row1],[row2],[row3],[row4]] 
## row1, row2, etc are the rows from csv

for row in data1:
    for x,y in enumerate(row):
        if (x == 0) or (x == 1): ## dynamically change the column width with certain conditions
            pdf.cell(2.0, 0.15, str(y), align = 'C', border=1) ## width = 2.0
        else:
            pdf.cell(0.60, 0.15, str(y), align = 'L', border=1) ## width = 0.60

Hope this helps.

Answered By: Shudharsanan
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.