【问题标题】:Create export PDF module for div with canvas and multiple div使用画布和多个 div 为 div 创建导出 PDF 模块
【发布时间】:2013-05-26 18:51:46
【问题描述】:

我有一个这样的html页面:

 <html xml:lang="en" lang="en" xmlns="http://www.w3.org/1999/xhtml">
    <head>
   <title>charts</title>
   <link type="text/css" rel="stylesheet" media="screen" href="css/charts.css" />
   <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery   /1.9.1/jquery.min.js"></script>
   <script type="text/javascript" src="js/charts.js"></script>
   <script type="text/javascript">
    $(document).ready(function(){

      $("#thebutton").click(function(){
          //execute phantomjs to save div id example to pdf
      });     
    });
  </script>
  </head>
  <body>
    <div id="example">
        <div id="frame" class="graph2" style="position: relative; left: 0pt; top: 5pt; width: 500px; height: 415px;">
            <canvas id="myCanvas" height="415" width="500"></canvas>
            <div id="resultC10000" class="num" style="position: absolute; left: 120px; top: 195px;">4</div>
            <div id="resultC01000" class="num" style="position: absolute; left: 360px; top: 195px;">3</div>
            <div id="resultC00100" class="num num-empty" style="position: absolute; left: -1000px; top: -2200px;">0</div>
        </div>
    </div>
    <div><input type="button" id="thebutton" value="export"></div>
 </body>
 </html>

。我会创建一个导出模块到 png,但特别是到 pdf(一个按钮或列表来启动导出)。为此,我正在考虑使用插件 phantomjs 和 rasterize.js(如 Highcharts http://www.highcharts.com/component/content/article/2-news/52-serverside-generated-charts#phantom_usage),但我不知道如何集成并直接使用到我的网页中。此外,我的主 div 包含一个画布,但也包含一组包含文本的 div。我认为我们需要将我所有的 div 转换为画布,然后使用以前的插件将其转换为 pdf。

你能给我一些将 div 转换为 pdf 的线索吗?

【问题讨论】:

    标签: javascript pdf canvas phantomjs


    【解决方案1】:

    您将使用与用于 PNG 的工具完全相同的工具:phantomjs

    var page = new WebPage();
    page.paperSize = {
      format: "A4",
      orientation: "portrait",
      margin: {left:"2.5cm", right:"2.5cm", top:"1cm", bottom:"1cm"},
    };
    page.zoomFactor = 1;
    // assume the file is local, so we don't handle status errors
    page.open("http://your.url/here", function (status) {
       page.render("/path/to/your/pdf.pdf");
       phantom.exit();
    });
    

    是的,就是这么简单。显然,您可以使用标准的phantom 调用来限制render()。实际上,要打印,您只需要:

    • 已定义纸张格式/尺寸
    • .pdf 结尾的文件传递给render()

    【讨论】:

    • 好的,但是我不知道如何在我的html页面中直接使用它。我看到你可以使用命令行,但我希望点击一个按钮可以保存我的主 div。你能给我举个例子吗?
    • @Tof: phantomjs 是一个服务器端节点模块。您需要做的是绑定路由以触发该过程,然后从那里返回文件名的路径。
    • 但我不知道如何将我的 div 提供给 phantomjs。
    • @Tof:您可以通过 AJAX 为其提供整个页面的 HTML 代码,或者您可以再次使用 phantomjs 在服务器端重新渲染页面。
    • 我正在考虑做这样的事情:&lt;input type="button" oneclick="functionExport()"&gt;functionExport() 允许获取我的 div 并将其保存为 PDF。但我不知道如何执行我的功能导出。
    猜你喜欢
    • 1970-01-01
    • 2014-04-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-24
    • 1970-01-01
    • 1970-01-01
    • 2014-03-14
    相关资源
    最近更新 更多