Repository navigation
Expand file tree
/
Copy pathapp.py
More file actions
229 lines (173 loc) · 6.75 KB
/
Copy pathapp.py
File metadata and controls
229 lines (173 loc) · 6.75 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
import os
import json
import time
import uuid
from io import BytesIO
from flask import Flask, Request, render_template, request, send_file, jsonify
from pypdf import PdfReader, PdfWriter, Transformation
from reportlab.pdfgen import canvas
from reportlab.lib.utils import ImageReader
from PIL import Image
class MemoryRequest(Request):
# Keep uploaded files in memory instead of Werkzeug's temporary files, so
# PDFs never touch the disk.
def _get_file_stream(self, total_content_length, content_type,
filename=None, content_length=None):
return BytesIO()
app = Flask(__name__)
app.request_class = MemoryRequest
app.config['MAX_CONTENT_LENGTH'] = 50 * 1024 * 1024 # 50MB max
# Persistent data directory: only the signature library. PDFs are never
# stored: the browser keeps them and sends them again when saving.
DATA_DIR = os.environ.get('SIGNATRON_DATA', '/app/data')
SIGNATURES_DIR = os.path.join(DATA_DIR, 'signatures')
SIGNATURES_FILE = os.path.join(DATA_DIR, 'signatures.json')
# Signatures not saved to the library are only needed while signing.
TEMP_SIGNATURE_MAX_AGE = 24 * 60 * 60 # seconds
# Create directories if they don't exist
os.makedirs(SIGNATURES_DIR, exist_ok=True)
def load_saved_signatures():
if os.path.exists(SIGNATURES_FILE):
with open(SIGNATURES_FILE, 'r') as f:
return json.load(f)
return []
def save_signatures_list(sigs):
with open(SIGNATURES_FILE, 'w') as f:
json.dump(sigs, f)
def purge_temp_signatures():
library = {sig['id'] + sig['ext'] for sig in load_saved_signatures()}
limit = time.time() - TEMP_SIGNATURE_MAX_AGE
for name in os.listdir(SIGNATURES_DIR):
path = os.path.join(SIGNATURES_DIR, name)
try:
if name not in library and os.path.getmtime(path) < limit:
os.remove(path)
except FileNotFoundError:
pass # removed by another worker
@app.route('/')
def index():
return render_template('index.html')
# Returns the page sizes of the PDF; the file itself is not kept.
@app.route('/upload', methods=['POST'])
def upload_pdf():
if 'pdf' not in request.files:
return jsonify({'error': 'No PDF file'}), 400
pdf_file = request.files['pdf']
if pdf_file.filename == '':
return jsonify({'error': 'No file selected'}), 400
reader = PdfReader(BytesIO(pdf_file.read()))
pages_info = []
for i, page in enumerate(reader.pages):
pages_info.append({
'page': i,
'width': float(page.mediabox.width),
'height': float(page.mediabox.height)
})
return jsonify({'pages': pages_info})
@app.route('/signatures', methods=['GET'])
def get_saved_signatures():
return jsonify(load_saved_signatures())
@app.route('/signature', methods=['POST'])
def upload_signature():
if 'signature' not in request.files:
return jsonify({'error': 'No signature file'}), 400
sig_file = request.files['signature']
if sig_file.filename == '':
return jsonify({'error': 'No file selected'}), 400
sig_id = str(uuid.uuid4())
ext = os.path.splitext(sig_file.filename)[1].lower()
if ext not in ['.png', '.jpg', '.jpeg']:
return jsonify({'error': 'Only PNG/JPG allowed'}), 400
purge_temp_signatures()
sig_path = os.path.join(SIGNATURES_DIR, f'{sig_id}{ext}')
sig_file.save(sig_path)
with Image.open(sig_path) as img:
width, height = img.size
name = request.form.get('name', sig_file.filename)
save_to_library = request.form.get('save', 'false') == 'true'
sig_data = {
'id': sig_id,
'ext': ext,
'name': name,
'width': width,
'height': height
}
if save_to_library:
sigs = load_saved_signatures()
sigs.append(sig_data)
save_signatures_list(sigs)
return jsonify(sig_data)
@app.route('/signature/<sig_id>', methods=['GET', 'DELETE'])
def handle_signature(sig_id):
if request.method == 'DELETE':
sigs = load_saved_signatures()
sig_to_delete = None
for sig in sigs:
if sig['id'] == sig_id:
sig_to_delete = sig
break
if sig_to_delete:
sigs.remove(sig_to_delete)
save_signatures_list(sigs)
sig_path = os.path.join(SIGNATURES_DIR, f'{sig_id}{sig_to_delete["ext"]}')
if os.path.exists(sig_path):
os.remove(sig_path)
return jsonify({'success': True})
return jsonify({'error': 'Signature not found'}), 404
for ext in ['.png', '.jpg', '.jpeg']:
sig_path = os.path.join(SIGNATURES_DIR, f'{sig_id}{ext}')
if os.path.exists(sig_path):
return send_file(sig_path)
return jsonify({'error': 'Signature not found'}), 404
@app.route('/save', methods=['POST'])
def save_pdf():
# The browser sends the PDF again with the signatures: nothing is kept.
pdf_file = request.files.get('pdf')
if pdf_file is None:
return jsonify({'error': 'No PDF file'}), 400
try:
signatures = json.loads(request.form.get('signatures', '[]'))
except ValueError:
return jsonify({'error': 'Invalid signatures'}), 400
reader = PdfReader(BytesIO(pdf_file.read()))
writer = PdfWriter()
for page_num, page in enumerate(reader.pages):
page_width = float(page.mediabox.width)
page_height = float(page.mediabox.height)
page_sigs = [s for s in signatures if s.get('page', 0) == page_num]
if page_sigs:
overlay_buffer = BytesIO()
c = canvas.Canvas(overlay_buffer, pagesize=(page_width, page_height))
for sig in page_sigs:
sig_id = sig['id']
sig_ext = sig.get('ext', '.png')
sig_path = os.path.join(SIGNATURES_DIR, f'{sig_id}{sig_ext}')
if not os.path.exists(sig_path):
continue
x = sig['x']
y = page_height - sig['y'] - sig['height']
width = sig['width']
height = sig['height']
img = ImageReader(sig_path)
c.drawImage(img, x, y, width, height, mask='auto')
c.save()
overlay_buffer.seek(0)
overlay_pdf = PdfReader(overlay_buffer)
overlay_page = overlay_pdf.pages[0]
page.merge_transformed_page(
overlay_page,
Transformation(),
over=True
)
writer.add_page(page)
output_buffer = BytesIO()
writer.write(output_buffer)
output_buffer.seek(0)
return send_file(
output_buffer,
mimetype='application/pdf',
as_attachment=True,
download_name='signed.pdf'
)
if __name__ == '__main__':
app.run(debug=True, host='0.0.0.0', port=5000)