黄色网页视频 I 影音先锋日日狠狠久久 I 秋霞午夜毛片 I 秋霞一二三区 I 国产成人片无码视频 I 国产 精品 自在自线 I av免费观看网站 I 日本精品久久久久中文字幕5 I 91看视频 I 看全色黄大色黄女片18 I 精品不卡一区 I 亚洲最新精品 I 欧美 激情 在线 I 人妻少妇精品久久 I 国产99视频精品免费专区 I 欧美影院 I 欧美精品在欧美一区二区少妇 I av大片网站 I 国产精品黄色片 I 888久久 I 狠狠干最新 I 看看黄色一级片 I 黄色精品久久 I 三级av在线 I 69色综合 I 国产日韩欧美91 I 亚洲精品偷拍 I 激情小说亚洲图片 I 久久国产视频精品 I 国产综合精品一区二区三区 I 色婷婷国产 I 最新成人av在线 I 国产私拍精品 I 日韩成人影音 I 日日夜夜天天综合

使用 TCPDF 動(dòng)態(tài)創(chuàng)建 PDF

系統(tǒng) 2942 0

TCPDF 是一個(gè)幫助您創(chuàng)建 PDF 文檔的流行開(kāi)源 PHP 庫(kù)。它的靈活性和多功能性讓您可以創(chuàng)建具有任何您需要的字體和圖形功能的復(fù)雜彩色文檔。TCPDF 完全用 PHP 編寫(xiě)且在無(wú)需任何外部庫(kù)的情況下施展 PDF 所有魔法。本文向您介紹了 TCPDF,然后帶您了解在可下載的 PDF 文件上復(fù)制一個(gè)簡(jiǎn)單的 HTML 發(fā)票。

?

簡(jiǎn)介

TCPDF 是托管在 Sourceforge.net 上最活躍的項(xiàng)目之一,其完全在 PHP 上實(shí)現(xiàn)了強(qiáng)大的 PDF 生成引擎。這使得其更容易安裝,即使在您無(wú)法訪問(wèn)系統(tǒng)目錄或編譯自己的代碼的站點(diǎn)上。同時(shí),通過(guò)讓您直接查看 PHP 代碼生成的結(jié)果,而不使用任何中間步驟,這使迭代開(kāi)發(fā)更加容易。

TCPDF 支持一系列有用的圖像格式,包括 SVG 矢量格式和位圖格式,如 JPEG 和 PNG。一個(gè)簡(jiǎn)單獨(dú)立的實(shí)用工具讓您可以處理 TrueType、OpenType、PostScript Type 1 和 CID-0 字體,使它們可以添加到 TCPDF 創(chuàng)建的文檔。您可以使用 TCPDF 來(lái)生成無(wú)數(shù) 1-D 和 2-D 條形碼格式,且它支持所有常見(jiàn)的 PDF 功能,如書(shū)簽、文檔鏈接、壓縮、注釋、文檔加密和數(shù)字簽名。

用 PHP 編寫(xiě) TCPDF 并使用其頁(yè)面,這使其易于創(chuàng)建并部署 PDF 生成的 Web 頁(yè)面。在您使用任何支持 Web 服務(wù)器和您最喜歡的 PHP 開(kāi)發(fā)環(huán)境開(kāi)發(fā)并部署 TCPDF 時(shí),我將使用如下工具:

  • Eclipse V3.5.2 — 我最新歡的開(kāi)源開(kāi)發(fā)環(huán)境之一,其支持廣泛的編程語(yǔ)言和環(huán)境。
  • PHP Development Tools V2.2.0 — 適用于 Eclipse 的 PHP 插件。
  • MAMP Pro V1.9 — 適用于 Mac OS X 的方便的程序包,其通過(guò)有用的 GUI 前端在一個(gè)隔離的環(huán)境中提供 Apache、MySQL 和 PHP。雖然 Mac OS X 附帶安裝 Apache 和 PHP,但我還是選擇使用此工具,因?yàn)槠涮峁┝艘幌盗蟹€(wěn)定且容易分離的 Web 服務(wù)器/數(shù)據(jù)庫(kù)/PHP。
  • TCPDF V5.0.006 — TCPDF 當(dāng)前的穩(wěn)定版本。

您可以在 參考資料 部分找到以上所有工具的下載鏈接。

如 果您已經(jīng)安裝了 PHP,我們就來(lái)看看如何在您自己的網(wǎng)站上使用 TCPDF。我們將檢查安裝過(guò)程,然后我們將使用 PHP 生成一個(gè)顯示可能來(lái)自任何電子商務(wù)站點(diǎn)的發(fā)票式樣(invoice-style)文檔的網(wǎng)頁(yè)。此后,我們將使用 TCPDF 來(lái)創(chuàng)建一個(gè)使用類似格式的可打印的 PDF 版發(fā)票。

?

安裝 TCPDF

當(dāng)您從 Sourceforge.net 下載 TCPDF 時(shí),它提供一個(gè)自包含的 ZIP 存檔,也就是說(shuō),您可以使用您最喜歡的 ZIP 提取工具來(lái)解壓存檔,您最終將獲得一個(gè)包含您所需要的所有信息的 TCPDF 目錄。

如果您將 TCPDF 目錄添加到您的 web 文檔目錄,則您可以通過(guò)加載 doc/index.html 訪問(wèn) TCPDF 文檔并通過(guò)加載 examples/index.php 文件查看任何示例,這也可在 TCPDF 網(wǎng)站上找到(請(qǐng)參考 參考資料 )。

然而在您可以查看示例以前,您需要配置您的 TCPDF 安裝。

?

配置 — 類 UNIX 系統(tǒng)

如 果您正在類 UNIX? 系統(tǒng)上安裝 TCPDF,則您需要更改文件模式,因?yàn)樗鼈儾](méi)有全部被標(biāo)記為可執(zhí)行。在 Microsoft? Windows? 系統(tǒng)上存在一個(gè)創(chuàng)建 TCPDF 存檔的副作用。幸運(yùn)的是,很容易在來(lái)自 shell 的一個(gè)失衡中調(diào)整這些(請(qǐng)參考 清單 1)。您還需要確保緩存和圖像目錄是可寫(xiě)入的,因?yàn)?TCPDF 將在那里存儲(chǔ)臨時(shí)文件。

