DEV Community

artydev
artydev

Posted on • Edited 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

Image of Datadog

Create and maintain end-to-end frontend tests

Learn best practices on creating frontend tests, testing on-premise apps, integrating tests into your CI/CD pipeline, and using Datadog’s testing tunnel.

Download The Guide

Top comments (0)

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more