Django_plotly_dash: error exporting to pdf with html2pdf.js
I am trying to export a django_plotly_dash dashboard to pdf and can't quite get it. I am stuck with the following error in console when clicking on the button to trigger the export:
ReferenceError: html2pdf is not defined
at Object.nClicksToPDF [as n_clicks]
which is telling me that html2pdf cannot be found. I have tried importing in assets folder as well as cdn directly in the app layout but nothing seems to do the trick and I am out of things to try:
here is how I import it in the app:
html.Script(src="https://cdnjs.cloudflare.com/ajax/libs/html2pdf.js/0.10.1/html2pdf.bundle.min.js"),
here is my callback where it is called:
app.clientside_callback(
"""
function nClicksToPDF(n_clicks){
if(n_clicks > 0){
document.querySelector('.chkremove').style.display = 'none';
const opt = {
margin: 2,
filename: 'myfile.pdf',
image: { type: 'jpeg', quality: 0.98 },
html2canvas: { scale: 1},
jsPDF: { unit: 'cm', format: 'a2', orientation: 'p' },
pagebreak: { mode: ['avoid-all'] }
};
console.log('ok')
html2pdf().from(document.getElementById("print")).set(opt).save();
setTimeout(function(){
document.querySelector('.chkremove').style.display = 'block';
}, 2000);
}
}
""",
Output('js','n_clicks'),
Input('js','n_clicks')
)
Don't know what else to do, any help would be highly welcome!
The problem comes from the html.Script
component, which does not work as one might expect : in short, the <script>
tag is created, but never executed.
It is part of a larger issue : Several components have limited or no functionality in current browsers :
[...] browsers don't execute
<script>
s inserted in the way react does it (via innerHTML). Includinghtml.Script
in the documentation only leads folks down dead ends. Either it should use a different insertion mechanism, or it should have a bright big warning in the docs, or it should be removed entirely.
The alternative is to add html2pdf as an external script, ie :
scripts = [{
'src': 'https://cdnjs.cloudflare.com/ajax/libs/html2pdf.js/0.10.1/html2pdf.bundle.min.js'
}]
app = DjangoDash(__name__, external_scripts=scripts)