Search This Blog

Wednesday, June 30, 2021

Python - Image to Pdf

1. Install img2pdf

> pip/pip3 install img2pdf

2. img2pdfown.py


# importing necessary libraries

import img2pdf

from PIL import Image

import os

  

# CLI  img2pdf *jpg -o output_all_pngs.pdf

'''

img_path = "image1.jpg";

pdf_path = "output.pdf";

image = Image.open(img_path);

pdf_bytes = img2pdf.convert(image.filename);

file = open(pdf_path, "wb");

file.write(pdf_bytes);

image.close();

file.close();

'''


# convert all files ending in .jpg inside a directory

dirname = "dump/images/"

imgs = []

#dpix = dpiy = 300;

#layout_fun = img2pdf.get_fixed_dpi_layout_fun((dpix, dpiy))

for fname in os.listdir(dirname):

    if not fname.endswith(".jpg"):

        continue

    path = os.path.join(dirname, fname)

    if os.path.isdir(path):

        continue

    imgs.append(path)

    print ("\n" + path);

with open("dump/output.pdf", "wb") as f:

    #f.write(img2pdf.convert(imgs, layout_fun=layout_fun));

    f.write(img2pdf.convert(imgs));

  

'''    

imgs = ['dump/images/page_1.jpg', 'dump/images/page_2.jpg', 'dump/images/page_10.jpg']

with open("dump/output1.pdf", "wb") as f:

    f.write(img2pdf.convert(imgs))


# specify paper size (A4)

a4inpt = (img2pdf.mm_to_pt(210), img2pdf.mm_to_pt(297))

layout_fun = img2pdf.get_layout_fun(a4inpt)

with open("name.pdf", "wb") as f:

    f.write(img2pdf.convert('test.jpg', layout_fun=layout_fun))


# use a fixed dpi of 300 instead of reading it from the image

dpix = dpiy = 300;

layout_fun = img2pdf.get_fixed_dpi_layout_fun((dpix, dpiy))

with open("name.pdf", "wb") as f:

    f.write(img2pdf.convert('test.jpg', layout_fun=layout_fun))


# create a PDF/A-1b compliant document by passing an ICC profile

with open("name.pdf", "wb") as f:

    f.write(img2pdf.convert('test.jpg', pdfa="/usr/share/color/icc/sRGB.icc"))    

'''

    


No comments:

Hit Counter


View My Stats