下一步,您需要將文件分配給用戶和組 web 服務(wù)器;雖然這通常是用戶 www 和組 www,但是這將取決于您的系統(tǒng)。如果您正在您的個(gè)人網(wǎng)站領(lǐng)域以外運(yùn)行 TCPDF,(在您的主目錄下通常是 public_html),則您可以跳過(guò)此步驟。

?
清單 1. 調(diào)整文件模式和所有權(quán)
      $ cd tcpdf
$ find . -type f | xargs chmod -x
$ chmod +w cache images
$ chown -R www:www .
    

?

請(qǐng)注意命令可能使用 . 代替 : 來(lái)在一些系統(tǒng)上分離用戶和組;如果出現(xiàn)問(wèn)題,則檢查其文檔詳細(xì)資料。

?

適用于每個(gè)人的配置

使用您最喜歡的文本編輯器,加載 config/tcpdf_config.php 文件。這就是 TCPDF 的配置設(shè)置并讓您控制庫(kù)的默認(rèn)設(shè)置,并告訴它如何找到自己的支持文件。

在 tcpdf_config.php 中您想要變更的設(shè)置包括:

  • PDF_PAGE_FORMAT — 如果您不使用公制頁(yè)面格式,則設(shè)置其為 letter 。除非您手頭有一些非常奇特方法,否則 TCPDF 可能比您的打印機(jī)支持更大的頁(yè)面尺寸。
  • PDF_UNIT — 如果您想用點(diǎn)而不是毫米來(lái)布置您的 PDF 文檔,則設(shè)置其為 pt 。
  • PDF_CREATOR PDF_AUTHOR — 一旦您的 PDF 生成代碼忘了設(shè)置它們,則默認(rèn)文檔創(chuàng)建者和作者。

您可以在您的 PHP 代碼中調(diào)整這些設(shè)置中的任意一個(gè),如果無(wú)法確定也無(wú)需擔(dān)心(例如,如果您在此處設(shè)置的是像模式文檔布局,您仍然可以創(chuàng)建景觀文檔)。

假設(shè)您沒(méi)有移動(dòng)文件和目錄遠(yuǎn)離其初始位置,則通過(guò)默認(rèn)配置設(shè)置,TCPDF 應(yīng)該沒(méi)有呈現(xiàn)任何其附帶示例的問(wèn)題。

在這一點(diǎn)上,您可以加載示例文件以確保您擁有一個(gè)正在運(yùn)行的 TCPDF 安裝。讓我們使用它來(lái)創(chuàng)建一個(gè)可打印版的發(fā)票。

?

創(chuàng)建發(fā)票

在您創(chuàng)建了電子商務(wù)網(wǎng)站以后,您的客戶將訂購(gòu)一些物品,而您將收取他們的貨款。雖然這很不錯(cuò),但是他們將想得到某種發(fā)票,以防訂單錯(cuò)誤或他們的信用卡公司搞混了付款,。

讓我們制作一個(gè)合理美觀的發(fā)票網(wǎng)頁(yè),這樣他們可以看到他們已經(jīng)訂購(gòu)了什么和您將要向他們收取什么。

?

第一個(gè)版本 — Web 頁(yè)面

使用我最喜歡的 PHP 開(kāi)發(fā)環(huán)境,我已經(jīng)創(chuàng)建了一個(gè)新的發(fā)票文件夾,其包含如下文件:

  • Invoice.php — PHP 生成發(fā)票
  • Invoice.css — CSS 式樣的發(fā)票
  • Azuresol_OnyxTree-S.png — Azuresol 的 “OnyxTree S”,您將其用作您公司的標(biāo)志(來(lái)自 iconfinder.com Web 站點(diǎn)的免費(fèi)圖標(biāo)(請(qǐng)參考 參考資料 ))
  • gentleface_print.png — gentleface 的 “Print”,您將使用其觸發(fā) PDF 生成(來(lái)自 iconfinder.com 的另一個(gè)免費(fèi)圖標(biāo))

在 Invoice.php 內(nèi)部,檢查看看是否使用 PDF 參數(shù)調(diào)用頁(yè)面(請(qǐng)參考 清單 2)。如果不是,用戶想要一個(gè)正常 web 頁(yè)面,這樣您就可以使用 generateHTML 函數(shù)(請(qǐng)參考 清單 3)顯示頁(yè)面。稍后您將看到 generatePDF 函數(shù),但是可以肯定使用它來(lái)生成發(fā)票數(shù)據(jù)的 PDF 沒(méi)任何問(wèn)題。

?
Listing 2. 頁(yè)面生成控制代碼
      if( array_key_exists( 'PDF', $_REQUEST ) ) {
    generatePDF( $invoiceData );
} else {
    generateHTML( $invoiceData );
}
    

$invoiceData 陣列擁有所有發(fā)票數(shù)據(jù);雖然您將直接在 Invoice.php 上創(chuàng)建它,但是您可以設(shè)想數(shù)據(jù)來(lái)自于數(shù)據(jù)庫(kù)、web 服務(wù)或某種網(wǎng)上購(gòu)物車(chē)系統(tǒng)。

?
清單 3. 生成 HTML
      function generateHTML( $data ) {
?>
... HTML code was here ...
<?php
    foreach( $data['items'] as $item ) {
        echo '<tr class="invoiceRow">' . "\n";
        echo '    <td class="itemCol">' . $item[0] . "</td>\n";
        echo '    <td class="quantityCol">' . $item[1] . "</td>\n";
        echo '    <td class="priceCol">' . $item[2] . "</td>\n";
        echo '    <td class="costCol">' . $item[3]. "</td>\n";
        echo "</tr>\n";
    }
?>
... HTML code was here ...
<?php
    echo '<td class="totalCol">' . $data['total'] . "</td>\n";
?>
... HTML code was here ...
<?php
    echo 'Invoice prepared for ' . $data['user'] . ' on ' . $data['date'] . "\n";
?>
... HTML code was here ...
<?php
    
}
    

