PhP print to pdf
To generate a PDF file in PHP, you can use a library like TCPDF or FPDF. Below is a simple example using TCPDF to create and print a PDF document:
Step 1: Install TCPDF
You can download TCPDF from its official website or install it using Composer:
composer require tecnickcom/tcpdf
Step 2: Create a PDF Document
Here’s a basic example of how to generate a PDF file with TCPDF:
<?php
// Include the TCPDF library require_once(tcpdf/tcpdf.php); // Create a new PDF document $pdf = new TCPDF(); // Set document information $pdf->SetCreator(PDF_CREATOR); $pdf->SetAuthor(Your Name); $pdf->SetTitle(Sample PDF); $pdf->SetSubject(PDF Tutorial); $pdf->SetKeywords(TCPDF, PDF, example, test, guide); // Set default header data $pdf->SetHeaderData(PDF_HEADER_LOGO, PDF_HEADER_LOGO_WIDTH, Sample PDF, by Your Name); // Set header and footer fonts $pdf->setHeaderFont(Array(PDF_FONT_NAME_MAIN, , PDF_FONT_SIZE_MAIN)); $pdf->setFooterFont(Array(PDF_FONT_NAME_DATA, , PDF_FONT_SIZE_DATA)); // Set default monospaced font $pdf->SetDefaultMonospacedFont(PDF_FONT_MONOSPACED); // Set margins $pdf->SetMargins(PDF_MARGIN_LEFT, PDF_MARGIN_TOP, PDF_MARGIN_RIGHT); $pdf->SetHeaderMargin(PDF_MARGIN_HEADER); $pdf->SetFooterMargin(PDF_MARGIN_FOOTER); // Set auto page breaks $pdf->SetAutoPageBreak(TRUE, PDF_MARGIN_BOTTOM);
// Add a page
$pdf->AddPage(); // Set some content to print $html = <h1>Welcome to TCPDF!</h1>; $html .= <p>This is a simple PDF document generated using TCPDF in PHP.</p>; // Print text using writeHTMLCell() $pdf->writeHTMLCell(0, 0, , , $html, 0, 1, 0, true, , true); // Close and output PDF document $pdf->Output(sample.pdf, I); // I for inline view, D for download ?>
Explanation of the Code
- Include TCPDF: Make sure to include the TCPDF library.
- Create PDF Document: An instance of the TCPDF class is created.
- Set Document Properties: You can set the author, title, subject, and keywords of the PDF.
- Margins and Page Settings: You can set margins and page settings for the PDF.
- Add Page: A new page is added to the document.
- Write HTML Content: Use
writeHTMLCell()
to write HTML content into the PDF. - Output PDF: The
Output()
method generates the PDF, and the parameters control how the PDF is presented (inline or download).
Step 3: Test Your Code
Save this code in your api.php
file or any other PHP file and access it through your web server. It should generate and display the PDF in your browser.
Feel free to modify the content and settings as needed!
To generate a PDF file in PHP, you can use a library like TCPDF or FPDF. Below is a simple example using TCPDF to create and print a PDF docu...