-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
828 lines (643 loc) · 29.2 KB
/
Copy pathmain.py
File metadata and controls
828 lines (643 loc) · 29.2 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
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
from flask import Flask
from markupsafe import escape
from flask import url_for, redirect , jsonify
from flask import render_template
from flask import request
from flask import send_from_directory
from flask import send_file
from werkzeug.utils import secure_filename
from pypdf import PdfWriter,PdfReader
import fitz
import zipfile
import time
import os
import shutil
import io
import subprocess
import platform
from PIL import Image
from flask import after_this_request
from reportlab.pdfgen import canvas
from reportlab.lib.pagesizes import A4
from reportlab.lib.colors import Color, black
app = Flask(__name__)
gs_cmd = 'gswin64c' if platform.system() == 'Windows' else 'gs'
if os.environ.get('RENDER'): # Custom flag for Render (you can set this in env vars)
UPLOAD_FOLDER = '/tmp/uploads'
OUTPUT_FOLDER = '/tmp/output'
PREVIEW_FOLDER = '/tmp/previews'
else:
UPLOAD_FOLDER = os.path.abspath('uploads')
OUTPUT_FOLDER = os.path.abspath('output')
PREVIEW_FOLDER = os.path.abspath('previews')
os.makedirs(UPLOAD_FOLDER, exist_ok=True)
os.makedirs(OUTPUT_FOLDER, exist_ok=True)
os.makedirs(PREVIEW_FOLDER, exist_ok=True)
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
app.config['OUTPUT_FOLDER'] = OUTPUT_FOLDER
app.config['PREVIEW_FOLDER'] = PREVIEW_FOLDER
def empty_dir(path):
[os.remove(os.path.join(path, f)) for f in os.listdir(path) if os.path.isfile(os.path.join(path, f))]
def create_watermark(text, output="./uploads/watermark.pdf"):
os.makedirs(os.path.dirname(output), exist_ok=True)
c = canvas.Canvas(output, pagesize=A4)
c.setFont("Helvetica", 100)
c.setFillColor(Color(0.5, 0.5, 0.5, alpha=0.6))
c.saveState()
c.translate(300, 400)
c.rotate(45)
c.drawCentredString(0, 0, text)
c.restoreState()
c.save()
return output
@app.route("/tools")
def hello_world():
empty_dir(UPLOAD_FOLDER)
empty_dir(OUTPUT_FOLDER)
empty_dir(PREVIEW_FOLDER)
return render_template('index.html')
# @app.route('/preview-list')
# def preview_list():
# previews = os.listdir('previews')
# return jsonify(previews)
# @app.route('/previews/<filename>')
# def get_preview(filename):
# return send_from_directory('previews', filename)
@app.route('/previews/<filename>')
def serve_preview(filename):
return send_from_directory(PREVIEW_FOLDER, filename)
@app.route('/previews')
def list_previews():
files = os.listdir(PREVIEW_FOLDER)
image_files = [f for f in files if f.lower().endswith(('.jpg', '.jpeg', '.png', '.webp'))]
return jsonify(image_files)
@app.route('/reorder-previews', methods=['POST'])
def reorder_previews():
data = request.json
order = data.get('order', [])
temp_folder = 'Preview_temp'
os.makedirs(temp_folder, exist_ok=True)
# Move files to temp in the new order
for i, filename in enumerate(order):
src = os.path.join(PREVIEW_FOLDER, filename)
if not os.path.exists(src):
print(f"[!] Skipping missing file: {filename}")
continue # skip this file
dst = os.path.join(temp_folder, f"{i:03d}_{filename}")
if os.path.exists(src):
shutil.move(src, dst)
print("Received reorder list:", order)
print("Existing preview files:", os.listdir(PREVIEW_FOLDER))
# Clear old previews and move temp back
for f in os.listdir(PREVIEW_FOLDER):
os.remove(os.path.join(PREVIEW_FOLDER, f))
for f in os.listdir(temp_folder):
shutil.move(os.path.join(temp_folder, f), os.path.join(PREVIEW_FOLDER, f))
os.rmdir(temp_folder)
pdf_path = os.path.join(OUTPUT_FOLDER, "Reordered_pdf.pdf")
doc = fitz.open()
for filename in sorted(os.listdir(PREVIEW_FOLDER)):
filepath = os.path.join(PREVIEW_FOLDER, filename)
img = fitz.Pixmap(filepath)
if img.alpha: # If image has transparency
img = fitz.Pixmap(fitz.csRGB, img)
rect = fitz.Rect(0, 0, img.width, img.height)
page = doc.new_page(width=img.width, height=img.height)
page.insert_image(rect, pixmap=img)
img = None # free memory
doc.save(pdf_path)
doc.close()
return send_from_directory(directory=OUTPUT_FOLDER, path="Reordered_pdf.pdf", as_attachment= True)
@app.route('/')
def index():
return redirect(url_for('pdf_home'))
@app.route('/home')
def pdf_home():
empty_dir(UPLOAD_FOLDER)
empty_dir(OUTPUT_FOLDER)
empty_dir(PREVIEW_FOLDER)
return render_template("home.html")
@app.route('/tnc')
def pdf_terms():
return render_template("terms.html")
@app.route('/privacypolicy')
def pdf_privacy():
return render_template("privacyPolicy.html")
@app.route('/contact')
def pdf_contact():
return render_template("contact.html")
@app.route("/tools/<slug>", methods=['GET','POST'])
def pdf_tool(slug):
op = escape(slug)
if request.method == 'GET':
# pull your “metadata” out of request.args
img1 = request.args.get('img1')
img2 = request.args.get('img2')
caption1 = request.args.get('caption1')
caption2 = request.args.get('caption2')
description = request.args.get('description')
empty_dir(UPLOAD_FOLDER)
empty_dir(OUTPUT_FOLDER)
empty_dir(PREVIEW_FOLDER)
# … same for img2, caption2, description …
return render_template(
"tooljinja.html",
name=op,
img1=img1,caption1=caption1,
img2=img2,caption2=caption2,
description=description)
match(op):
case "Pdf Merger":
return pdf_merger(op)
case "Images to Pdf":
return Img_pdf(op)
case "Pdf Compresser":
return pdf_compress(op)
case "Pdf Splitter":
return pdf_splitt(op)
case "Pdf to PNG":
return pdf_PNG(op)
case "Pdf to JPG":
return pdf_JPG(op)
case "Pdf to TIFF":
return pdf_TIFF(op)
case "Pdf Encryptor":
return pdf_Locker(op)
case "Pdf Decryptor":
return pdf_unlocker(op)
case "Pdf Rotator":
return pdf_rotator(op)
case "Text Extractor":
return pdf_textext(op)
case "Pdf Watermarker":
return pdf_Wmark(op)
case "Pdf Reorderer":
return pdf_reorder(op)
# return render_template("tooljinja.html", name=op , operation="splitt pdf")
def pdf_merger(name):
if request.method == 'GET':
return render_template("tooljinja.html", name=name , operation="Merged pdf")
if request.method == 'POST':
uploaded_files = request.files.getlist('files[]')
# Output_path = ""
if uploaded_files:
for file in uploaded_files:
fileName = secure_filename(file.filename)
Upload_path = os.path.join(UPLOAD_FOLDER,fileName)
output_fileName = f"Processed_{fileName}"
Output_path = os.path.join(OUTPUT_FOLDER,output_fileName)
file.save(Upload_path)
input_files = [os.path.join(UPLOAD_FOLDER, f) for f in os.listdir(UPLOAD_FOLDER)]
#Ghost Command
command = [
gs_cmd,
"-sDEVICE=pdfwrite",
"-dBATCH",
"-dQUIET",
"-dNOPAUSE",
f"-sOutputFile={Output_path}"
] + input_files
try:
subprocess.run(command, check=True)
print("Pdfs are successfully merged : ",output_fileName)
return send_from_directory(directory=OUTPUT_FOLDER, path=output_fileName, as_attachment= True)
except Exception as e:
print("Merging failed try again : ",e)
return jsonify(success=False, error="Ghostscript processing failed."), 500
return jsonify(success=False, error="File upload failed"), 400
def Img_pdf(name):
if request.method == 'GET':
return render_template("tooljinja.html", name=name, operation="Generated pdf")
if request.method == 'POST':
uploaded_files = request.files.getlist('files[]')
output_fileName = "Processed_Pdf.pdf"
Output_path = os.path.join(OUTPUT_FOLDER, output_fileName)
if uploaded_files:
image_list = []
for file in uploaded_files:
img = Image.open(file).convert("RGB")
image_list.append(img)
# Save all images into a single PDF
image_list[0].save(Output_path, save_all=True, append_images=image_list[1:])
return send_from_directory(directory=OUTPUT_FOLDER, path=output_fileName, as_attachment=True)
return jsonify(success=False, error="File upload failed"), 400
def pdf_compress(name):
if request.method == 'GET':
return render_template("tooljinja.html", name=name , operation="Compressed pdf")
if request.method == 'POST':
uploaded_files = request.files.getlist('files[]')
if uploaded_files:
for file in uploaded_files:
fileName = secure_filename(file.filename)
Upload_path = os.path.join(UPLOAD_FOLDER,fileName)
output_fileName = f"Processed_{fileName}"
Output_path = os.path.join(OUTPUT_FOLDER,output_fileName)
file.save(Upload_path)
quality = request.form.get('value')
# Pdf compresser
command = [
gs_cmd,
"-sDEVICE=pdfwrite",
"-dCompatibilityLevel=1.4",
f"-dPDFSETTINGS={quality}",
"-dNOPAUSE",
"-dQUIET",
"-dBATCH",
f"-sOutputFile={Output_path}",
Upload_path
]
try:
subprocess.run(command, check=True)
print(f"Pdf successfully compressed to : {output_fileName}")
return send_file(Output_path, as_attachment=True, download_name=output_fileName, max_age=0, conditional=False)
except subprocess.CalledProcessError as e:
print("Compression failed try again : ",e)
return jsonify(success=False, error="Ghostscript processing failed."), 500
return jsonify(success=False, error="File upload failed"), 400
def pdf_splitt(name):
if request.method == 'GET':
return render_template("tooljinja.html", name=name , operation="Splitted pdf")
if request.method == 'POST':
uploaded_files = request.files.getlist('files[]')
if uploaded_files:
for file in uploaded_files:
fileName = secure_filename(file.filename)
Upload_path = os.path.join(UPLOAD_FOLDER,fileName)
output_fileName = f"Processed_{fileName}"
Output_path = os.path.join(OUTPUT_FOLDER,output_fileName)
Start_page = request.form.get("start-page")
End_page = request.form.get("end-page")
file.save(Upload_path)
command = [
gs_cmd,
"-sDEVICE=pdfwrite",
"-dCompatibilityLevel=1.4",
"-dBATCH",
"-dQUIET",
"-dNOPAUSE",
f"-dFirstPage={Start_page}",
f"-dLastPage={End_page}",
f"-sOutputFile={Output_path}",
Upload_path
]
try:
subprocess.run(command, check=True)
print(f"Pdf successfully splitted from {Start_page}-{End_page} : ",output_fileName)
return send_from_directory(directory=OUTPUT_FOLDER, path=output_fileName, as_attachment= True)
except subprocess.CalledProcessError as e:
print("Splitting failed try again : ",e)
return jsonify(success=False, error="Ghostscript processing failed."), 500
def pdf_PNG(name):
if request.method == 'GET':
return render_template("tooljinja.html", name=name , operation="Pdf to PNG")
if request.method == 'POST':
uploaded_files = request.files.getlist('files[]')
if uploaded_files:
for file in uploaded_files:
fileName = secure_filename(file.filename)
Upload_path = os.path.join(UPLOAD_FOLDER,fileName)
output_fileName = "img"
Output_path = os.path.join(OUTPUT_FOLDER,output_fileName)
file.save(Upload_path)
#Ghostscript command
command = [
gs_cmd,
"-sDEVICE=png16m",
f"-r150",
f"-dDownScaleFactor=2",
"-dNOPAUSE",
"-dQUIET",
"-dBATCH",
f"-sOutputFile={Output_path}%03d.png",
Upload_path
]
try:
subprocess.run(command, check=True)
zip_path = os.path.join(OUTPUT_FOLDER,"photos.zip")
with zipfile.ZipFile(zip_path, 'w', zipfile.ZIP_DEFLATED) as zipf:
for image in os.listdir(OUTPUT_FOLDER):
if image.lower().endswith(('.png', '.jpg', '.jpeg', '.webp', '.gif')):
full_path = os.path.join(OUTPUT_FOLDER,image)
zipf.write(full_path, arcname=image)
print(f"Photos zipped into: {output_fileName}")
return send_from_directory(directory=OUTPUT_FOLDER, path="photos.zip", as_attachment= True)
except subprocess.CalledProcessError as e:
print("Conversion failed try again: ",e)
def pdf_JPG(name):
if request.method == 'GET':
return render_template("tooljinja.html", name=name , operation="Pdf to JPG")
if request.method == 'POST':
uploaded_files = request.files.getlist('files[]')
if uploaded_files:
for file in uploaded_files:
fileName = secure_filename(file.filename)
Upload_path = os.path.join(UPLOAD_FOLDER,fileName)
output_fileName = "img"
Output_path = os.path.join(OUTPUT_FOLDER,output_fileName)
file.save(Upload_path)
#Ghostscript command
command = [
gs_cmd,
"-sDEVICE=jpeg",
f"-r150",
f"-dDownScaleFactor=2",
"-dNOPAUSE",
"-dQUIET",
"-dBATCH",
f"-sOutputFile={Output_path}%03d.JPG",
Upload_path
]
try:
subprocess.run(command, check=True)
zip_path = os.path.join(OUTPUT_FOLDER,"photos.zip")
with zipfile.ZipFile(zip_path, 'w', zipfile.ZIP_DEFLATED) as zipf:
for image in os.listdir(OUTPUT_FOLDER):
if image.lower().endswith(('.png', '.jpg', '.jpeg', '.webp', '.gif')):
full_path = os.path.join(OUTPUT_FOLDER,image)
zipf.write(full_path, arcname=image)
print(f"Photos zipped into: {output_fileName}")
return send_from_directory(directory=OUTPUT_FOLDER, path="photos.zip", as_attachment= True)
except subprocess.CalledProcessError as e:
print("Conversion failed try again: ",e)
def pdf_TIFF(name):
if request.method == 'GET':
return render_template("tooljinja.html", name=name , operation="Pdf to TIFF")
if request.method == 'POST':
uploaded_files = request.files.getlist('files[]')
if uploaded_files:
for file in uploaded_files:
fileName = secure_filename(file.filename)
Upload_path = os.path.join(UPLOAD_FOLDER,fileName)
output_fileName = "img"
Output_path = os.path.join(OUTPUT_FOLDER,output_fileName)
file.save(Upload_path)
#Ghostscript command
command = [
gs_cmd,
"-sDEVICE=tiff24nc",
"-r150",
"-dNOPAUSE",
"-dQUIET",
"-dBATCH",
f"-sOutputFile={Output_path}%03d.tiff",
Upload_path
]
try:
subprocess.run(command, check=True)
zip_path = os.path.join(OUTPUT_FOLDER,"photos.zip")
with zipfile.ZipFile(zip_path, 'w', zipfile.ZIP_DEFLATED) as zipf:
for image in os.listdir(OUTPUT_FOLDER):
if image.lower().endswith(('.png', '.jpg', '.jpeg', '.webp', '.gif')):
full_path = os.path.join(OUTPUT_FOLDER,image)
zipf.write(full_path, arcname=image)
print(f"Photos zipped into: {output_fileName}")
return send_from_directory(directory=OUTPUT_FOLDER, path="photos.zip", as_attachment= True)
except subprocess.CalledProcessError as e:
print("Conversion failed try again: ",e)
return jsonify(success=False, error="File upload failed"), 400
def pdf_Locker(name):
if request.method == 'GET':
return render_template("tooljinja.html", name=name)
if request.method == 'POST':
uploaded_files = request.files.getlist('files[]')
if not uploaded_files:
return jsonify(success=False, error="No file uploaded"), 400
if name == "Pdf Encryptor":
if len(uploaded_files) != 1:
return jsonify(success=False, error="Only one PDF allowed"), 400
file = uploaded_files[0]
fileName = secure_filename(file.filename)
Upload_path = os.path.join(UPLOAD_FOLDER, fileName)
output_fileName = f"Locked_{fileName}"
Output_path = os.path.join(OUTPUT_FOLDER, output_fileName)
# ✅ Save ONCE
file.save(Upload_path)
user_pass = request.form.get("code", "").strip()
user_pass = (
user_pass
.encode("utf-8", "ignore")
.decode("utf-8")
.strip()
)
owner_pass = f"{user_pass}@135"
command = [
gs_cmd,
"-sDEVICE=pdfwrite",
"-dCompatibilityLevel=1.4",
"-dPDFSETTINGS=/default",
"-dNOPAUSE",
"-dBATCH",
"-dQUIET",
"-dEncryptionR=3",
"-dKeyLength=128",
f"-sUserPassword={user_pass}",
f"-sOwnerPassword={owner_pass}",
"-dPermissions=-4",
f"-sOutputFile={Output_path}",
Upload_path
]
subprocess.run(command, check=True)
return send_from_directory(
OUTPUT_FOLDER,
output_fileName,
as_attachment=True
)
return jsonify(success=False, error="File upload failed"), 400
# def pdf_Locker(name):
# if request.method == 'GET':
# return render_template("tooljinja.html", name=name)
# if request.method == 'POST':
# uploaded_files = request.files.get('file')
# if uploaded_files:
# for file in uploaded_files:
# fileName = secure_filename(file.filename)
# Upload_path = os.path.join(UPLOAD_FOLDER,fileName)
# output_fileName = f"Locked_{fileName}"
# Output_path = os.path.join(OUTPUT_FOLDER,output_fileName)
# file.save(Upload_path)
# user_pass = request.form.get("code")
# owner_pass = f"{user_pass}@135"
# #Ghostscript command
# command = [
# gs_cmd,
# "-sDEVICE=pdfwrite",
# "-dCompatibilityLevel=1.4",
# "-dPDFSETTINGS=/default",
# "-dNOPAUSE",
# "-dBATCH",
# "-dQUIET",
# "-dEncryptionR=3", # Encryption settings:
# "-dKeyLength=128",
# f"-sUserPassword={user_pass.strip()}",
# f"-sOwnerPassword={owner_pass.strip()}",
# "-dPermissions=-4",
# f"-sOutputFile={Output_path}",
# Upload_path
# ]
# try:
# subprocess.run(command, check=True)
# print(f"Pdf is successfully locked : {output_fileName}")
# print("User pass: ",user_pass)
# print(f"User password raw bytes: {list(user_pass.encode())}")
# print("Output path: ",Output_path)
# print("Input Filename ",fileName)
# return send_from_directory(directory=OUTPUT_FOLDER, path=output_fileName, as_attachment= True)
# except subprocess.CalledProcessError as e:
# print("User pass: ",user_pass)
# print(f"User password raw bytes: {list(user_pass.encode())}")
# print("Process failed try again: ",e)
# return jsonify(success=False, error="Ghostscript processing failed."), 500
# return jsonify(success=False, error="File upload failed"), 400
def pdf_unlocker(name):
if request.method == 'GET':
return render_template("tooljinja.html", name=name)
if request.method == 'POST':
uploaded_files = request.files.getlist('files[]')
if uploaded_files:
for file in uploaded_files:
fileName = secure_filename(file.filename)
Upload_path = os.path.join(UPLOAD_FOLDER,fileName)
output_fileName = f"Unlocked_{fileName}"
Output_path = os.path.join(OUTPUT_FOLDER,output_fileName)
file.save(Upload_path)
user_pass = request.form.get("code")
#Ghostscript command
command = [
gs_cmd,
"-sDEVICE=pdfwrite",
"-dCompatibilityLevel=1.4",
"-dPDFSETTINGS=/default",
"-dNOPAUSE",
"-dBATCH",
"-dQUIET",
f"-sPDFPassword={user_pass}",
f"-sOutputFile={Output_path}",
Upload_path
]
try:
subprocess.run(command, check=True)
print(f"Pdf is successfully Unlocked : {output_fileName}")
print("User pass: ",user_pass)
print(f"User password raw bytes: {list(user_pass.encode())}")
print("Output path: ",Output_path)
print("Input Filename ",fileName)
return send_from_directory(directory=OUTPUT_FOLDER, path=output_fileName, as_attachment= True)
except subprocess.CalledProcessError as e:
print("Process failed try again: ",e)
return jsonify(success=False, error="Ghostscript processing failed."), 500
return jsonify(success=False, error="File upload failed"), 400
def pdf_rotator(name):
if request.method == 'GET':
return render_template("tooljinja.html", name=name)
if request.method == 'POST':
uploaded_files = request.files.getlist('files[]')
if uploaded_files:
for file in uploaded_files:
fileName = secure_filename(file.filename)
Upload_path = os.path.join(UPLOAD_FOLDER,fileName)
output_fileName = f"Rotated_{fileName}"
Output_path = os.path.join(OUTPUT_FOLDER,output_fileName)
file.save(Upload_path)
angle = int(request.form.get("value", 90))
#Ghostscript command
Writer = PdfWriter()
Reader = PdfReader(Upload_path)
try:
for page in Reader.pages:
page.rotate(angle)
Writer.add_page(page)
with open(Output_path, "wb") as f :
Writer.write(f)
return send_from_directory(directory=OUTPUT_FOLDER, path=output_fileName, as_attachment= True)
except subprocess.CalledProcessError as e:
print("Process failed try again: ",e)
return jsonify(success=False, error="Ghostscript processing failed."), 500
return jsonify(success=False, error="File upload failed"), 400
def pdf_textext(name):
if request.method == 'GET':
return render_template("tooljinja.html", name=name)
if request.method == 'POST':
uploaded_files = request.files.getlist('files[]')
if uploaded_files:
for file in uploaded_files:
fileName = secure_filename(file.filename)
Upload_path = os.path.join(UPLOAD_FOLDER,fileName)
output_fileName = "Text_file.txt"
Output_path = os.path.join(OUTPUT_FOLDER,output_fileName)
file.save(Upload_path)
#PyuPDf command
try:
doc = fitz.open(Upload_path)
with open(Output_path, "w", encoding="utf-8") as f:
for i, page in enumerate(doc):
text = page.get_text()
f.write(f"----Page {i+1}----\n{text}\n\n")
doc.close()
print(f"Text saved to: {Output_path}")
return send_from_directory(directory=OUTPUT_FOLDER, path=output_fileName, as_attachment= True)
except Exception as e:
print("Extraction failed:", e)
return jsonify(success=False, error="Ghostscript processing failed."), 500
return jsonify(success=False, error="File upload failed"), 400
def pdf_Wmark(name):
if request.method == 'GET':
return render_template("tooljinja.html", name=name)
if request.method == 'POST':
uploaded_files = request.files.getlist('files[]')
if not uploaded_files:
return jsonify(success=False, error="No files uploaded"), 400
for file in uploaded_files:
fileName = secure_filename(file.filename)
Upload_path = os.path.join(UPLOAD_FOLDER, fileName)
output_fileName = f"Watermarked_{fileName}"
Output_path = os.path.join(OUTPUT_FOLDER, output_fileName)
file.save(Upload_path)
file.stream.seek(0)
watermark = request.form.get('code')
if os.path.getsize(Upload_path) == 0:
print(f"❌ File {fileName} is empty after saving.")
continue # Skip this file
# Proceed only if saved properly
watermark_pdf_bytes = create_watermark(watermark)
time.sleep(1)
input_pdf = PdfReader(Upload_path)
watermark_pdf = PdfReader(watermark_pdf_bytes)
watermark_page = watermark_pdf.pages[0]
writer = PdfWriter()
for page in input_pdf.pages:
page.merge_page(watermark_page)
writer.add_page(page)
with open(Output_path, "wb") as f_out:
writer.write(f_out)
print(f"✅ Watermarked PDF generated: {output_fileName}")
return send_from_directory(OUTPUT_FOLDER, output_fileName, as_attachment=True)
return jsonify(success=False, error="Invalid method"), 400
def pdf_reorder(name):
if request.method == 'GET':
return render_template("tooljinja.html", name=name)
if request.method == 'POST':
uploaded_files = request.files.getlist('files[]')
if not uploaded_files:
return jsonify(success=False, error="No files uploaded"), 400
previews = []
for file in uploaded_files:
fileName = secure_filename(file.filename)
Upload_path = os.path.join(UPLOAD_FOLDER, fileName)
output_fileName = f"Watermarked_{fileName}"
Output_path = os.path.join(OUTPUT_FOLDER, output_fileName)
file.save(Upload_path)
doc = fitz.open(Upload_path)
for i in range(len(doc)):
page = doc[i]
pix = page.get_pixmap(matrix=fitz.Matrix(2,2))
img_bytes = io.BytesIO(pix.tobytes("png"))
preview_filename = f"{fileName}_page_{i}.png"
preview_path = os.path.join(PREVIEW_FOLDER, preview_filename)
with open(preview_path,"wb") as img_file:
img_file.write(img_bytes.getvalue())
previews.append({
"page": i,
"preview_url": f"/preview/{preview_filename}"
})
return jsonify(success=True)
return jsonify(success=False, error="Invalid method"), 400