-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpng2pdf.py
More file actions
52 lines (43 loc) · 1.72 KB
/
png2pdf.py
File metadata and controls
52 lines (43 loc) · 1.72 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
# Python3 program to convert image to pdf
# using img2pdf library
# usage python3 png2pdf <input directory> <output_filename>
# importing necessary libraries
import img2pdf
import re
import os
import sys
# Set the input and output paths
input_folder = sys.argv[1]
output_file = sys.argv[2]
def extract_number(filename):
match = re.search(r'\d+', filename)
if match:
return int(match.group())
return 0 # Default if no number found
def create_pdf_from_png_directory(directory_path, output_pdf_name):
"""
Converts all PNG images in a specified directory into a single PDF file.
Args:
directory_path (str): The path to the directory containing PNG images.
output_pdf_name (str): The name of the output PDF file.
"""
image_files = []
for filename in os.listdir(directory_path):
if filename.lower().endswith(".png"):
image_files.append(os.path.join(directory_path, filename))
# Sort the image files to ensure consistent page order in the PDF
sorted_filenames = sorted(image_files, key=extract_number)
if not image_files:
print(f"No PNG images found in '{directory_path}'.")
return
try:
with open(output_pdf_name, "wb") as f:
f.write(img2pdf.convert(sorted_filenames))
print(f"PDF '{output_pdf_name}' created successfully from images in '{directory_path}'.")
except Exception as e:
print(f"Error creating PDF: {e}")
# Example usage:
# Replace 'your_image_directory' with the actual path to your directory of PNGs
# and 'my_document.pdf' with your desired output PDF name.
output_filename=os.path.join(input_folder,output_file)
create_pdf_from_png_directory(input_folder, output_filename)