import http.server import socketserver from pdf2image import convert_from_path import sys import os import io import cgi import json import random from base64 import b64decode import base64 #from PIL import Image #from PIL import ImageDraw #from PIL import ImageFont import codecs from urllib.parse import urlparse from urllib.parse import parse_qs class MyHttpRequestHandler(http.server.SimpleHTTPRequestHandler): def do_GET(self): # Sending an '200 OK' response self.send_response(200) # Setting the header self.send_header("Content-type", "application/json") # Whenever using 'send_header', you also have to call 'end_headers' self.end_headers() # Extract query param fileName = "" vfileName = "" ctype, pdict = cgi.parse_header(self.headers['Content-Type']) pdict['boundary'] = bytes(pdict['boundary'], "utf-8") pdict['CONTENT-LENGTH'] = int(self.headers['Content-Length']) if ctype == 'multipart/form-data': form = cgi.FieldStorage( fp=self.rfile, headers=self.headers, environ={'REQUEST_METHOD':'POST', 'CONTENT_TYPE':self.headers['Content-Type'], }) #fileName = form["file"].filename #print (form["base64"].value) #print ("saving file") #print (type(form)) vfileName = form["vfileName"].value bytesD = b64decode(form["base64"].value, validate=True) #print ("decode bytesD") # Perform a basic validation to make sure that the result is a valid PDF file # Be aware! The magic number (file signature) is not 100% reliable solution to validate PDF files # Moreover, if you get Base64 from an untrusted source, you must sanitize the PDF contents if bytesD[0:4] != b'%PDF': raise ValueError('Missing the PDF file signature') # Write the PDF contents to a local file randValue1 = str(random.randint(9999,999999)) fileName = randValue1+'file.pdf' f = open(randValue1+'file.pdf', 'wb') f.write(bytesD) f.close() #try: #if isinstance(form["file"], list): #for record in form["file"]: #print ("saved") #open("./%s"%record.filename, "wb").write(record.file.read()) #else: #print ("saved") #print(form["file"].filename) #open("./%s"%form["file"].filename, "wb").write(form["file"].file.read()) #except IOError: #print ("error") #return (False, "Can't create file to write, do you have permission to write?") #return (True, "Files uploaded") #print(path) #print ("generating images") images = convert_from_path(fileName) dict = {} for i in range(len(images)): randValue = str(random.randint(9999,999999)) # Save pages as images in the pdf images[i].save(randValue+'page'+ str(i) +'.jpg', 'JPEG') #print(randValue+'page'+ str(i) +'.jpg') #img = Image.open(randValue+'page'+ str(i) +'.jpg') # Call draw Method to add 2D graphics in an image #I1 = ImageDraw.Draw(img) #myFont = ImageFont.truetype('OpenSans-Bold.ttf', 40) # Add Text to an image #I1.text((28, 36), "Employee Name: Sarah, Employee Id: CF2", font=myFont, fill=(255, 0, 0)) #I1.text((28, 75), "2022-08-23 15:04:45", font=myFont, fill=(255, 0, 0)) #I1.text((28, 110), "K. M. Global Credit Private Limited", font=myFont, fill=(255, 0, 0)) # Display edited image #img.save(randValue+'page'+ str(i) +'.jpg') #img.save(randValue+'test_page'+ str(i) +'.png') #print(randValue+'page'+ str(i) +'.jpg') with open(randValue+'page'+ str(i) +'.jpg', "rb") as image_file: encoded_string = base64.b64encode(image_file.read()) #file = open(randValue+'page'+ str(i) +'.json', 'w') #file.write(encoded_string.decode("utf-8")) #file.close() dict[randValue+'page'+ str(i) +'.jpg'] = encoded_string.decode("utf-8") if os.path.isfile(randValue+'page'+ str(i) +'.jpg'): os.remove(randValue+'page'+ str(i) +'.jpg') if os.path.isfile(randValue1+'file.pdf'): os.remove(randValue1+'file.pdf') # Writing the HTML contents with UTF-8 print(vfileName+" start------------------------") print(dict) print(vfileName+" end------------------------") self.wfile.write(json.dumps(dict).encode()) return # Create an object of the above class handler_object = MyHttpRequestHandler PORT = 5003 my_server = socketserver.TCPServer(("", PORT), handler_object) # Star the server my_server.serve_forever()