為了簡(jiǎn)單明了我已經(jīng)刪掉了此處所有的 HTML 標(biāo)記代碼;您可以在位于 CreatingPDFs-Invoice.zip 存檔文件中的 Invoice.php 上看到它, CreatingPDFs-Invoice.zip 存檔文件可以在 下載 部分找到。

使用傳遞給函數(shù)的發(fā)票信息作為 $data ,創(chuàng)建一個(gè)包含每個(gè)項(xiàng)目一行的表、及其數(shù)量、單價(jià)和總價(jià)的表。在表的末尾,添加一個(gè)包含訂單的總成本的行。頁(yè)腳包含用戶 ID 和發(fā)票生成的日期/時(shí)間。

當(dāng)然,簡(jiǎn)單明了的事情,以及您在自己站點(diǎn)上實(shí)現(xiàn)它的時(shí)候所面臨的主要挑戰(zhàn),將與您的數(shù)據(jù)源互動(dòng),并獲得恰到好處的 CSS 式樣。

?
圖 1. 光彩奪目的網(wǎng)頁(yè)發(fā)票

截圖顯示了一個(gè)有吸引力的可打印發(fā)票示例;Sumatra Special 的最大數(shù)量為 24,而其他的則處于 1 到 5 之間

我完全虛構(gòu)了一家提供優(yōu)良咖啡和茶的 South Seas Pacifica 公司,顯然我對(duì) Sumatran 品種深深的吸引了。至少他們的價(jià)格很吸引人!

右下角的打印機(jī)圖標(biāo)是誘人的,您希望能夠有單擊那里并獲得打印發(fā)票。這里就是 TCPDF 的用武之地。并不只是打印網(wǎng)頁(yè),您將為我們尊貴的客戶提供一個(gè)時(shí)髦的 PDF 版本,這會(huì)使他們?cè)谳p松的狀態(tài)下完成打印。

?

第二個(gè)版本 — PDF

現(xiàn)在,您的網(wǎng)頁(yè)發(fā)票看起來(lái)很好,您需要?jiǎng)?chuàng)建可以打印的 PDF 版本。

回憶 清單 2,將 PDF 參數(shù) (http://.../Invoice.php?PDF) 與 Invoice.php 頁(yè)面一起加載將調(diào)用具有相同數(shù)據(jù)的 generatePDF 函數(shù)(請(qǐng)參考清單 4)。

?
清單 4. 生成 PDF 發(fā)票
      function generatePDF( $data ) {
    # Create a new PDF document.
    $pdf = new InvoicePdf( $data, 'P', 'pt', 'LETTER' );

    # Generate the invoice.
    $pdf->CreateInvoice();
    
    # Output the PDF document.
    $pdf->Output( 'Your_Invoice.pdf', 'D' );
}
    

generatePDF 函數(shù)創(chuàng)建了一個(gè) InvoicePdf 對(duì)象,調(diào)用其 CreateInvoice 方法,然后發(fā)送一個(gè)名為 Your_Invoice.pdf 的下載 PDF 文檔給用戶的瀏覽器。雖然這看起來(lái)非常簡(jiǎn)單,但是隱藏了必須自己創(chuàng)建 InvoicePdf 類的事實(shí),且需要復(fù)制原始發(fā)票式樣。讓我們來(lái)看看這是如何進(jìn)行的。

InvoicePdf 類擴(kuò)展了 TCPDF 的 TCPDF 類,這是主 PDF 生成引擎。在構(gòu)造函數(shù)(請(qǐng)參考 清單 5)中,使用傳入的 $orientation (頁(yè)面方向)、 $unit (計(jì)量單位)和 $format (頁(yè) 面大小)初始化父類。TCPDF 構(gòu)造函數(shù)的最后三個(gè)參數(shù)表明輸入的是 Unicode(默認(rèn)為 Ture),已生成 PDF 的字符編碼格式是 UTF-8,且您不應(yīng)使用磁盤(pán)緩存 (False)。雖然在創(chuàng)建 PDF 時(shí),磁盤(pán)緩存減少了內(nèi)存占用,但是速度變得更慢了。因?yàn)槲覀兊奈募淮笠膊粡?fù)雜,所以無(wú)需權(quán)衡這一點(diǎn)。

在初始化父類以后,將參考存儲(chǔ)到發(fā)票數(shù)據(jù)以便今后使用。下一步,使用 SetMargins 方法將頁(yè)邊距設(shè)置為寬度 72 點(diǎn)、高度 36 點(diǎn)。 SetMargins 最終參數(shù)表明您正在用自己的值來(lái)重寫(xiě)默認(rèn)頁(yè)邊距。使用 SetAutoPageBreaks 方法,可在從底部算起有 36 點(diǎn)高時(shí)告知 TCPDF 自動(dòng)創(chuàng)建新頁(yè)面。

?
清單 5. InvoicePdf 類構(gòu)造函數(shù)
      function __construct( $data, $orientation, $unit, $format ) {
    parent::__construct( $orientation, $unit, $format, true, 'UTF-8', false );

    $this->invoiceData = $data;

    # Set the page margins: 72pt on each side, 36pt on top/bottom.
    $this->SetMargins( 72, 36, 72, true );
    $this->SetAutoPageBreak( true, 36 );
    
    # Set document meta-information
    $this->SetCreator( PDF_CREATOR );
    $this->SetAuthor( 'Chris Herborth (chrish@pobox.com)' );
    $this->SetTitle( 'Invoice for ' . $this->invoiceData['user'] );
    $this->SetSubject( "A simple invoice example for 'Creating PDFs on 
the fly with TCPDF' on IBM's developerWorks" );
    $this->SetKeywords( 'PHP, sample, invoice, PDF, TCPDF' );

    //set image scale factor
    $this->setImageScale(PDF_IMAGE_SCALE_RATIO); 
    
    //set some language-dependent strings
    global $l;
    $this->setLanguageArray($l);
}
    

?在建立邊距以后,設(shè)置 PDF 文檔元信息。這將顯示在您最喜歡的 PDF 查看器中的文檔屬性窗口。這些僅僅是字符串,因此您可以將它們?cè)O(shè)置為任何對(duì)您的應(yīng)用程序有意義的信息。

