I get mysql data.
Create - echo the mysql data as html.
If visitor wants to print the data as pdf (i mean to create pdf file and save on computer), i with jquery take the data and send to external php file. In the external php file, using http://www.tcpdf.org
solution i want to create pdf file (on fly, only as variable; i do not want to save the file on my server) so that user can save it.
User remains on the same url, just after user clicks button, i offer the user to save rendered pdf. I do not want to change url or add html content to the url (like print_pdf.php?html_content
).
At the moment i use code like below.
<div id="to_print_as_pdf">
<div>Some content from mysql</div>
<table>Another content from mysql</table>
</div>
<button type="button">Click to print as pdf</button>
<span id="result_print_pdf"></span>
Jquery to send the data
<script>
$("button").click(function(){
$.post('_prepare_to_print_pdf.php',
{ content_to_print: $('#to_print_as_pdf').html() },
function(result_print_pdf) {
$('#result_print_pdf').html(result_print_pdf).css('color', 'black');
});
});
</script>
File _prepare_to_print_pdf.php
$_SESSION['content_to_print'] = trim($_POST['content_to_print']);
<script>
window.location.href = "https://www.example.com/_print_pdf.php";
</script>
File _print_pdf.php
//Use http://www.tcpdf.org solution
$html = $_SESSION['content_to_print'];
$pdf->writeHTMLCell(0, 0, '', '', $html, 0, 1, 0, true, '', true);
$pdf->Output('example_001.pdf', 'I');
How to do the same without _prepare_to_print_pdf.php
? Above solution waste server resources (creating session).
I tried with $.post
to send html content directly to _print_pdf.php
, but in such case instead of prompting to to save pdf file, i see "garbage" characters...
Solution at the moment
May be will help to someone
$('#for_hidden_form_for_print_pdf').append('<form action="_print_pdf.php" method="post" target="_blank" id="hidden_form_for_print_pdf">' +
'<textarea id="content_to_print" name="content_to_print">html content to send </textarea>' +
'<div><button style="display: none;" id="btn_to_print_pdf">Print pdf</button></div></form>');
$('#btn_to_print_pdf').trigger('click');
$( "#hidden_form_for_print_pdf" ).remove();
So when visitor clicks button/icon, i take necessary html data, insert into textarea id="content_to_print"
. Then trigger click for btn_to_print_pdf
, then remove appended form. So i send to external php file, necessary html code. In php file i process the html code, create content for pdf file and print.