Search code examples
pythonfpdf

Python FPDF How to display in 2 columns and to not split addresses when a new page is created


''' The module should read addresses from a text file, lay them out in two columns ready for printing on A4 self-adhesive paper.

The code I have is ok. But, I need it to display in 2 columns and to not split addresses when a new page is created.

The addresses vary in size from 4 to 7 lines of text.

I've examined other's code but can't work out how to achieve my goal. Any help would be much appreciated. '''

import os,sys
from fpdf import FPDF

pdf = FPDF()
pdf.add_page()
pdf.set_font('arial', '', 14)
w = 80

file = open(os.path.join(sys.path[0], 'addressbookMultiPrint.txt'))
for i, line in enumerate(file.readlines()):
    
    if i == 0:
        pdf.cell(w, 3, '', 'TLR', 1)
        
    pdf.cell(w, 7, line, 'LR', 1)
    
    if line == '\n':
        pdf.cell(w, 1, '', 'BLR', 1)
        pdf.cell(w, 3, ' ', 0, 1)
        pdf.cell(w, 3, '', 'TLR', 1)

pdf.output('single.pdf')
os.startfile('single.pdf')#,'print')

Solution

  • The best way is to use HTML.

    You need to make a table in HTML.

    1. Import HTMLMixin. Don't forget to install FPDF2

      pip install fpdf2

      from fpdf import FPDF, HTMLMixin

    2. Now we need variable with all HTML code

        html = '''
        <table width="100%">
        <tr><th width="50%">Header #1</th><th width="50%">Header #2</th></tr>
        '''
    

    You may change 100% in the table if you don't want to make it so wide.

    In th you may also change 50% if some of columns should be wider, but in total it must be 100%. (Even if your table is not 100%)

    1. Your code with data
    html += "<tr><td>" + name + "</td><td>" + surname + "</td></tr>"
    
    1. Don't forget to close the table tag
    html += "</table>"
    
    1. Now, when all HTML is ready, pass it to the new class
    class PDF(FPDF, HTMLMixin):
        pass
    
    pdf = FPDF()
    pdf.add_page()
    pdf.set_font('arial', '', 14)
    pdf.write_html(html)
    pdf.output('single.pdf', 'F')
    

    For more info check this