将 PHP 文件中的 HTML 转换为 PDF 文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7108882/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 02:01:48  来源:igfitidea点击:

Converting HTML in PHP File to PDF File

phphtmlpdfhtml2pdf

提问by user559142

I have a php file which queries a database and then writes and updates the html accordingly.

我有一个 php 文件,它查询数据库,然后相应地写入和更新 html。

I have a button on this page "Export As PDF"..I am trying to convert this page to a pdf using HTML2FPDF, but I get the following error:

我在此页面上有一个按钮“导出为 PDF”。我正在尝试使用 HTML2FPDF 将此页面转换为 pdf,但出现以下错误:

FPDF error: Unable to create output file: Entry Report

I suspect the problem is because I am passing a php file instead of a html file:

我怀疑问题是因为我传递的是 php 文件而不是 html 文件:

<?php
require('html2fpdf.php');

if(isset($_POST['link'])){
  $url = $_POST['link'];
  $nm = $_POST['nm'];
  convert($url, $nm);
}

function convert($link, $name){
  $pdf=new HTML2FPDF();
  $pdf->AddPage();
  $fp = fopen($link,"r");
  $strContent = fread($fp, filesize($link));
  fclose($fp);
  $pdf->WriteHTML($strContent);
  $pdf->Output($name);
  echo ("PDF file generated successfully!");
}
?>

Does anyone know how I can get around this? perhaps by either converting php to html then html to pdf...

有谁知道我该如何解决这个问题?也许通过将 php 转换为 html 然后将 html 转换为 pdf ...

Or is there a direct way to convert a php file into a pdf file...

或者有没有直接的方法将php文件转换为pdf文件...

EDIT: OK so the problem was that I didn't allow public write permissions. Upon changing this, I managed it to create the pdf file...The problem is this....the pdf file is blank...

编辑:好的,所以问题是我不允许公共写权限。更改后,我设法创建了 pdf 文件...问题是这样的....pdf 文件是空白的...

I know this has something to do with the fact that I am passing a php page which is probably empty when it is being passed...How do I capture the html content within the html so the pdf output isn't blank?

我知道这与我传递的 php 页面有关,该页面在传递时可能为空...如何捕获 html 中的 html 内容,以便 pdf 输出不是空白?

Here is the php page:

这是php页面:

<?php

function connect() {
  $dbh = mysql_connect ("localhost", "user", "password") or die ('I cannot connect to the database because: ' . mysql_error());
  mysql_select_db("PDS", $dbh); 
  return $dbh;
}

session_start();

if(isset($_SESSION['username'])){
  if(isset($_POST['entryId'])){
    //do something
    $dbh = connect();
    $ide = $_POST['entryId'];
    $usertab = $_POST['usertable'];
    $answertable = $usertab . "Answers";
    $entrytable = $usertab . "Entries";
    $query = mysql_query("SELECT e.date, q.questionNumber, q.question, q.sectionId, a.answer FROM $answertable a, Questions q, $entrytable e WHERE a.entryId = '$ide' AND a.questionId = q.questionId AND e.entryId = '$ide' ORDER BY q.questionNumber ASC;") or die("Error: " . mysql_error());

    if($query){
      //set variables

      $sectionOne = array();
      $sectionTwo = array();
      $sectionThree = array();
      $sectionFour = array();
      $sectionFive = array();
      while($row=mysql_fetch_assoc($query)){
    $date = $row['date'];
    $section = $row['sectionId'];
    switch($section){
    case '1':
      $sectionOne[] = $row;
      break;
    case '2':
      $sectionTwo[] = $row;
      break;
    case '3':
      $sectionThree[] = $row;
      break;
        case '4':
      $sectionFour[] = $row;
      break;
        case '5':
      $sectionFive[] = $row;
      break;
        default:    
      break;      
    }
      }
    }else{
      //error - sql failed
    }
  }

?>
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
   <head>
   <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
   <script src = "jQuery.js"></script>
   <script>
   $(document).ready(function(){
       $("#export").click(function(e){
       //post to html2pdfconverter.php
       $("#link").val("Testers/viewentryreport.php");
       $("#nm").val("Entry Report.pdf");
       $("form#sendanswers").submit();
       }); 
   });
  </script>
  <title>Personal Diary System - Entry Report - <?php echo($date); ?></title>
  </head>
  <body>
  <h1>Entry Report - <?php echo($date); ?></h1>    
  <div id = "buttons">
  <form id = "sendanswers" name = "sendanswers" action="Testers/html2pdfconverter.php" method="post">
  <input type = "hidden" name = "link" id = "link" value = "">
  <input type = "hidden" name = "nm" id = "nm" value = "">
  <input type = "button" name = "export" id = "export" value = "Export As PDF"/>
  </form>                        
  </div>                         
  <h3>Biological Information</h3>
  <?php
      $i = 0;                         
      foreach($sectionOne as &$value){
    if($i == 1 || $i == 3){
      $image = "assets/urine".$i.".png";
      echo("<br/>");
      echo($value['question']." <br/> "."<img src = \"$image\"/>");
      echo("<br/>");
    }else{
      echo($value['question'].' : '.$value['answer']);
    }
    echo("<br/>");
    $i++;
      }
  ?>
  <h3>Fatigue and Recovery</h3>
  <?php
      foreach($sectionTwo as &$value){
    echo($value['question'].' : '.$value['answer']);
    echo("<br/>");
      }
  ?>
  <h3>Illness and Injury</h3>
  <?php
      foreach($sectionThree as &$value){
    echo($value['question'].' : '.$value['answer']);
    echo("<br/>");
      }
  ?>
  <h3>Training Sessions</h3>
  <?php
      foreach($sectionFour as &$value){
    echo($value['question'].' : '.$value['answer']);
    echo("<br/>");
      }
  ?>
  <h3>General Feedback</h3>
  <?php 
     if(count($sectionFive)>0){
      foreach($sectionFive as &$value){
    echo($value['question'].' : '.$value['answer']);    
      }
     }else{
       $sectionFive = "User didn't leave any feedback";
       echo("User didn't leave any feedback");
     }
     echo("<br/>");
  ?>
  </body>
</html>
<?php
}
?>

