Here is a full working example of how to upload and display PDF’s in a Dash App:
# -*- coding: utf-8 -*-
"""
Created on Tue Apr 21 09:59:11 2020
@author: GRussell
"""
import base64
import datetime
import io
import time
import dash
from dash.dependencies import Input, Output, State
import dash_core_components as dcc
import dash_html_components as html
from pdf2image import convert_from_path, convert_from_bytes
import pandas as pd
from pdf2image import convert_from_bytes
external_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css']
app = dash.Dash(__name__, external_stylesheets=external_stylesheets)
app.layout = html.Div(children=[
html.Div(
children = [
dcc.Upload(
className="four columns",
id='upload-coa',
children=html.Div([
'Drag and Drop or ',
html.A('Select PDF')
]),
style={
'width': '45%',
'height': '60px',
'lineHeight': '60px',
'borderWidth': '1px',
'borderStyle': 'dashed',
'borderRadius': '5px',
'textAlign': 'center',
'margin': '10px'
},
# Allow multiple files to be uploaded
multiple=False
),
]
),
html.Hr(),
html.Div(id='output-coa'),
])
def pil_to_b64_dash(im):
buffered = io.BytesIO()
im.save(buffered, format="JPEG")
img_str = base64.b64encode(buffered.getvalue())
return bytes("data:image/jpeg;base64,", encoding='utf-8') + img_str
def parse_coa_contents(contents, filename, date):
content_type, content_string = contents.split(',')
decoded = base64.b64decode(content_string)
images = convert_from_bytes(decoded)
encoded = pil_to_b64_dash(images[0])
return html.Div([
# HTML images accept base64 encoded strings in the same format
# that is supplied by the upload
html.Img(src=encoded.decode('utf-8')),
html.Hr(),
])
@app.callback(Output('output-coa', 'children'),
[Input('upload-coa', 'contents')],
[State('upload-coa', 'filename'),
State('upload-coa', 'last_modified')])
def show_coa(list_of_contents, list_of_names, list_of_dates):
if list_of_contents is not None:
children = [parse_coa_contents(list_of_contents, list_of_names, list_of_dates)]
return children
if __name__ == '__main__':
app.run_server(debug=True)
Please excuse any unnecessary imports or code blocks, this is copy and pasted code from another project (I tried to trim it down to just what is necessary for the PDF portion … but I am impatient).
Let me know if there are any questions.