使用 setImageScale 方法,在 TCPDF 的配置文件中使用默認(rèn)圖像縮放比例設(shè)置。這是用于將位圖圖像的大小從像素大小調(diào)整為適合的頁(yè)面。

最后,使用 setLanguageArray 來(lái)為 PDF 文件設(shè)置一些語(yǔ)言相關(guān)的字符串;通過(guò) TCPDF 主配置,這些會(huì)在特定語(yǔ)言配置文件中定義。

在 清單 6 中,您重寫(xiě)了 Header 方法,其被調(diào)用以便生成每一個(gè)頁(yè)面的標(biāo)題內(nèi)容。首先,定義一些變量。以 14 點(diǎn)的 bigFont 大小開(kāi)始,您會(huì)計(jì)算出商標(biāo)圖像的相對(duì)大小和相對(duì)于 bigFont 大小的正常文本大小。然后您將深入 TCPDF 調(diào)用。

ImagePngAlpha 方法插入放置在其左上角寬 72 點(diǎn)、高 32 點(diǎn)的商標(biāo)圖像,其與您以前的邊距設(shè)置相匹配。因?yàn)樗且粋€(gè)正方形的圖像,所以您可以指定相同的寬度和高度(已計(jì)算的 $imageScale )。您將要說(shuō)明它是一個(gè) PNG 圖像,因?yàn)榇苏{(diào)用實(shí)際可以插入 PNG 和 JPEG 圖像(如果在您的 PHP 安裝中已安裝了 GD 庫(kù),則其也可以加載任何由 GD 支持的圖像)。下一步,指定一個(gè)空值,因?yàn)槟鷽](méi)有為此圖像添加 PDF 鏈接(通過(guò) AddLink 方法創(chuàng)建)目標(biāo)。再下一步,使用 T 來(lái)說(shuō)明您想在圖像區(qū)域的右上角制定下一個(gè) PDF 對(duì)象。最后,告知 TCPDF 不要調(diào)整圖像大小,既保持初始的 72 dpi(一個(gè)通用的屏幕分辨率),且圖像在頁(yè)面上應(yīng)該左對(duì)齊。

顯然, ImagePngAlpha 方法對(duì)如何在 PDF 文檔中將圖像添加到頁(yè)面的問(wèn)題上給予您大量的控制(請(qǐng)參考清單 6)。

?
清單 6. 頁(yè)面標(biāo)題的生成
      public function Header() {
    global $webcolor;

    # The image is this much larger than the company name text.
    $bigFont = 14;
    $imageScale = ( 128.0 / 26.0 ) * $bigFont;
    $smallFont = ( 16.0 / 26.0 ) * $bigFont;

    $this->ImagePngAlpha('Azuresol_OnyxTree-S.png', 72, 36, $imageScale, 
$imageScale, 'PNG', null, 'T', false, 72, 'L' );
    $this->SetFont('times', 'b', $bigFont );
    $this->Cell( 0, 0, 'South Seas Pacifica', 0, 1 );
    $this->SetFont('times', 'i', $smallFont );
    $this->Cell( $imageScale );
    $this->Cell( 0, 0, '', 0, 1 );
    $this->Cell( $imageScale );
    $this->Cell( 0, 0, '31337 Docks Avenue,', 0, 1 );
    $this->Cell( $imageScale );
    $this->Cell( 0, 0, 'Toronto, Ontario', 0, 1 );

    $this->SetY( 1.5 * 72, true );
    $this->SetLineStyle( array( 'width' => 2, 'color' => 
array( $webcolor['black'] ) ) );
    $this->Line( 72, 36 + $imageScale, $this->getPageWidth() - 72, 36 
+ $imageScale );
}
    

在標(biāo)題上放置商標(biāo)圖像以后,設(shè)置字體(粗體 Times,使用您的 bigFont 大?。?,然后創(chuàng)建一些單元格來(lái)存放公司的名稱和地址信息。這些單元格在 HTML 上包含文本,而且有點(diǎn)像表格單元格。 Cell 方法采用這些參數(shù)(實(shí)際上更多;參考 TCPDF 文檔獲取完整列表):

  • Width — 單元格寬度;如果設(shè)置為 0,則單元格一直擴(kuò)展到右側(cè)邊距(或者如果您使用的是從右到左的語(yǔ)言,則擴(kuò)展到左側(cè)邊距)。
  • Height — 單元格高度;如果設(shè)置為 0,則單元格高度將擴(kuò)展,以便能放得下內(nèi)容。
  • Text — 該文本在單元格內(nèi)繪制,使用當(dāng)前的字體和顏色設(shè)置。
  • Border — 說(shuō)明是否邊界應(yīng)該根據(jù)單元格制定。在這種情況下,由于您正在使用 0,所以您無(wú)需任何邊界。您也可以傳遞 1 來(lái)根據(jù)單元格制定完整的邊界,或字符串以便說(shuō)明特定的邊界。
  • Position — 說(shuō)明何處創(chuàng)建下一個(gè)單元格;1 表明您需要其在下一行的開(kāi)始出顯示,但是您可以使用 0 在此單元格旁邊添加下一個(gè)單元格,或者 2 以停留在當(dāng)前的 X 坐標(biāo)并移到下一行。

最后,我們的 Header 方法在標(biāo)題的底部繪制了一條兩點(diǎn)黑線,一直穿過(guò)頁(yè)面的內(nèi)容區(qū)域。圖 2 顯示了將如何在頁(yè)面上查看,如 Mac OS X 的 預(yù)覽應(yīng)用程序所呈現(xiàn)的那樣。

?
圖 2. 打印標(biāo)題,就像網(wǎng)頁(yè)標(biāo)題

截圖對(duì)左邊的地址顯示了帶有圖形商標(biāo)的標(biāo)題,名稱使用大的、粗體的字體,且地址使用斜體

現(xiàn)在您已經(jīng)創(chuàng)建了一個(gè)原始標(biāo)題的合理副本,您也需要重寫(xiě) Footer 方法,以便于您生成頁(yè)腳。這非常簡(jiǎn)單,只包含用戶 ID 和發(fā)票信息,其通過(guò)另外一個(gè)兩點(diǎn)黑線從剩余的頁(yè)面中分離出來(lái)。

您尚未看到此方法的唯一部分正在使用使用一個(gè)負(fù)值調(diào)用 SetY 方法。在您這樣做的時(shí)候,相對(duì)于頁(yè)面的底部設(shè)置當(dāng)前的 Y 。在這里,您將要為頁(yè)面頁(yè)腳留下大量的空間,以確保您的繪制不太接近底部邊距(請(qǐng)參考清單 7)。

?
清單 7. 頁(yè)面頁(yè)腳的生成
      public function Footer() {
    global $webcolor;

    $this->SetLineStyle( array( 'width' => 2, 'color' => 
array( $webcolor['black'] ) ) );
    $this->Line( 72, $this->getPageHeight() - 1.5 * 72 - 2, 
$this->getPageWidth() - 72, $this->getPageHeight() - 1.5 * 72 - 2 );
    $this->SetFont( 'times', '', 8 );
    $this->SetY( -1.5 * 72, true );
    $this->Cell( 72, 0, 'Invoice prepared for ' . 
$this->invoiceData['user'] . ' on ' . $this->invoiceData['date'] );
}
    

在您創(chuàng)建頁(yè)面時(shí),顯示出來(lái)的就像發(fā)票的網(wǎng)絡(luò)版,只是減去了打印機(jī)的圖標(biāo)。您已經(jīng)中斷了此操作,因?yàn)檫@是打印版本(它是多余的)。圖 3 得出了結(jié)果。

