pythondownloadpdf-generationfastapipdfkit

Download PDF file using pdfkit and FastAPI


I am going to create an API, using FastAPI, that converts an HTML page to a PDF file, using pdfkit. However, it saves the file to my local disk. After I serve this API online, how could users download this PDF file to their computer?

from typing import Optional
from fastapi import FastAPI
import pdfkit

app = FastAPI()
@app.post("/htmltopdf/{url}")
def convert_url(url:str):
  pdfkit.from_url(url, 'converted.pdf')

Solution

  • Returning FileResponse is solved my problem. Thanks to @Paul H and @clmno Below codes are working example of returning pdf file to download with FastApi.

    from typing import Optional
    from fastapi import FastAPI
    from starlette.responses import FileResponse
    import pdfkit
    
    app = FastAPI()
    config = pdfkit.configuration(wkhtmltopdf=r"C:\Program Files\wkhtmltopdf\bin\wkhtmltopdf.exe")
    
    @app.get("/")
    def read_root():
        pdfkit.from_url("https://nakhal.expo.com.tr/nakhal/preview","file.pdf", configuration=config)
        return FileResponse(
                    "file.pdf",
                    media_type="application/pdf",
                    filename="ticket.pdf")
    

    **2)**This is another way with using tempfiles - to add pdf to a variable just write False instead of path -

    from typing import Optional
    from fastapi import FastAPI
    from starlette.responses import FileResponse
    import tempfile
    import pdfkit
    
    
    
    app = FastAPI()
    
    config = pdfkit.configuration(wkhtmltopdf=r"C:\Program Files\wkhtmltopdf\bin\wkhtmltopdf.exe")
    
    
    @app.get("/")
    def read_root():
        pdf = pdfkit.from_url("https://nakhal.expo.com.tr/nakhal/preview",False, configuration=config)
    
        with tempfile.NamedTemporaryFile(mode="w+b", suffix=".pdf", delete=False) as TPDF:
            TPDF.write(pdf)
            return FileResponse(
                    TPDF.name,
                    media_type="application/pdf",
                    filename="ticket.pdf")