php-tcpdfHow can I generate a PDF from data stored in a MySQL database using TCPDF and PHP?
The following steps can be used to generate a PDF from data stored in a MySQL database using TCPDF and PHP:
- Include the TCPDF library in your PHP code:
require_once('tcpdf_include.php');
- Connect to the MySQL database:
$host = "localhost";
$username = "username";
$password = "password";
$dbname = "databasename";
$conn = new mysqli($host, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
- Create a query to retrieve the data you need for the PDF:
$sql = "SELECT * FROM users";
$result = $conn->query($sql);
- Create a new PDF document using the TCPDF library:
$pdf = new TCPDF(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);
- Add content to the PDF document:
// set document information
$pdf->SetCreator(PDF_CREATOR);
$pdf->SetAuthor('John Doe');
$pdf->SetTitle('Users Report');
$pdf->SetSubject('TCPDF Tutorial');
$pdf->SetKeywords('TCPDF, PDF, example, test, guide');
// add a page
$pdf->AddPage();
// create some HTML content
$html = '<h1>Users Report</h1>
<table>
<tr>
<th>ID</th>
<th>Name</th>
<th>Email</th>
</tr>';
// output data from database
while($row = $result->fetch_assoc()) {
$html .= '<tr>
<td>'.$row['id'].'</td>
<td>'.$row['name'].'</td>
<td>'.$row['email'].'</td>
</tr>';
}
$html .= '</table>';
// output the HTML content
$pdf->writeHTML($html, true, false, true, false, '');
- Output the PDF document:
$pdf->Output('example_001.pdf', 'I');
- Close the MySQL connection:
$conn->close();
Helpful links
More of Php Tcpdf
- How do I install TCPDF using Yum on a PHP server?
- How can I generate a QR code using PHP and TCPDF?
- How can I generate a PDF from XML data using PHP and TCPDF?
- How do I install TCPDF with Composer in a PHP project?
- How do I use the PHP TCPDF WriteHTMLCell function?
- How do I generate a PDF file using TCPDF, PHP and MySQL?
- How do I add a watermark to PDFs using PHP and TCPDF?
- How do I set the margins using PHP TCPDF?
- How can I install and use PHP-TCPDF on a Linux system?
- How do I set the page orientation when using PHP TCPDF?
See more codes...