0

I've question: Why program below, doesn't generate 107 different pages?:

import PyPDF2
import os
from fpdf import FPDF
from reportlab.pdfgen import canvas
from reportlab.lib.units import mm
from reportlab.lib.pagesizes import A4, landscape

font_h = 55*mm
page_width = 297*mm
page_height = 210*mm

lista = []

for i in range(1,108):
    lista.append(str(i))

pdfWriter = PyPDF2.PdfWriter()

for number in lista:
    myCanvas = canvas.Canvas('new.pdf', pagesize = landscape(A4))
    myCanvas.setFont('Helvetica-Bold', font_h)
    myCanvas.drawString(page_width/2 - myCanvas.stringWidth(number)/2, page_height/2 - font_h, number)
    myCanvas.save()
    pdfIn = open('new.pdf', 'rb')
    pdfReader = PyPDF2.PdfReader(pdfIn)
    page = pdfReader.pages[0]
    pdfWriter.add_page(page)
    pdfIn.close()

pdfOut = open('wynik.pdf', 'wb')
pdfWriter.write(pdfOut)
pdfOut.close()

os.startfile('wynik.pdf')

Some of them have the same number. Every time, when I start program different pages change. When I print variable 'number' in loop 'for', every varible is correct.

Robert
  • 1
  • 3

1 Answers1

0

I get all 107 pages, each with the correct page number.

I would strongly suggest you write the new pdf to an in-memory buffer, instead of to disk (which is very slow, relatively). See io.BytesIO

Also, instead of explicitly calling .close(), open the file with a with statement. It will implicitly be called at the end of the block. See 7.2. Reading and Writing Files:

It is good practice to use the with keyword when dealing with file objects. The advantage is that the file is properly closed after its suite finishes, even if an exception is raised at some point. Using with is also much shorter than writing equivalent try-finally blocks

import PyPDF2
import os
from fpdf import FPDF
from reportlab.pdfgen import canvas
from reportlab.lib.units import mm
from reportlab.lib.pagesizes import A4, landscape
from io import BytesIO
font_h = 55*mm
page_width = 297*mm
page_height = 210*mm

lista = []

for i in range(1,108):
    lista.append(str(i))

pdfWriter = PyPDF2.PdfWriter()

for number in lista:
    new_pdf = BytesIO()
    myCanvas = canvas.Canvas(new_pdf, pagesize = landscape(A4))
    myCanvas.setFont('Helvetica-Bold', font_h)
    myCanvas.drawString(page_width/2 - myCanvas.stringWidth(number)/2, page_height/2 - font_h, number)
    myCanvas.save()
    
    pdfReader = PyPDF2.PdfReader(new_pdf)
    page = pdfReader.pages[0]
    pdfWriter.add_page(page)

with open('wynik.pdf', 'wb') as pdfOut:
    pdfWriter.write(pdfOut)

os.startfile('wynik.pdf')
GordonAitchJay
  • 4,640
  • 1
  • 14
  • 16