How to use a local font (.otf file) in Dash Python

Viewed 927

I'm currently working on a project where I have to include a custom font in a Dash App. I've received the .otf file, but I have no idea how I can use it. After searching quiet a while I hope you guys can help me.

import dash
import dash_html_components as html

external_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css']
app             = dash.Dash(__name__, prevent_initial_callbacks=True, external_stylesheets=external_stylesheets)

app.layout = html.Div([
                html.P('Hello world'),
            ])

if __name__ == "__main__":
    app.run_server(debug=True,port=8050)

The .otf file is places in the folder '/assets/fonts'. I've seen some posts about this subject where I should create a .css file and add it to external_stylesheets, but I'm not sure how to do that and even if it will work.

Anyway, thanks in advance!

1 Answers

This is really simple! You're on the right track. As you say, all you have to do is use a .css file located in a local (relative to your app.py file; i.e., same directory) "assets" directory.

Here below I have set up the following basic app file structure:

.
|-- app.py
`-- assets
    |-- FreeSerifItalic-KErA.otf
    `-- custom.css

1 directory, 3 files

I have a local .otf font file I want to use under the .assets/ folder. Here are the contents of the custom.css file, also located under my assets/ folder:

@font-face {
    font-family: 'FreeSerif-Italic'; 
    src: url('FreeSerifItalic-KErA.otf');
}

body {
    margin: 10%;
    overflow-x: hidden;
    text-align: center;
    font-family: "FreeSerif-Italic";
    font-size: 2.5rem;
}

where I have used the @font-face CSS3 feature to properly import the font for use, by giving it the reference name "FreeSerif-Italic". I define the body element of my app to default to using this font for all text (you don't have to use the font for the body element, you could use it for any html element you want!; you could also use in within your app.py Dash code using the style parameter of any dash.html component).

And here I have a very simple app.py file, (nearly) just like your example:

import dash
from dash import html

app = dash.Dash(__name__)

app.layout = html.Div([html.P("Hello world")])

if __name__ == "__main__":
    app.run_server(debug=True, dev_tools_hot_reload=True)

which when ran ('$ python app.py'), gives:

dash app when ran

Related