-->

Converting HTML in PHP File to PDF File [closed]

2019-01-28 23:05发布

问题:

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

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:

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
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...

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

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...

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?

Here is the php page:

<?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

<?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

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

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

回答1:

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

See this link for an expample regarding converting to PDF. Also, here you can find more examples. Example 61 could also come in quite handy.

Sample code which TCPDF uses:

$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, '');


回答2:

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.



回答3:

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

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