?
圖 3. 已打印的頁(yè)腳

截圖顯示了頁(yè)腳,其對(duì)帶有收件人、時(shí)間和日期的詳細(xì)信息用粗體水平線標(biāo)出

在這一點(diǎn)上,您擁有附帶美觀的頁(yè)眉和頁(yè)腳的空白頁(yè)。您需要為此添加實(shí)際的發(fā)票內(nèi)容,這樣做很有用。

在使用 AddPage 方法啟動(dòng)新的頁(yè)面以后(在這種情況下,這是唯一的頁(yè)面),將字體設(shè)置為 11 點(diǎn) Helvetica 并將插入點(diǎn)從頁(yè)面的頂部移動(dòng)到 144 點(diǎn)處。在表開(kāi)始以前,這會(huì)在頁(yè)眉以下給我們留出一個(gè)小空間。

下一步,要計(jì)算您將需要使表居中的縮進(jìn)量,這基于頁(yè)面寬度、兩個(gè) 72 點(diǎn)邊距、一個(gè)寬列和三個(gè)正常列。

在此之后,您將使用以前計(jì)算出的值并描繪出每個(gè)單元格的完全邊界,來(lái)創(chuàng)建一系列單元格以呈現(xiàn)列標(biāo)題。您還要右對(duì)齊數(shù)字列的標(biāo)題因?yàn)樗鼈兺ㄟ^(guò)值進(jìn)行排列。在標(biāo)題單元格的最后,您要調(diào)用 Ln 方法以便向下移動(dòng)到下一行的開(kāi)始。

通過(guò)在發(fā)票上迭代項(xiàng)目的 foreach 循環(huán),您為每一個(gè)內(nèi)容行進(jìn)行同類型的布局(請(qǐng)參考清單 8)。

?
清單 8. 頁(yè)面內(nèi)容的生成
      public function CreateInvoice() {
    $this->AddPage();
    $this->SetFont( 'helvetica', '', 11 );
    $this->SetY( 144, true );

    # Table parameters
    #
    # Column size, wide (description) column, table indent, row height.
    $col = 72;
    $wideCol = 3 * $col;
    $indent = ( $this->getPageWidth() - 2 * 72 - $wideCol - 3 * $col ) / 2;
    $line = 18;

    # Table header
    $this->SetFont( '', 'b' );
    $this->Cell( $indent );
    $this->Cell( $wideCol, $line, 'Item', 1, 0, 'L' );
    $this->Cell( $col, $line, 'Quantity', 1, 0, 'R' );
    $this->Cell( $col, $line, 'Price', 1, 0, 'R' );
    $this->Cell( $col, $line, 'Cost', 1, 0, 'R' );
    $this->Ln();

    # Table content rows
    $this->SetFont( '', '' );
    foreach( $this->invoiceData['items'] as $item ) {
        $this->Cell( $indent );
        $this->Cell( $wideCol, $line, $item[0], 1, 0, 'L' );
        $this->Cell( $col, $line, $item[1], 1, 0, 'R' );
        $this->Cell( $col, $line, $item[2], 1, 0, 'R' );
        $this->Cell( $col, $line, $item[3], 1, 0, 'R' );
        $this->Ln();
    }

    # Table Total row
    $this->SetFont( '', 'b' );
    $this->Cell( $indent );
    $this->Cell( $wideCol + $col * 2, $line, 'Total:', 1, 0, 'R' );
    $this->SetFont( '', '' );
    $this->Cell( $col, $line, $this->invoiceData['total'], 1, 0, 'R' );
}
    

代碼的最后一位呈現(xiàn)總行數(shù)。這演示了您如何可以更容易地在單元格之間變更字體式樣(通過(guò)調(diào)用 SetFont 方法來(lái)打開(kāi)或關(guān)閉粗體)。第一個(gè)文本單元格的寬度被設(shè)置橫跨表的前三列,因?yàn)槟枰l(fā)票總數(shù)出現(xiàn)在最后一列的底部。

一旦您完成后,發(fā)票項(xiàng)目表看起來(lái)將非常的棒(請(qǐng)參考圖 4)。

