/
topdf.py
111 lines (88 loc) · 2.74 KB
/
topdf.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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
# -*- coding: utf-8 -*-
import os
import glob
import StringIO
from PIL import Image as PilImage
from reportlab.pdfgen import canvas
from reportlab.lib.pagesizes import A4
from reportlab.lib.utils import ImageReader
def pil_to_rl(image, name):
output = StringIO.StringIO()
image.save(output, format='png')
contents = output.getvalue()
output.close()
return ImageReader(StringIO.StringIO(contents))
def physical_size(cols, rows):
a4_width = 210.0 # mm
size = a4_width * 0.95
return ((cols * size) / 1000, (rows * size) / 1000)
def print_image(canvas, image, name):
w, h = A4
canvas.drawImage(
pil_to_rl(image, name),
0,
0,
height=w * 0.95,
width=w * 0.95,
preserveAspectRatio=True,
anchor='sw'
)
canvas.drawCentredString(w / 2, 600, name)
canvas.showPage()
canvas.save()
def create_composite(ul, ll, ur, lr, name):
new_im = PilImage.new('RGB', (512, 512))
new_im.paste(PilImage.open(ul), (0, 0))
new_im.paste(PilImage.open(ll), (256, 0))
new_im.paste(PilImage.open(ur), (0, 256))
new_im.paste(PilImage.open(lr), (256, 256))
return new_im
def get_filename(x, y):
return '/%03d_%03d.png' % (x, y)
def sort_tiles(tiles):
sorted_tiles = {}
for tile in tiles:
fn = tile.split('/')[-1].split('.')[0].split('_')
x = int(fn[0])
y = int(fn[1])
xs = sorted_tiles.get(x, None)
if not xs:
xs = {}
sorted_tiles[x] = xs
xs[y] = tile
return sorted_tiles
def create_pdf(directory, name):
tiles = sort_tiles(get_files(directory))
height = len(tiles[0])
width = len(tiles)
cols = width / 2
rows = height / 2
physical_width, physical_height = physical_size(cols, rows)
pages = rows * cols
print 'generating PDF'
print 'cols: %s' % cols
print 'rows: %s' % rows
print 'pages: %s' % pages
print 'size: %.1f m x %.1f m (w x h)' % (physical_width, physical_height)
c = canvas.Canvas(name + '_new.pdf', pagesize=A4)
x_idx = 0
for x_idx, x1 in enumerate(range(0, width - 1, 2)):
x2 = x1 + 1
for y_idx, y1 in enumerate(range(0, height - 1, 2)):
y2 = y1 + 1
filename = get_filename(x_idx, y_idx)
image = create_composite(
tiles[x1][y1],
tiles[x2][y1],
tiles[x1][y2],
tiles[x2][y2],
filename
)
print_image(c, image, filename)
def get_files(dir):
directory = os.getcwd() + '/' + dir
os.chdir(directory)
files = [directory + '/' + png for png in glob.glob('*.png')]
return sorted(file for file in files)
if __name__ == '__main__':
create_pdf('xyz', 'map')