0

我正在开发 WordPress 网站。在前端,我提供了在线创建简历的功能,在提交表格时,他将获得下载和打印 PDF 格式简历的选项。到目前为止,如果我传递一个简单的 html 文件以转换为 PDF,一切正常。但我想从插入数据库的简历字段中创建一个 PDF。如果我传递纯 html 文件进行转换,它工作正常。但是,如果我想创建 PHP 文件的动态 PDF 文件怎么办。这是我尝试过的代码:我为此使用了 html2pdf 转换库。

这是调用 test.php 的文件。

require("html2pdf/html2fpdf.php");

$htmlFile = "test.php";
$buffer = file_get_contents($htmlFile);

$pdf = new HTML2FPDF('P', 'mm', 'Letter');
$pdf->AddPage();
$pdf->WriteHTML($buffer);
$pdf->Output('test.pdf', 'F');

test.php 文件是:

<html>
    <body>
        <?php
            $username = "";
            $password = "";
            $hostname = "";
            $dbname = "";

            // Create connection
            $con = mysqli_connect($hostname, $username, $password, $dbname);

            // Check connection
            if (mysqli_connect_errno($con))
            {
                echo "Failed to connect to MySQL: " . mysqli_connect_error();
            }

            echo $result = mysqli_query($con,"SELECT * FROM wp_resume ORDER BY id DESC LIMIT 1");
            echo "hioooooo";
            while($row = mysqli_fetch_array($result))
            {
                ?>
                <div>
                    <label>First Name</label><script type="text/php"><?php echo $row['firstName']; ?></script><br>
                    <label>Last Name</label><script type="text/php"><?php echo $row['lastName']; ?></script><br>
                </div>
                <?php
            }
        ?>
    </body>
</html>

现在提交表单后,我得到一个仅包含以下数据的 PDF 文件:

我想要插入条目的所有细节。显然,这忽略了标签内的<?php ?>代码。因此,即使我使用var_dump(),我也没有得到任何东西。

所以请帮我解决这个问题。如何将 PHP 数据传递到 PDF 文件。

4

2 回答 2

2

嘿,我得到了解决方案。正确的代码是:

      require("html2pdf/html2fpdf.php"); 

      $html = '<h2>Resume</h2>';
      $query = "SELECT * FROM wp_resume order by id desc limit 1";
      $result = mysqli_query($con,$query);
      while($row = mysqli_fetch_array($result))
      {
          $html .= '<div>
                      <label>First Name</label> '. $row['firstName'].'<br>
                      <label>Last Name</label> '.  $row['lastName']. '<br>
                    </div>';
      }

      $pdf = new HTML2FPDF('P', 'mm', 'Letter'); 
      $pdf->AddPage(); 
      $pdf->WriteHTML($html); 
      $pdf->Output('test.pdf', 'F'); 

我希望这会对某人有所帮助....

于 2013-10-31T21:45:16.033 回答
0

file_get_contents 返回文件的内容,而不会将其解析为 PHP...

代替

$buffer = file_get_contents($htmlFile); 

ob_start();
include($htmlFile);
$buffer = ob_end_clean();

我们在做什么:打开一个输出缓冲区(这样可以防止回显出现在客户端),然后我们包含 PHP 文件,以便对其进行解析。记住所有的回声都在输出缓冲区中,所以用 ob_end_clean() 抓取它并使用生成的 HTML 来制作 PDF。

于 2013-10-31T16:39:45.167 回答