Reputation: 579
I am trying to convert a html file to pdf in python.
The html file has a javascript chart.
At first, I used weasyprint and pdfkit modules but I found that the modules does not support javascript.
So now I am using wkhtmltopdf module. It convert most of the html code to pdf, except javascript. Is it possible to convert an html file containing a JavaScript chart to PDF in python?
or should I use another module?
Below is the JavaScript code that does not appear in the pdf file.
<script type="text/javascript">
FusionCharts.ready(function(){
var fusioncharts = new FusionCharts({
type: 'hlineargauge',
renderAt: 'chart_container',
width: '350px',
height: '170px',
dataFormat: 'json',
dataSource: {
"chart": {
"theme": "fint",
"caption": "Chart A",
"lowerLimit": "0",
"upperLimit": "20",
"chartBottomMargin": "40",
"valueFontSize": "11",
"valueFontBold": "z0"
},
"colorRange": {
"color": [{
"minValue": "0",
"maxValue": "11.5",
"label": "Low",
"code" : "#FDB881",
}, {
"minValue": "11.5",
"maxValue": "12.5",
"label": "Typical",
"code" : "#F18B36",
}, {
"minValue": "12.5",
"maxValue": "20",
"label": "High",
"code" : "#D2660D",
}]
},
"pointers": {
"pointer": [{
"value": "8",
'borderColor':'#333333',
'borderThickness':'3',
'borderAlpha':'100',
'bgColor':'#FF0000'
}]
},
}
}
);
fusioncharts.render();
});
</script>
wkhtmltopdf version is 0.12.4 and the command is
$ wkhtmltopdf --javascript-delay 5000 test.html test.pdf
Upvotes: 4
Views: 5108
Reputation:
Here is an example from a previous StackOverflow question. How to convert webpage into PDF by using Python
This example uses the library pfdkit
import pdfkit
pdfkit.from_url('http://google.com', 'out.pdf')
If it doesn't render the chart you could try using an iFrame with pdfkit to get desired results!
Here is an example using WeasyPrint First, install weasyprint.
pip install weasyprint
Then run example
python
>>> pdf = weasyprint.HTML('http://www.google.com').write_pdf()
>>> len(pdf)
92059
>>> file('google.pdf', 'w').write(pdf)
Here is a third example, because i'm fun. :)
import sys
from PyQt4.QtCore import *
from PyQt4.QtGui import *
from PyQt4.QtWebKit import *
app = QApplication(sys.argv)
web = QWebView()
web.load(QUrl("http://www.yahoo.com"))
printer = QPrinter()
printer.setPageSize(QPrinter.A4)
printer.setOutputFormat(QPrinter.PdfFormat)
printer.setOutputFileName("fileOK.pdf")
def convertIt():
web.print_(printer)
print "Pdf generated"
QApplication.exit()
QObject.connect(web, SIGNAL("loadFinished(bool)"), convertIt)
sys.exit(app.exec_())
Upvotes: 5