【问题标题】:Create PDF from specific div从特定 div 创建 PDF
【发布时间】:2013-08-14 19:18:27
【问题描述】:

下午好!

我需要从 HTML 页面生成 PDF,但需要从特定的 div

<div id="canvas">
   all content is here
</div>

我在 CodeIgniter 中有这个功能作为插件,使用 mPDF

function pdf($html, $filename=null)
{
    require_once("mpdf_lib/mpdf.php");

    $mpdf = new mPDF();
    $mpdf->WriteHTML($html);

    if($filename == null){
        $filename = date("Y-m-d").'_test.pdf';
    }

    $mpdf->Output($filename, 'I');
}

我只需要知道如何从该特定 div 中获取 html 内容以作为参数传递给 pdf ($html) 函数。

我找到了很多示例,但实际上所有示例都使用“静态”html 代码。

提前致谢!

【问题讨论】:

  • 首先,这里已经是午夜了!第二,你的这个特定的div,它在哪里?它在服务器的另一个文件中?是php生成的html吗?...
  • 那么晚安!哈哈 这个 div 位于从控制器 (codeigniter) 加载的视图 (newproject.php) 中

标签: php codeigniter codeigniter-2 mpdf


【解决方案1】:

首先确保您的 php 函数位于 codeigniter 控制器中,以便访问网页 /controllername/pdf 调用该函数。

然后,使用 javascript 将 div 的内容发布到您的服务器。如果您使用的是 jquery,请参阅 jquery.post。这将通过 ajax 调用控制器函数,并生成 pdf。

$.post('/controller/php', {html: $("#canvas").html()})

然后更改 php 函数以通过 $this-&gt;input-&gt;post('html'); 收集其参数

function pdf()
{
    require_once("mpdf_lib/mpdf.php");

    $html = $this->input->post('html');
    $mpdf = new mPDF();
    $mpdf->WriteHTML($html);

    $filename = date("Y-m-d").'_test.pdf';

    $mpdf->Output($filename, 'I');
}

【讨论】:

  • 函数找到正确。我需要知道如何发布 div 的内容。我对javascript不太了解。
【解决方案2】:

这不是一个干净的方法,但它有效

例如,我在“视图/测试”中有我的 html 布局

这是在views/test.php里面

<!--
   Check if $print variable is set
   if it is set then the request is for printing if not the request is for veiwing
-->
<?if(isset($print)):?>

     <!--
       if canvas is set a specific part of the html is only selected
       i did not put an else condition you can supply it if you want
     -->
     <?if($isset($canvas)):?>
           <?if($canvas == 'canvas'):?>
               <div id="canvas">
                  <!--content-->
               </div>

           <?elseif($canvas == 'canvas_two'):?>
               <div id="canvas_two">
                  <!--content-->
              </div>
           <?elseif($canvas == 'canvas_three'):?>
               <div id="canvas_three">
                  <!--content-->
               </div>
           <?endif;?>
     <?endif;?>
<?else:?>
 <div id="canvas">
      <!--content-->
  </div>

 <div id="canvas_two">
      <!--content-->
  </div>

<div id="canvas_three">
      <!--content-->
  </div>
<?endif;?>

你是控制器:

function pdf()
{
    require_once("mpdf_lib/mpdf.php");
    //gives of the variable print and canvas on what id
    $html = $this->load->view('test',array('print'=>TRUE,'canvas'=>'canvas'),TRUE);
    $mpdf = new mPDF();
    $mpdf->WriteHTML($html);

    if($filename == null){
        $filename = date("Y-m-d").'_test.pdf';
    }

    $mpdf->Output($filename, 'I');
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-06-24
    • 1970-01-01
    • 2015-03-20
    • 2015-05-24
    • 2014-01-09
    • 2013-07-13
    相关资源
    最近更新 更多