and html2pdfconverter.php

和 html2pdfconverter.php

<?php
require('html2fpdf.php');

if(isset($_POST['link'])){
  $url = $_POST['link'];
  $nm = $_POST['nm'];
  convert($url, $nm);
}

function convert($link, $name){
  $pdf=new HTML2FPDF();
  $pdf->AddPage();
  $fp = fopen($link,"r");
  $strContent = fread($fp, filesize($link));
  fclose($fp);
  $pdf->WriteHTML($strContent);
  $pdf->Output($name);
  echo ("PDF file generated successfully!");
}
?>

EDIT @TIMFERRIS

编辑@TIMFERRIS

I changed my convert function to this based on @TimeFerris' answer:

我根据@TimeFerris 的回答将我的转换函数更改为此:

function convert($link, $name){

  $pdf=new HTML2FPDF();
  $pdf->AddPage();
  $content = file_get_contents( $link ); //shorter than what you did
  ob_start();
  echo $content;
  $pdf->WriteHTML( ob_get_contents() );
  ob_end_clean();
  $pdf->Output($name);
  echo ("PDF file generated successfully!");
}

The PDF file is created but still blank

PDF 文件已创建但仍为空白

回答by Devator

I recently done this by using TCPDF. TCPDF is a further developed version of FPDF.

我最近通过使用TCPDF做到了这一点。TCPDF 是 FPDF 的进一步开发版本。

See this linkfor an expample regarding converting to PDF. Also, hereyou can find more examples. Example 61 could also come in quite handy.

有关转换为 PDF 的示例,请参阅此链接。此外,您可以在此处找到更多示例。示例 61 也可以派上用场。

Sample code which TCPDF uses:

TCPDF 使用的示例代码:

$html = '<h1>HTML Example</h1>
<div style="text-align:center">IMAGES<br />
<img src="../images/logo_example.png" alt="test alt attribute" width="100" height="100" border="0" /><img src="../images/tiger.ai" alt="test alt attribute" width="100" height="100" border="0" /><img src="../images/logo_example.jpg" alt="test alt attribute" width="100" height="100" border="0" />
</div>';

// output the HTML content
$pdf->writeHTML($html, true, false, true, false, '');

回答by Daniel Wolfe

One thing that you could do is run the PHP file, but use output buffering to capture the contents that the PHP script is writing out. Then, save those contents to an .html file and pass that file to the converter.

您可以做的一件事是运行 PHP 文件,但使用输出缓冲来捕获 PHP 脚本写出的内容。然后,将这些内容保存到 .html 文件并将该文件传递给转换器。

回答by TFennis

The php file you are supplying has to run through a parser before it's valid html code.

您提供的 php 文件必须经过解析器才能成为有效的 html 代码。

$content = file_get_contents( $filename ); //shorter than what you did
ob_start();
echo $content;
$pdf->WriteHTML( ob_get_contents() );
ob_end_clean();