Converting images to PDF. Final file has blank pages before and after.

MRAB python at mrabarnett.plus.com
Mon Nov 30 21:15:00 EST 2020


On 2020-12-01 01:20, Michael Baca wrote:
> Hello, new to the group, rather new to programming.
> 
> I'm writing a program that takes images and converts them into PDF's. It works after quite a few days of trying, however the final file has a blank page inserted before and after each page containing the images.
> 
> This uses FPDF to do the conversion. I've been up and down trying to figure out where I'm adding an extra page, so it might be an FPDF issue.
> 
> def multi_convert(pdf_Filename, file_path):
>      if (dir):
>          file_list = []
>          print(""), print("")
>          print("Converting... This may take awhile depending on the number of images.")
>          
>          for entry in os.scandir(file_path):
>              if (entry.path.endswith(".jpg") or entry.path.endswith(".png")) and entry.is_file():
>                  file_list.append(entry.path)
>      else:
>          print("Error: ")
>          print("Invalid Directory - {}", dir)
>      cover = Image.open(str(file_list[0]))
>      width, height = cover.size
> 
>      pdf = FPDF(unit="pt", format=[width, height])
> 
>      for page in file_list:
>          pdf.add_page()
>          pdf.image(str(page))
> 
>      pdf.output(file_path + pdf_Filename + ".pdf", "F")
>      exit()
> 
It says in the documentation for the .image method:

"""
x:

Abscissa of the upper-left corner. If not specified or equal to None, 
the current abscissa is used (version 1.7.1 and up).

y:

Ordinate of the upper-left corner. If not specified or equal to None, 
the current ordinate is used; moreover, a page break is triggered first 
if necessary (in case automatic page breaking is enabled) and, after the 
call, the current ordinate is moved to the bottom of the image (version 
1.7.1 and up).
"""

In other words, you're not specifying where the top-left corner of the 
image should go, so it's putting it at the current position, wherever 
that is, and it's responding to the positioning by inserting additional 
pages.

The solution is to specify the images' positions, and, perhaps, also 
their sizes, if necessary.

By the way, why doesn't the function end with "exit()"? That'll make it 
exit the Python completely; rarely a good idea.


More information about the Python-list mailing list