Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create a PDF file with PHP

Tags:

php

pdf

I want to create pdf file from my web page written by php . My document must produce from mysql and produce pdf file.I want to be to save this pdf and to read.Please give me code sample.

like image 555
thinzar Avatar asked Jul 30 '09 05:07

thinzar


People also ask

How do I create a PDF from a Web application?

To create a PDF from the currently open web page, choose Convert Web Page To PDF. Then select a location, type a filename, and click Save. To add a PDF of the currently open web page to another PDF, choose Add Web Page To Existing PDF. Then locate and select the existing PDF, and click Save.


2 Answers

Using the TCPDF library:

<?
require_once("tcpdf/tcpdf.php");
$pdf = new TCPDF();

// set document information
$pdf->SetCreator(PDF_CREATOR);
$pdf->SetAuthor("my name");
$pdf->SetTitle("my doc");
$pdf->SetSubject("x");
$pdf->SetKeywords("a, b, c");


// set default header data
$pic = "/gfx/header.png";
$pdf->SetHeaderData(realpath($pic), "25", "Title");

// 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 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);

 //set image scale factor
 $pdf->setImageScale(PDF_IMAGE_SCALE_RATIO);

 //set some language-dependent strings
 $pdf->setLanguageArray($l);

 //initialize document
 $pdf->AliasNbPages();

 // add a page
 $pdf->AddPage();

 // ---------------------------------------------------------

 // set font
 $pdf->SetFont("helvetica", "", 12);

 // set a background color
 $pdf->SetFillColor(230, 240, 255, true);


$pdf->SetFont("", "b", 16);
$pdf->Write(16, "some text\n", "", 0, 'C');

$pdf->Output("filename.pdf", "I");
?>
like image 200
bb. Avatar answered Oct 15 '22 21:10

bb.


I you already have an HTML page, the fastest way for you might be to use a tool like HTML2PDF to "convert" that HTML data to PDF, instead of generating a PDF file "from scratch".

Quoting that page :

It allows the conversion of valid HTML 4.01 in PDF format, and is distributed under LGPL.

This library has been designed to handle mainly TABLE intertwined to generate invoices delivery, and other official documents. It does not yet have all the tags.

There are some example of HTML, and the corresponding PDF files, so you can see what's capable of.

like image 37
Pascal MARTIN Avatar answered Oct 15 '22 20:10

Pascal MARTIN