简体   繁体   English

FPDF 创建一个 pdf 文件,每次迭代都会多出 1 页

[英]FPDF creates a pdf file with 1 extra page with every iteration

I've got a function from FPDF library to create pdf.我从 FPDF 库中获得了 function 来创建 pdf。 Let's say, i have 4 orders and i need to create pdf for each of them, so i loop through them,比方说,我有 4 个订单,我需要为每个订单创建 pdf,所以我遍历它们,

orders = [10, 11, 12, 13]
for o in orders: 
    generate_pdf(o)

Function generate_pdf: Function generate_pdf:

from fpdf import FPDF
pdf = FPDF()
def generate_pdf(DokId):
    pdf.add_page()
    header = "Order #{}".format(DokId)
    
    pdf.set_font('Arial', 'B', 20)
    w = pdf.get_string_width(header) + 6
    pdf.set_x((210 - w) / 2)
    pdf.cell(w, 9, header, 0, 0, 'C')
    pdf.line(20, 18, 210-20, 18)
    pdf.output('{}.pdf'.format(DokId), 'F')
    return None

For first el in my list i've got file "10.pdf" with 1 page, for the next one - 2 pages, etc. How to avoid this case and create only one page for each order number in a loop?对于我列表中的第一个 el,我有 1 页的文件“10.pdf”,下一个 - 2 页等。如何避免这种情况并在循环中为每个订单号只创建一个页面

Thanks in advance提前致谢

I haven't used FPDF but I'm guessing the issue is that you are re-usig the same pdf object every time, and so after every call to add_page you add another page to the same document instead of a new one.我没有使用过 FPDF,但我猜问题是您每次都在重新使用相同的 pdf object,因此每次调用 add_page 后,您都会在同一文档中添加另一个页面而不是新页面。

Try adding尝试添加

pdf = FPDF()

before your pdf.add_page() call.在您的 pdf.add_page() 调用之前。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM