DEV Community

artydev
artydev

Posted on • Updated on

FastHTML : View PDF in browser

For reasonable size pdf files, this script can suffice:

from fasthtml.common import *
import base64


app = FastHTML(hdrs=(picolink,))

@app.post("/post_and_display_pdf")
async def display_pdf(myFile:UploadFile):
    bytes_stream =  await myFile.read()
    base64_encoded_bytes = base64.b64encode(bytes_stream)
    return Iframe(
        src = f'data:Application/pdf;base64,{base64_encoded_bytes.decode('utf-8')}',
        style = "width:100%;height:100%"
    )

def formPDF ():
    form = Form(Group(Input(id="myFile", type="file"), Button("Add")),
               hx_post="/post_and_display_pdf", hx_target="#mypdf", hx_swap="outerhtml")
    return Main(form, style="flex:1")    

@app.route("/")
def get():
    return Div(
        H1("Upload and Display PDF's", style="text-align:center"),
        Div (
            Div(id="mypdf", style="flex:1;position:relative;min-height:89vh;background:rgba(0,0,0,0.1)"),
            formPDF (),
            style="display:flex;gap:0.5rem"
        )

    )

serve()
Enter fullscreen mode Exit fullscreen mode

Top comments (0)