Bạn sử dụng PHP và muốn tạo văn bản dạng PDF trực tuyến. Công cụ tốt nhất hiện nay là TCPDF. Bài này sẽ hướng dẫn bạn sử dụng PHP để tạo PDF qua TCPDF.
2 bài hướng dẫn tại đây:
http://www.web-development-blog.com/archives/create-pdf-documents-online-with-tcpdf/
http://www.startutorial.com/articles/view/how-to-create-pdf-helper-with-tcpdf
Many web applications output documents like invoices, contracts or just web pages in the PDF format. There are a few PHP classes which can be used for creating PDF files online, one of them is TCPDF. This tutorial is about how-to use the TCPDF class while creating a simple invoice document. If you like to take a sneak peak on the result, check this website which generates the PDF Invoice document on the fly.
WriteHTML and RTL support, Multiple columns, JavaScript and Forms, Bookmarks (Table of Content), Multicell complex alignment, Barcodes, Set PDF viewer display preferences, EPS/AI vectorial images and many more.

In our code we include some PHP files, next we’ve created a small class extension to have a custom header/footer and some handy method which creates a text box.
The header method has only two functions, one sets
the image quality and the second will place an image (including
hyperlink) on a defined place (x=120, Y=10, width=75). All coordinates
are measured in Millimeters and the height for the image is calculated
by the script. Inside the footer method we’re using some basic TCPDF
methods to define the position, the font/style and the cell with the
footer text. The third method (CreateTextBox) is just a group of TCPDF
functions which makes it easier to place some text box into the PDF
document. Note, the constant variable PDF_FONT_NAME_MAIN is defined inside the TCPDF config file, which is located inside the config directory.
After the headers and after the list of invoice items we create a line. Inside the loop, we use the variable $currY to raise the Y coordinate by 5 for each new row. The row amount is calculated by PHP and also the total amount is raised inside the foreach loop.
At the end we call the output method which will safe the created PDF
under the name test.pdf and sends the document to the browser.
This is just an example to show how easy it is to create PDF files online. Before you start your own PDF scripts, check all the TCPDF examples to get an idea how-to use the different methods.
Hoặc sử dụng cách khác
1.Prepration
2.PDF Helper class
Create "pdf.php" and place it to directory "app/views/helpers/pdf.php". Below is the code for the class:
3.Usage
Let us test out this helper class.
4.The end
Hopefully this simple tutorial helped you with your development.
If you like our post, please follow us on Twitter and help spread the word. We need your support to continue.
If you have questions or find our mistakes in above tutorial, do leave a comment below to let us know.
- See more at: http://www.startutorial.com/articles/view/how-to-create-pdf-helper-with-tcpdf#sthash.KBoR9vjJ.dpuf
2 bài hướng dẫn tại đây:
http://www.web-development-blog.com/archives/create-pdf-documents-online-with-tcpdf/
http://www.startutorial.com/articles/view/how-to-create-pdf-helper-with-tcpdf
Many web applications output documents like invoices, contracts or just web pages in the PDF format. There are a few PHP classes which can be used for creating PDF files online, one of them is TCPDF. This tutorial is about how-to use the TCPDF class while creating a simple invoice document. If you like to take a sneak peak on the result, check this website which generates the PDF Invoice document on the fly.
Why TCPDF and not some other PHP class?
TCPDF is based on the FPDF class, a very stable project written for PHP4. Since several years has TCPDF much more features than FPDF and is written for PHP5 (there is also a PHP4 version). The TCPDF has also some great documentation and of course examples for all important PDF jobs like:WriteHTML and RTL support, Multiple columns, JavaScript and Forms, Bookmarks (Table of Content), Multicell complex alignment, Barcodes, Set PDF viewer display preferences, EPS/AI vectorial images and many more.
The Zend Framework has some PDF class too…
Yes right, the first plan was to write this tutorial about the Zend Framework, but after writing a few rows of code I’ve noticed that the PDF Class is missing some important functions, like the MultiCell, which is used to wrap multiple rows of text. It’s a required function which was suggested as the Zend_Pdf_Cell 2 years ago and didn’t find the way to the core version until now. I like the Zend Framework a lot but not for creating PDF documents, the PDF class is much too limited.Okay let’s start the tutorial:
In this tutorial we create a PDF invoice including header logo, the invoice rows, an information box and some footer row.In our code we include some PHP files, next we’ve created a small class extension to have a custom header/footer and some handy method which creates a text box.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
|
require_once('tcpdf/config/lang/eng.php');
require_once('tcpdf/tcpdf.php');
class MYPDF extends TCPDF {
public function Header() {
$this->setJPEGQuality(90);
$this->Image('logo.png', 120, 10, 75, 0, 'PNG', 'http://www.finalwebsites.com');
}
public function Footer() {
$this->SetY(-15);
$this->SetFont(PDF_FONT_NAME_MAIN, 'I', 8);
$this->Cell(0, 10, 'finalwebsites.com - PHP Script Resource, PHP classes and code for web developer', 0, false, 'C');
}
public function CreateTextBox($textval, $x = 0, $y, $width = 0, $height = 10, $fontsize = 10, $fontstyle = '', $align = 'L') {
$this->SetXY($x+20, $y); // 20 = margin left
$this->SetFont(PDF_FONT_NAME_MAIN, $fontstyle, $fontsize);
$this->Cell($width, $height, $textval, 0, false, $align);
}
}
|
The invoice header
The following code will create a TCPDF object with default values, the PDF meta data gets defined (author, title, etc.), a page is added and the invoice header with information is created using our custom text box method.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
|
// create a PDF object
$pdf = new MYPDF(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);
// set document (meta) information
$pdf->SetCreator(PDF_CREATOR);
$pdf->SetAuthor('Olaf Lederer');
$pdf->SetTitle('TCPDF Example');
$pdf->SetSubject('TCPDF Tutorial');
$pdf->SetKeywords('TCPDF, PDF, example, tutorial');
// add a page
$pdf->AddPage();
// create address box
$pdf->CreateTextBox('Customer name Inc.', 0, 55, 80, 10, 10, 'B');
$pdf->CreateTextBox('Mr. Tom Cat', 0, 60, 80, 10, 10);
$pdf->CreateTextBox('Street address', 0, 65, 80, 10, 10);
$pdf->CreateTextBox('Zip, city name', 0, 70, 80, 10, 10);
// invoice title / number
$pdf->CreateTextBox('Invoice #201012345', 0, 90, 120, 20, 16);
// date, order ref
$pdf->CreateTextBox('Date: '.date('Y-m-d'), 0, 100, 0, 10, 10, '', 'R');
$pdf->CreateTextBox('Order ref.: #6765765', 0, 105, 0, 10, 10, '', 'R');
|
Invoice Rows
Now we create the information about the products we like put into the PDF invoice. First we create some headers and than we use a foreach loop to output our $orders array.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
|
// list headers
$pdf->CreateTextBox('Quantity', 0, 120, 20, 10, 10, 'B', 'C');
$pdf->CreateTextBox('Product or service', 20, 120, 90, 10, 10, 'B');
$pdf->CreateTextBox('Price', 110, 120, 30, 10, 10, 'B', 'R');
$pdf->CreateTextBox('Amount', 140, 120, 30, 10, 10, 'B', 'R');
$pdf->Line(20, 129, 195, 129);
// some example data
$orders[] = array('quant' => 5, 'descr' => '.com domain registration', 'price' => 9.95);
$orders[] = array('quant' => 3, 'descr' => '.net domain name renewal', 'price' => 11.95);
$orders[] = array('quant' => 1, 'descr' => 'SSL certificate 256-Byte encryption', 'price' => 99.95);
$orders[] = array('quant' => 1, 'descr' => '25GB VPS Hosting, 200GB Bandwidth', 'price' => 19.95);
$currY = 128;
$total = 0;
foreach ($orders as $row) {
$pdf->CreateTextBox($row['quant'], 0, $currY, 20, 10, 10, '', 'C');
$pdf->CreateTextBox($row['descr'], 20, $currY, 90, 10, 10, '');
$pdf->CreateTextBox('$'.$row['price'], 110, $currY, 30, 10, 10, '', 'R');
$amount = $row['quant']*$row['price'];
$pdf->CreateTextBox('$'.$amount, 140, $currY, 30, 10, 10, '', 'R');
$currY = $currY+5;
$total = $total+$amount;
}
$pdf->Line(20, $currY+4, 195, $currY+4);
|
Invoice footer and information
First we create a total row using the value from the variable $total we created before. After that row we have a MultiCell which can hold the payment conditions or just some other information. You can use HTML code in this cell as well, for example a link to your terms and conditions.
1
2
3
4
5
6
7
8
9
10
11
12
|
// output the total row
$pdf->CreateTextBox('Total', 20, $currY+5, 135, 10, 10, 'B', 'R');
$pdf->CreateTextBox('$'.number_format($total, 2, '.', ''), 140, $currY+5, 30, 10, 10, 'B', 'R');
// some payment instructions or information
$pdf->setXY(20, $currY+30);
$pdf->SetFont(PDF_FONT_NAME_MAIN, '', 10);
$pdf->MultiCell(175, 10, '<em>Lorem ipsum dolor sit amet, consectetur adipiscing elit</em>.
Vestibulum
sagittis venenatis urna, in pellentesque ipsum pulvinar eu. In nec
<a href="http://www.google.com/">nulla libero</a>, eu
sagittis diam. Aenean egestas pharetra urna, et tristique metus egestas
nec. Aliquam erat volutpat. Fusce pretium dapibus tellus.', 0, 'L', 0, 1, '', '', true, null, true);
//Close and output PDF document
$pdf->Output('test.pdf', 'F');
|
This is just an example to show how easy it is to create PDF files online. Before you start your own PDF scripts, check all the TCPDF examples to get an idea how-to use the different methods.
Hoặc sử dụng cách khác
1.Prepration
- Download TCPDF from Sourceforge.
- Unpack downloaded folder, and copy it to directory "app/vendors/tcpdf"
2.PDF Helper class
Create "pdf.php" and place it to directory "app/views/helpers/pdf.php". Below is the code for the class:
1
2
3
4
5
6
7
8
9
10
11
12
| <?php App::import( 'Vendor' , 'TCPDF' , array ( 'file' => 'tcpdf/tcpdf.php' )); //1 class PdfHelper extends AppHelper //2 { var $core ; function PdfHelper() { $this ->core = new TCPDF(); //3 } } ?> |
- Import the TCPDF class from vendor folder.
- Extend PdfHelper from AppHelper class.
1
| $pdf ->core->TCPDFfunction() |
3.Usage
Let us test out this helper class.- Create a layout file "app/views/layouts/pdf.ctp":
1234
<?php
header(
"Content-type: application/pdf"
);
echo
$content_for_layout
;
?>
-
Create a PdfsController class, and include PDF Helper. We will also create a index function for generating pdf:
12345678910
<?php
class
PdfsController
extends
AppController {
var
$uses
= null;
var
$helpers
=
array
(
'Pdf'
);
function
index() {
$this
->layout=
'pdf'
;
}
}
?>
-
Now let us create a view file "app/views/pdfs/index.ctp", this file will utilize our PDF Helper class to generate
a PDF:
123456
<?php
$pdf
->core->addPage(
''
,
'USLETTER'
);
$pdf
->core->setFont(
'helvetica'
,
''
, 12);
$pdf
->core->cell(30, 0,
'Hello World'
);
$pdf
->core->Output(
'example_001.pdf'
,
'D'
);
?>
- Now go to your browser and type in address to access /pdfs/index. You should be prompted to download a PDF file.
4.The end
Hopefully this simple tutorial helped you with your development.If you like our post, please follow us on Twitter and help spread the word. We need your support to continue.
If you have questions or find our mistakes in above tutorial, do leave a comment below to let us know.
- See more at: http://www.startutorial.com/articles/view/how-to-create-pdf-helper-with-tcpdf#sthash.KBoR9vjJ.dpuf