?
圖 4. 發(fā)票上的項(xiàng)目

附帶數(shù)量、價(jià)格和總數(shù)的項(xiàng)目格式化清單的截圖

通過(guò)邏輯地布局文本單元格,您已經(jīng)用適合打印的格式重新創(chuàng)建了初始的網(wǎng)頁(yè)。在無(wú)需變更網(wǎng)頁(yè)本身或任何基礎(chǔ)數(shù)據(jù)的情況下,TCPDF 讓您將創(chuàng)建 PDF 的支持添加到您現(xiàn)存的 PHP 網(wǎng)頁(yè)上。

?

結(jié)束語(yǔ)

本 文向您介紹了 TCPDF,它是一種用于生成 PDF 文檔的流行 PHP 庫(kù)。TCPDF 無(wú)需額外的庫(kù)就能執(zhí)行此操作,并使其作為您現(xiàn)有 PHP 網(wǎng)站的一部分易于安裝。本文向您顯示了在類 UNIX 系統(tǒng)中安裝并配置 TCPDF 的概述。然后您創(chuàng)建了一個(gè)簡(jiǎn)單的基于 Web 的發(fā)票,類似于您可能在一家從事異國(guó)熱飲的電子商務(wù)站點(diǎn)上所看到的諸如此類的事情。

一旦您擁有一個(gè)看上去像專業(yè)發(fā)票的網(wǎng)頁(yè),您就可以擴(kuò)展 TCPDF 類來(lái)生產(chǎn)一個(gè) PDF 版本的發(fā)票,即客戶可以輕松地下載或打印。重寫(xiě) Header Footer 方法讓我們用相似的方式建立頁(yè)面,然后您可以編寫(xiě)一個(gè)附加方法來(lái)布置發(fā)票項(xiàng)目作為一個(gè)表。

?

參考資料

學(xué)習(xí)

獲得產(chǎn)品和技術(shù)

討論

原文: http://www.ibm.com/developerworks/cn/opensource/os-tcpdf/

?

1. 動(dòng)態(tài)加載header

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

// change header dynamicly
$pdf->setHeaderTemplateAutoreset(true);

// set default header data
$pdf->SetHeaderData('', 0, 'Wu  Wang / 130501901');

// Start First Page Group
$pdf->startPageGroup();

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

$pdf->writeHTML($html, true, false, false, false, '');

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

// change header dynamicly
$pdf->setHeaderTemplateAutoreset(true);

// set default header data
$pdf->SetHeaderData('', 0, 'San  Zhang / 130501901');

// Start Second Page Group
$pdf->startPageGroup();

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

$pdf->writeHTML($html, true, false, false, false, '');

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

// change header dynamicly
$pdf->setHeaderTemplateAutoreset(true);

// set default header data
$pdf->SetHeaderData('', 0, 'Si  Lee / 130501901');

// Start Third Page Group
$pdf->startPageGroup();

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

$pdf->writeHTML($html, true, false, false, false, '');

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

$pdf->Output('student_attendances_example.pdf', 'I');
    

?

2. 保存pdf到本地文件夾

      $pdf->Output('/path/to/file.pdf', 'F')
    

?

3. 添加背景圖片

      $pdf->AddPage();
$img_file = K_PATH_IMAGES.'logo_tr.jpg';
$pdf->Image($img_file, 115, 240, 360);
    

?

