โค้ด: เลือกทั้งหมด
@app.post('/api_pdftopic')
async def read_pdf(request: Pdf_base64):
dt = datetime.now()
ts = str(datetime.timestamp(dt))
directory = "pdf_to_image" + ts
parent_dir = r"C:\Users\fonfo\pdf-toolkits"
path = os.path.join(parent_dir, directory)
os.mkdir(path)
attach_fname = 'PDF_File.pdf'
attach_fname_jpj = attach_fname.replace(".pdf", ".jpg")
jpeg_report_path = os.path.join(path, attach_fname_jpj)
fname_new = ' "' + jpeg_report_path + '"'
pdf_report_path = os.path.join(path, attach_fname)
with open(pdf_report_path, 'wb') as theFile:
theFile.write(base64.b64decode(request.pdf_base64))
process = subprocess.Popen(r'Magick convert ' + pdf_report_path + fname_new,stdout=subprocess.PIPE, stderr=subprocess.PIPE)
out, err = process.communicate()
file_len = len([name for name in os.listdir(path) if
os.path.isfile(os.path.join(path, name))])
image_base_64 = []
for no in range(file_len -1):
if file_len > 2:
new = "-%s.jpg" % no
else:
new = ".jpg"
name_jpg = attach_fname.replace(".pdf", new)
jpeg_report_path = os.path.join(path, name_jpg)
with open(jpeg_report_path, "rb") as image_file:
image_base_64.append({'base64_Img': base64.b64encode(image_file.read()),})
os.unlink(jpeg_report_path)
os.unlink(pdf_report_path)
os.rmdir(path)
return image_base_64