-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathapp-old.py
More file actions
286 lines (183 loc) · 7.55 KB
/
Copy pathapp-old.py
File metadata and controls
286 lines (183 loc) · 7.55 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
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
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
#! /usr/bin/env python
# DEPRECATED
import sys
import os
import time
# PROJECT_ROOT = os.path.dirname(os.path.abspath(__file__))
# sys.path.insert(0, os.path.abspath(os.path.join(PROJECT_ROOT, "..")))
import json
import tempfile
from jinja2 import Template
from jinja2 import Environment, PackageLoader, select_autoescape
env = Environment(
loader=PackageLoader('app', 'templates'),
autoescape=select_autoescape(['html', 'xml'])
)
def formatFloat(val):
try:
float(val)
except ValueError:
return ''
return format(float(val), '.12f').rstrip("0").rstrip('.')
env.globals.update(formatFloat=formatFloat)
from werkzeug.wsgi import wrap_file
from werkzeug.wrappers import Request, Response
from executor import execute
from werkzeug.datastructures import Headers
import logging
logger = logging.getLogger()
gunicorn_error_logger = logging.getLogger('gunicorn.error')
logger.handlers.extend(gunicorn_error_logger.handlers)
logger.setLevel(logging.DEBUG)
def get_report(data):
html = ''
template = env.get_template('base.html')
html = template.render(**data)
return html
def create_file(html, options):
file_name = ''
with tempfile.NamedTemporaryFile(suffix='.html') as source_file:
# source_file.write(payload['contents'].decode('base64'))
source_file.write(html)
# options = payload.get('options', {})
source_file.flush()
# Evaluate argument to run with subprocess
args = ['wkhtmltopdf']
# Add Global Options
if options:
for option, value in options.items():
args.append('--%s' % option)
if value:
args.append('%s' % value)
# Add source file name and output file name
file_name = source_file.name
args += [file_name, file_name + ".pdf"]
# Execute the command using executor
execute(' '.join(args))
return file_name
def fit_columns_to_a4_width(layout, scale, margin, columns):
columns_to_remove = 0
current_width = 0
limit_width = 0
# scale_modifier = 1
# if scale > 1:
# scale_modifier = 1 - (scale - 1)
# if scale_modifier == 0:
# scale_modifier = 0.1
# else:
# scale_modifier = 1 + (1 - scale)
# A4 (21 x 29.7 cm), width:794px; height:1122px - data from internet
# A4 estimated width equals to 1173px - data recieved by testing
# logger.info('layout %s' % layout)
logger.info('scale %s' % scale)
# logger.info('scale_modifier %s' % scale_modifier)
logger.info('margin %s' % margin)
if layout == 'portrait':
limit_width = 833
# limit_width = 794 * scale_modifier
if layout == 'landscape':
limit_width = 1173
# limit_width = 1047 * scale_modifier
# one margin unit estimately equals to 4.1px
limit_width = float(limit_width) - float(margin) * 8.2
logger.info('limit_width %s' % limit_width)
columns_fit_count = 0
if len(columns):
for column in columns:
column_width = int(float(column['style']['width'].split('px')[0])) * scale
if column_width + current_width <= limit_width:
current_width = current_width + column_width
logger.info('current_width: %s' % current_width)
print('current_width %s' % current_width)
print('columns_fit_count %s' % str(columns_fit_count + 1))
columns_fit_count = columns_fit_count + 1
else:
break
columns_len = len(columns)
columns_to_remove = columns_len - columns_fit_count
columns = columns[:columns_len - columns_to_remove]
return columns
@Request.application
def application(request):
if request.method != 'POST':
return
# logger.info("Request data %s" % request.data)
requestData = json.loads(request.data)
entityType = requestData['entityType']
settings = requestData['settings']
contentSettings = requestData['contentSettings']
templateData = {}
templateData['entityType'] = entityType
templateData['content'] = requestData['content']
templateData['layoutName'] = contentSettings['layoutName']
templateData['reportOptions'] = contentSettings['reportOptions']
# requestData['layout'] = 'portrait'
# requestData['margin'] = '4'
options = {
'orientation': settings['layout'],
# 'viewport-size': '1280x1024',
# 'viewport-size': '1920x1080',
# 'page-width': 1600 * 0.271,
# 'page-height': 1200 * 0.271,
# 'zoom': 1,
'zoom': settings['zoom'],
# 'zoom': 0.5,
# 'zoom': '0.25',
'disable-smart-shrinking': '',
'page-width': '210mm',
'page-height': '297mm',
#'page-size': 'A4',
'footer-right': '[page]/[toPage]',
'footer-font-size': '8',
'margin-top': str(settings['margin']),
'margin-bottom': str(settings['margin']),
'margin-left': str(settings['margin']),
'margin-right': str(settings['margin'])
#'dpi': '300'
}
logger.info('Columns total: %s' % len(contentSettings["columns"]))
templateData["columns"] = fit_columns_to_a4_width(settings['layout'],
float(settings['zoom']),
settings['margin'],
contentSettings["columns"])
logger.info("Columns fit: %s" % len(templateData["columns"]))
templateData["pageLayout"] = settings['layout']
logger.info('templateData["pageLayout"] %s' % templateData["pageLayout"])
conv = None
if entityType == 'balance-report':
conv = time.strptime(contentSettings["reportOptions"]["report_date"], "%Y-%m-%d")
templateData["reportDate"] = time.strftime("%d/%m/%Y", conv)
if entityType == 'transaction-report':
beginDateConverted = time.strptime(contentSettings["reportOptions"]["begin_date"], "%Y-%m-%d")
templateData["beginDate"] = time.strftime("%d/%m/%Y", beginDateConverted)
endDateConverted = time.strptime(contentSettings["reportOptions"]["end_date"], "%Y-%m-%d")
templateData["endDate"] = time.strftime("%d/%m/%Y", endDateConverted)
if entityType == 'pl-report':
beginDateConverted = time.strptime(contentSettings["reportOptions"]["pl_first_date"], "%Y-%m-%d")
templateData["beginDate"] = time.strftime("%d/%m/%Y", beginDateConverted)
endDateConverted = time.strptime(contentSettings["reportOptions"]["report_date"], "%Y-%m-%d")
templateData["endDate"] = time.strftime("%d/%m/%Y", endDateConverted)
html = get_report(templateData)
# Get result of html page creation
# f = open('page.html', mode='w')
# f.write(html)
# f.close()
# return Response(wrap_file(request.environ, open('page.html')), mimetype="text/html")
# < Get result of html page creation >
logger.info('options %s' % options)
file_name = create_file(html, options)
headers = Headers()
headers.add('Content-Type', 'application/pdf')
headers.add('Content-Disposition', 'attachment', filename='report.pdf')
pdf = open(file_name + '.pdf')
os.remove(file_name + '.pdf')
response = Response(pdf.read(),
mimetype='application/pdf', headers=headers
)
pdf.close()
return response
if __name__ == '__main__':
from werkzeug.serving import run_simple
run_simple(
'127.0.0.1', 5000, application, use_debugger=True, use_reloader=True
)