4. 生成表格

      function pdf($students,$semester)
{
    $docRoot = rtrim($_SERVER["DOCUMENT_ROOT"],'/') . '/services/';
    define('K_PATH_IMAGES', $docRoot.'attendances/images/');
    define('K_PATH_CACHE',  $docRoot.'attendances/images/');  //exit(K_PATH_CACHE);
    include_once $docRoot.'tcpdf/tcpdf.php';
    $pdf = new TCPDF('L','pt',PDF_PAGE_FORMAT, true,'UTF-8',false);
    
    //echo '<pre>'; print_r($students); echo '</pre>';
    
    $margin_left   = 36;
    $margin_right  = 36;
    $margin_top    = 30;
    $margin_bottom = 30;

    # Set document meta-information
    $pdf->SetCreator(PDF_CREATOR);
    $pdf->SetAuthor('R&D');
    $pdf->SetTitle('OU - Myolivet');
    $pdf->SetSubject('OU');
    $pdf->SetKeywords('Student Attendances, OU, Semesters, Quarters');

    # Set the page margins: 72pt on each side, 36pt on top/bottom.
    $pdf->SetMargins($margin_left, $margin_top, $margin_right);
    $pdf->SetHeaderMargin(12);
    $pdf->SetFooterMargin(20);
    $pdf->SetAutoPageBreak(true, $margin_bottom);
    
    // set header and footer fonts
    $pdf->setHeaderFont(Array(PDF_FONT_NAME_MAIN, '', 9));
    $pdf->setFooterFont(Array(PDF_FONT_NAME_DATA, '', PDF_FONT_SIZE_DATA));
    
    //set image scale factor
    $pdf->setImageScale(PDF_IMAGE_SCALE_RATIO); 
    
    // set default monospaced font
    $pdf->SetDefaultMonospacedFont(PDF_FONT_MONOSPACED);

    # Table parameters
    #
    # Column size, wide (description) column, table indent, row height.
    $table_padding  = 7;
    $table_width    = $pdf->getPageWidth() - 2 * ($table_padding + $margin_left);
    $cell_width     = $table_width / 7;
    $double_cell    = $cell_width * 2;
    $triple_cell    = $cell_width * 3;
    $quadruple_cell = $cell_width * 4;
    $tuep_cell      = $cell_width * 3/4;
    $line_height    = 18;
    
    $total_box      = 35;
    $box_width      = $table_width / $total_box;
    $sixteen_cell   = $box_width * 16;
    $fifteen_cell   = $box_width * 15;
    $two_cell       = $box_width * 2;
    $three_cell     = $box_width * 3;
    $four_cell      = $box_width * 4;
    $five_cell      = $box_width * 5;
    $six_cell       = $box_width * 6;
    $seven_cell     = $box_width * 7;
    $eight_cell     = $box_width * 8;
    $full_cell      = $box_width * $total_box;
    
    $tiny_font      = 8;
    $small_font     = 9;
    $normal_font    = 10;
    $big_font       = 12;
    
    foreach($students as $studentid=>$student)
    {
        $_student = $student['Student'];
        $_program = $student['Program'];
        $_sheet   = $student['Sheet'];
        
        if(!count($_sheet)) continue;
        
        $full_name    = $_student['firstname'].' '.$_student['middlename'].' '.$_student['lastname'];
        $gender       = $_student['gender'] ? 'Male' : 'Female';
        $program_type = $_student['study_type']==1?'Online':'On Site';
        $city         = 'San Francisco';
        $state        = 'CA';
        $zipcode      = '94103';
        
        $pdf->setHeaderTemplateAutoreset(true);
        $pdf->SetHeaderData('', 0, $full_name.' / '.$studentid);
        $pdf->startPageGroup();

        $pdf->AddPage();
        $pdf->SetFont('helvetica', '', $normal_font);
        $pdf->SetY( 60, true );
                
        $pdf->SetFont( '', 'b', $big_font );
        $pdf->Cell( $table_padding );
        //$pdf->MultiCell($table_width, $line_height*3, '<img src="images/OUlogo.gif" width="200"> <br> Olivet University Student Attendance Record', 'LTR', 'C', 0, 0, '', '', true, null, true);
        $pdf->MultiCell($table_width, $line_height*2, '<img src="img/OUlogo.gif" width="200"> <br> Olivet University Student Attendance Record<br> ', 'LTR', 'C', 0, 0, '', '', true, null, true);
        $pdf->Ln();
        
        # Table header
        $pdf->SetFont( '', 'b', $normal_font );
        $pdf->Cell( $table_padding );
        $pdf->Cell( $double_cell, $line_height, 'Name of Student', 'LT', 0, 'C' );
        $pdf->Cell( $cell_width, $line_height, 'Student ID', 'LT', 0, 'C' );
        $pdf->Cell( $cell_width, $line_height, 'Gender', 'LT', 0, 'C' );
        $pdf->Cell( $double_cell, $line_height, 'Major', 'LT', 0, 'C' );
        $pdf->Cell( $cell_width, $line_height, 'Program Type', 'LTR', 0, 'C' );
        $pdf->Ln();

        # Table content rows
        $pdf->SetFont( '', '' );
        $pdf->Cell( $table_padding );
        $pdf->Cell( $double_cell, $line_height, $full_name, 'LT', 0, 'C' );
        $pdf->Cell( $cell_width, $line_height, $studentid, 'LT', 0, 'C' );
        $pdf->Cell( $cell_width, $line_height, $gender, 'LT', 0, 'C' );
        $pdf->Cell( $double_cell, $line_height, $_program['name'], 'LT', 0, 'C' );
        $pdf->Cell( $cell_width, $line_height, $program_type, 'LTR', 0, 'C' );
        $pdf->Ln();
        
        # Table header
        $pdf->SetFont( '', 'b', $normal_font );
        $pdf->Cell( $table_padding );
        $pdf->Cell( $double_cell, $line_height, 'Email', 'LT', 0, 'C' );
        $pdf->Cell( $double_cell, $line_height, 'City', 'LT', 0, 'C' );
        $pdf->Cell( $double_cell, $line_height, 'State', 'LT', 0, 'C' );
        $pdf->Cell( $cell_width, $line_height, 'Zip Code', 'LTR', 0, 'C' );
        $pdf->Ln();

        # Table content rows
        $pdf->SetFont( '', '' );
        $pdf->Cell( $table_padding );
        $pdf->Cell( $double_cell, $line_height, $_student['email'], 'LT', 0, 'C' );
        $pdf->Cell( $double_cell, $line_height, $city, 'LT', 0, 'C' );
        $pdf->Cell( $double_cell, $line_height, $state, 'LT', 0, 'C' );
        $pdf->Cell( $cell_width, $line_height, $zipcode, 'LTR', 0, 'C' );
        $pdf->Ln();

        # Table content rows
        $pdf->SetFont( '', 'b', $normal_font );
        $pdf->Cell( $table_padding );
        $pdf->Cell( $quadruple_cell, $line_height*2, 'T=Tardy; U=Unexcused; E=Excused; P=Present', 'LTB', 0, 'C' );
        $pdf->Cell( $triple_cell, $line_height, 'Attendance Totals', 'LTR', 0, 'C' );
        $pdf->Ln();

        $pdf->SetFont( '', '' );
        $pdf->Cell( $quadruple_cell + $table_padding );
        $pdf->Cell( $tuep_cell, $line_height, 'Tardy', 'LTB', 0, 'C' );
        $pdf->Cell( $tuep_cell, $line_height, 'Unexcused', 'LTB', 0, 'C' );
        $pdf->Cell( $tuep_cell, $line_height, 'Excused', 'LTB', 0, 'C' );
        $pdf->Cell( $tuep_cell, $line_height, 'Present', 'LTBR', 0, 'C' );
        $pdf->Ln(32);

        # Table header
        $pdf->SetFont( '', 'b', $normal_font );
        $pdf->Cell( $table_padding );
        $pdf->Cell( $sixteen_cell, $line_height, 'Course Information', 'LT', 0, 'C' );
        $pdf->Cell( $fifteen_cell, $line_height, 'Weeks of the Quarter', 'LT', 0, 'C' );
        $pdf->Cell( $four_cell, $line_height, 'Total', 'LTR', 0, 'C' );
        $pdf->Ln();

        # Table content rows
        $total_courses    = count($_sheet); 
        $head_borders     = $total_courses ? 'LT' : 'LTB';
        $head_last_border = $total_courses ? 'LTR' : 'LTRB';
        
        $pdf->SetFont( '', '' );
        $pdf->Cell( $table_padding );
        $pdf->Cell( $three_cell, $line_height, 'Quarter', $head_borders, 0, 'C' );
        $pdf->Cell( $three_cell, $line_height, 'Course No', $head_borders, 0, 'C' );
        $pdf->Cell( $eight_cell, $line_height, 'Course Title', $head_borders, 0, 'C' );
        $pdf->Cell( $two_cell, $line_height, 'Units', $head_borders, 0, 'C' );
        $pdf->Cell( $box_width, $line_height, '1', $head_borders, 0, 'C' );
        $pdf->Cell( $box_width, $line_height, '2', $head_borders, 0, 'C' );
        $pdf->Cell( $box_width, $line_height, '3', $head_borders, 0, 'C' );
        $pdf->Cell( $box_width, $line_height, '4', $head_borders, 0, 'C' );
        $pdf->Cell( $box_width, $line_height, '5', $head_borders, 0, 'C' );
        $pdf->Cell( $box_width, $line_height, '6', $head_borders, 0, 'C' );
        $pdf->Cell( $box_width, $line_height, '7', $head_borders, 0, 'C' );
        $pdf->Cell( $box_width, $line_height, '8', $head_borders, 0, 'C' );
        $pdf->Cell( $box_width, $line_height, '9', $head_borders, 0, 'C' );
        $pdf->Cell( $box_width, $line_height, '10', $head_borders, 0, 'C' );
        $pdf->Cell( $box_width, $line_height, '11', $head_borders, 0, 'C' );
        $pdf->Cell( $box_width, $line_height, '12', $head_borders, 0, 'C' );
        $pdf->Cell( $box_width, $line_height, '13', $head_borders, 0, 'C' );
        $pdf->Cell( $box_width, $line_height, '14', $head_borders, 0, 'C' );
        $pdf->Cell( $box_width, $line_height, '15', $head_borders, 0, 'C' );
        $pdf->Cell( $box_width, $line_height, 'P', $head_borders, 0, 'C' );
        $pdf->Cell( $box_width, $line_height, 'E', $head_borders, 0, 'C' );
        $pdf->Cell( $box_width, $line_height, 'U', $head_borders, 0, 'C' );
        $pdf->Cell( $box_width, $line_height, 'T', $head_last_border, 0, 'C' );
        $pdf->Ln();    
                         
        if($_sheet)
        {
            $i = 1;
            foreach($_sheet as $attend)
            {
                $borders     = $i<$total_courses ? 'LT' : 'LTB';
                $last_border = $i<$total_courses ? 'LTR' : 'LTRB';
                
                $attendstring = $attend['attendstring'];
                if(strlen($attendstring)<30) $attendstring .= str_repeat('-', (30-strlen($attendstring))); 

                $pstring =substr_count($attendstring,'P');
                $estring =substr_count($attendstring,'E');
                $ustring =substr_count($attendstring,'U');
                $tstring =substr_count($attendstring,'T');
                $stringarray= str_split($attendstring,2);
    
                //MultiCell($w, $h, $txt, $border=0, $align='J', $fill=false, $ln=1, $x='', $y='', $reseth=true, $stretch=0, $ishtml=false, $autopadding=true, $maxh=0, $valign='T', $fitcell=false)
                
                # Table content rows
                $pdf->SetFont( '', '' );
                $pdf->Cell( $table_padding );
                $pdf->Cell( $three_cell, $line_height, $attend['Semester'], $borders, 0, 'C' );
                $pdf->Cell( $three_cell, $line_height, $attend['code'], $borders, 0, 'C' );
                
                if(strlen($attend['title'])>32) $pdf->SetFont( '', '', $small_font );
                if(strlen($attend['title'])>42) $pdf->SetFont( '', '', $tiny_font );
                $pdf->MultiCell( $eight_cell, $line_height, $attend['title'],  $borders, 'C', 0, 0, '', '', true, null, true);
                $pdf->SetFont( '', '', $normal_font );
                
                $pdf->Cell( $two_cell, $line_height, $attend['units'], $borders, 0, 'C' );
                
                foreach($stringarray as $str)
                {
                    $str_array = str_split($str);
                    $pdf->Cell( $box_width, $line_height, $str_array[0].($str_array[1]=='-'?'':$str_array[1]), $borders, 0, 'C' );
                } 
                
                $pdf->Cell( $box_width, $line_height, $pstring, $borders, 0, 'C' );
                $pdf->Cell( $box_width, $line_height, $estring, $borders, 0, 'C' );
                $pdf->Cell( $box_width, $line_height, $ustring, $borders, 0, 'C' );
                $pdf->Cell( $box_width, $line_height, $tstring, $last_border, 0, 'C' );
                $pdf->Ln(); 
                
                $i++;                     
            }
        }
    }

    //$pdf->Output( 'Your_Invoice.pdf', 'I' );
    $pdf->Output( 'Student_Attendances_in_'.str_replace(' ', '_', $semester).'.pdf', 'D' );
}
    

?

使用 TCPDF 動(dòng)態(tài)創(chuàng)建 PDF


更多文章、技術(shù)交流、商務(wù)合作、聯(lián)系博主

微信掃碼或搜索:z360901061

微信掃一掃加我為好友

QQ號(hào)聯(lián)系: 360901061

您的支持是博主寫(xiě)作最大的動(dòng)力,如果您喜歡我的文章,感覺(jué)我的文章對(duì)您有幫助,請(qǐng)用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點(diǎn)擊下面給點(diǎn)支持吧,站長(zhǎng)非常感激您!手機(jī)微信長(zhǎng)按不能支付解決辦法:請(qǐng)將微信支付二維碼保存到相冊(cè),切換到微信,然后點(diǎn)擊微信右上角掃一掃功能,選擇支付二維碼完成支付。

【本文對(duì)您有幫助就好】

您的支持是博主寫(xiě)作最大的動(dòng)力,如果您喜歡我的文章,感覺(jué)我的文章對(duì)您有幫助,請(qǐng)用微信掃描上面二維碼支持博主2元、5元、10元、自定義金額等您想捐的金額吧,站長(zhǎng)會(huì)非常 感謝您的哦!??!

發(fā)表我的評(píng)論
最新評(píng)論 總共0條評(píng)論