0

I'm looking for a way to convert word or excel file to pdf file using in my FastAPI project.

I tried to use comtypes library but that didn't help. I guess this library is not what i exactly need

I got an error

ctypes.ArgumentError: argument 1: TypeError: Cannot put <starlette.datastructures.UploadFile object at 0x0000020CFF14E310> in VARIANT

main.py

import comtypes.client

app = FastAPI()


@app.post('/')
async def root(file: UploadFile = File(...)):
    wdFormatPDF = 17

    word = comtypes.client.CreateObject('Word.Application')
    doc = word.Documents.Open(file)
    doc.SaveAs(f'{file.filename}', FileFormat=wdFormatPDF)
    doc.Close()
    word.Quit()

    return {'file_name': file.filename}

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
Zesshi
  • 435
  • 12
  • `file` is a UploadFile object - I'm not familiar with what kind of argument the `Word.Application` COM Open expects, but if it's a path, you might want to write the file content to disk before trying to open it, since it uses a SpooledTemporaryFile as its backend, and the documentation states for TemporaryFile that: "your code should not rely on a temporary file created using this function having or not having a visible name in the file system." - so read the contents and write it to a file in a safe location, then give that to the COM application? – MatsLindh May 12 '23 at 08:40
  • You might also find [this answer](https://stackoverflow.com/a/74419367/17865804) and [this answer](https://stackoverflow.com/a/70653605/17865804), as well as [this answer](https://stackoverflow.com/a/71886990/17865804) and [this answer](https://stackoverflow.com/a/73324461/17865804) helpful – Chris May 12 '23 at 08:53
  • The main question was about how can i upload word file and return PDF file in fastapi – Zesshi May 12 '23 at 09:04
  • I need to convert word files into pdf and give that to user with FastAPI – Zesshi May 12 '23 at 09:05
  • You may also want to have a look [here](https://stackoverflow.com/a/76197700/17865804) and [here](https://stackoverflow.com/a/76195586/17865804) – Chris May 12 '23 at 12:01

0 Answers0