是否可以在python中将包含JavaScript图表的html文件转换为PDF格式?

2024-04-18 23:30:46 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试用python将html文件转换为pdf。 html文件有一个javascript图表。
起初,我使用weasyprint和pdfkit模块,但我发现这些模块不支持javascript。
所以现在我使用的是wkhtmltoppdf模块。它将大部分html代码转换为pdf,javascript除外。是否可以在python中将包含JavaScript图表的html文件转换为PDF格式?
还是应该使用其他模块?
下面是pdf文件中未显示的JavaScript代码。在

<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版本为0.12.4,命令为

^{pr2}$

Tags: 模块文件代码pdfhtmltype图表script
1条回答
网友
1楼 · 发布于 2024-04-18 23:30:46

下面是一个前一个StackOverflow问题的例子。 How to convert webpage into PDF by using Python

本例使用库pfdkit

import pdfkit
pdfkit.from_url('http://google.com', 'out.pdf')

如果它不能呈现图表,您可以尝试使用iFrame和pdfkit来获得所需的结果!在

下面是一个使用WeasyPrint的示例 首先,安装weasyprint。在

^{pr2}$

然后运行示例

python
>>> pdf = weasyprint.HTML('http://www.google.com').write_pdf()
>>> len(pdf)
92059
>>> file('google.pdf', 'w').write(pdf)

这是第三个例子,因为我很有趣。:)

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_())

相关问题 更多 >