FileNotFound Error while converting docx2pdf

315 views Asked by At

im trying to make a python program that converts docx files to pdf using flask. But i get an Error like this: enter image description here

Below I paste code:

from flask import Flask
from flask import request, render_template, send_file
import os
from typing import Tuple
from docx2pdf import convert

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(" ", "=")
           os.rename("hello.pdf", lis)
           print('converted')
           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()

Can any one help? This is my last post for further details: FileNotFoundError docx to pdf convert program

1

There are 1 answers

0
Ingwar On

As we can see there

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(" ", "=")
    os.rename("hello.pdf", lis)
    print('converted')
    return render_template("docx.html", variable=lis)

You try to convert file. But you use docx2pdf(input_file, output_file). And if you look at the import section, you can see this

from docx2pdf import convert

So, you don't use convert -> file not saved and processed -> FileNotFoundError