问题
I am trying to create a receipt for a web application by turning the receipt from the HTML code into a PDF so that it can be downloaded upon completion of the application. I have tried to send the code to a PHP file by assigning the contents of the targeted div to a hidden input field within a form. Upon pressing the button at the end, the js function below is executed onclick, as well as the PHP file:
function print() {
var elem = document.getElementById("receipt").innerHTML;
document.getElementById("hiddenhtml").value = elem;
}
Here is a rough outline of the form:
<form method="post" action="htmlpdf.php" target="_blank">
<div id="receipt">
------- CONTENT THAT I WANT IN THE PDF ----------
</div>
<input type="submit" onclick="print()" value="Print"/>
<input id="hiddenhtml" type="hidden" value=""/>
</form>
Where hiddenhtml is a hidden input field. Upon pressing the print button, the contents of the receipt div are added to the value of the hidden input field. I then try to pass this value as follows:
$html = $_POST['hiddenhtml'];
$pdf->writeHTML($html, true, false, true, false, '');
To use it in the writeHTML function. However, a blank PDF file is returned. I was wondering wether I can pass the contents of the targeted div as a parameter in the writeHTML method. The div has no external styling, and contains all compliant tags per the documentation.
回答1:
You need to add a page to the document to render your html in and then you need to actually output your page. See the example pdf page. Your code should look like this:-
$pdf = new TCPDF();
$pdf->AddPage('P');
$pdf->writeHTML($html, true, false, true, false, '');
$pdf->Output();
I did some further testing and created this code:-
if(isset($_POST['hidden'])){
$pdf = new TCPDF();
$pdf->AddPage('P');
$html = $_POST['hidden'];
$pdf->writeHTML($html);
$pdf->Output();
}
?>
<form method="POST">
<input name="hidden" type="hidden" value="
<div>
<h1>Receipt</h1>
<p>Some stuff</p>
<p>More stuff</p>
</div>"/>
<input type="submit" value="Submit"/>
</form>
Which, on submition, gave me this output:-

As you can see, a nice pdf page with my html rendered into it.
I would suggest you reduce your code to something as simple as this to aid trouble shooting. Once you have that working, then you can add complexity.
来源:https://stackoverflow.com/questions/14174932/creating-pdf-using-tcpdf-and-a-specific-div-as-the-content