Gangmax Blog

Convert Images to PDF and Vice Versa

The content below comes from ChatGPT’s answers.

Images to PDF

First method, you can use the command line tool “ImageMagick“.

1
2
3
4
5
# Before running, make sure you image files are named in order,
# such as "001.jpg", "002.jpg", "003.jpg" and so on.
magick *.jpg comic.pdf
# OR:
magick *.png comic.pdf

The second method, you can use Python script with the “Pillow“ library support.

comic.py
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
from PIL import Image
import os
import sys


def convert(image_folder: str, target_pdf: str) -> None:
# Get list of image files.
image_files = sorted(
[f for f in os.listdir(image_folder) if f.lower().endswith(('.jpg', '.png'))]
)
images = []
for file in image_files:
img_path = os.path.join(image_folder, file)
img = Image.open(img_path).convert('RGB')
images.append(img)
# Save all images to a single PDF.
if images:
images[0].save(target_pdf, save_all=True, append_images=images[1:])


if __name__ == '__main__':
if len(sys.argv) < 3:
print('Usage: python comic.py <image_folder> <target_pdf>')
exit(0)
convert(sys.argv[1], sys.argv[2])
print('Done.')

PDF to Images

The easiest way seems to use the command line tool “pdfimages” provided by “poppler“.

1
2
3
4
5
6
7
8
9
10
11
12
13
# Install "poppler" on macOS:
brew install poppler
# Or on Debian/Ubuntu:
sudo apt install poppler-utils
# Run the following commands to extract images from PDF file.
# The "prefix" value below will be used to name the extracted
# image file. With the command above, you will get image files
# with name like:
# prefix-000.jpg
# prefix-001.jpg
# prefix-002.jpg
# ...
pdfimages -all comic.pdf prefix

The questions I sent to ChatGPT were:

  1. How to convert a batch of comic image files in “jpg/png” formats into a single PDF file?

  2. Is there a way to extract images from a PDF file?

Comments