forked from pymupdf/PyMuPDF-Utilities
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathall-my-pics-inserted.py
84 lines (69 loc) · 2.14 KB
/
all-my-pics-inserted.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
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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
"""
@created: 2018-09-02 18:00:00
@author: (c) 2018 Jorj X. McKie
Create a PDF with images as its pages
-------------------------------------------------------------------------------
Dependencies:
-------------
PyMuPDF
PySimpleGUI, optional: requires Python 3 if used
License:
--------
GNU GPL V3+
Description
------------
Take all images in a file directory and make a PDF page from each image.
Pages retain the dimension of the image shown.
"""
from __future__ import print_function
import os, time, sys, fitz
print(fitz.__doc__)
# do some adjustments whether Python v2 or v3
if str is not bytes:
import PySimpleGUI as psg
mytime = time.perf_counter
else:
mytime = time.clock
rc = False
if str is bytes:
imgdir = sys.argv[1] # where my files are
else:
imgdir = psg.PopupGetFolder(
"Make a PDF from Embedded Files", "Enter file directory:"
)
if not imgdir:
raise SystemExit()
t0 = mytime() # set start timer
doc = fitz.open() # PDF with the pictures
imglist = os.listdir(imgdir) # list of them
imgcount = len(imglist) # pic count
for i, f in enumerate(imglist):
path = os.path.join(imgdir, f)
if not os.path.isfile(path):
print("skipping non-file '%s'!" % f)
continue
if str is not bytes:
psg.OneLineProgressMeter(
"Inserting Images", # show our progress
i + 1,
imgcount,
"dir: " + imgdir,
"file: " + f,
)
else:
print("inserting file '%s', (%i / %i)" % (f, i + 1, imgcount))
try:
img = fitz.open(os.path.join(imgdir, f)) # open pic as document
rect = img[0].rect # pic dimension
pdfbytes = img.convertToPDF() # make a PDF stream
img.close() # no longer needed
imgPDF = fitz.open("pdf", pdfbytes) # open stream as PDF
page = doc.newPage(
width=rect.width, height=rect.height # new page with ...
) # pic dimension
page.showPDFpage(rect, imgPDF, 0) # image fills the page
except:
print("unsupported document '%s'!" % f)
doc.save("all-my-inserted-pics.pdf")
t1 = mytime()
print("%g" % (t1 - t0), "sec processing time")