FileNotFoundError docx to pdf convert program

210 Views Asked by At

I'm making a flask docx to pdf convert program and occured an error as below:

File not found error

There are two files in the Templates directory index.html and docx.html, the structure of a program looks like this: Structure

After i run the program i can select a file and it works well: Select file

After choosing a file and clicking "upload" button the file is converting: upload file Terminal view

And I get redirected to an index url with a download correctly: Download page

But after clicking the "Download" button I get an error as I showed on a first SS saying "FileNotFoundError". Does anyone know what the problem is?

Below I paste code:

from flask import Flask
from flask import request, render_template, redirect, url_for, send_file
import os
from typing import Tuple
from docx2pdf import convert
#from tkinter import Tk,messagebox
#from tkinter import _tkinter

UPLOADER_FOLDER = ''
app = Flask(__name__)
app.config['UPLOADER_FOLDER'] = UPLOADER_FOLDER

@app.route('/')
@app.route('/index', methods=['GET', 'POST'])
def index():
    if request.method == "POST":
        def docx2pdf(input_file: str, output_file: str, pages: Tuple = None):
           if pages:
               pages = [int(i) for i in list(pages) if i.isnumeric()]

           result = convert(input_file, output_file)
           print('Convert Done')
           summary = {
               "File": input_file, "Pages": str(pages), "Output File": output_file
            }

           print("\n".join("{}:{}".format(i, j) for i, j in summary.items()))
           return result
        file = request.files['filename']
        if file.filename!= '':
           file.save(os.path.join(app.config['UPLOADER_FOLDER'], file.filename))
           input_file = file.filename
           output_file = r"hello.pdf"
           docx2pdf(input_file, output_file)
           pdf = input_file.split(".")[0]+".pdf"
           print(pdf)
           lis=pdf.replace(" ", "=")
           return render_template("docx.html", variable=lis)
    return render_template("index.html")


@app.route('/docx', methods=['GET', 'POST'])
def docx():
    if request.method=="POST":
        lis = request.form.get('filename', None)
        lis = lis.replace("=", " ")
        return send_file(lis, as_attachment=True)
    return render_template("index.html")

if __name__=="__main__":
    app.debug = True
    app.run()

1

There are 1 best solutions below

0
On

look at this section:

input_file = file.filename    
output_file = r"hello.pdf"
docx2pdf(input_file, output_file)
pdf = input_file.split(".")[0]+".pdf"
print(pdf)
lis=pdf.replace(" ", "=")
return render_template("docx.html", variable=lis)

your converted file is called "hello.pdf", but you are returning the "lis" variable. did you forget to rename the converted file?

I.E.

os.rename("hello.pdf", lis)

then return lis