天天看點

Zend Framework——PDF

Zend_Pdf

生成新的或加載 PDF 文檔

...
// 生成新的 PDF 文檔.
$pdf1 = new Zend_Pdf();

// 從檔案加載 PDF 文檔
$pdf2 = Zend_Pdf::load($fileName);

// 從字元串加載 PDF 文檔
$pdf3 = Zend_Pdf::parse($pdfString);
...
           

請求 PDF 文檔的指定版本

PDF 檔案格式支援增量式文檔更新。這樣每次文檔更新,就産生新的版本。Zend_Pdf 子產品支援指定版本的讀取。

版本可以指定為 Zend_Pdf::load() 和 Zend_Pdf::parse()的第二個參數或由 Zend_Pdf::rollback() 來請求,

Zend_Pdf::rollback() 方法必需在任何修改前調用,否則它的行為就沒有定義。

...
// Load PDF previouse revision of the document.
$pdf1 = Zend_Pdf::load($fileName, );

// Load PDF previouse revision of the document.
$pdf2 = Zend_Pdf::parse($pdfString, );

// Load first revision of the document.
$pdf3 = Zend_Pdf::load($fileName);
$revisions = $pdf3->revisions();
$pdf3->rollback($revisions - );
...
           

儲存修改到 PDF 文檔

有兩個方法來儲存修改到 PDF 文檔:Zend_Pdf::save() 和 Zend_Pdf::render()。

Zend_Pdf::save($filename, $updateOnly = false)

儲存 PDF 文檔到一個檔案。如果 $updateOnly 是 true,那麼隻有新的 PDF 檔案段被追加到檔案,否則,重寫檔案。

Zend_Pdf::render($newSegmentOnly = false)

把 PDF 文檔當作字元串傳回。如果 $newSegmentOnly 是 true,那麼隻有新的 PDF 檔案段傳回。

...
// Load PDF document.
$pdf = Zend_Pdf::load($fileName);
...
// Update document
$pdf->save($fileName, true);
// Save document as a new file
$pdf->save($newFileName);

// Return PDF document as a string.
$pdfString = $pdf->render();

...
           

Zend_Pdf_Page

新頁面可以通過建立 Zend_Pdf_Page 對象或調用 Zend_Pdf::newPage() 方法來獲得,它傳回 Zend_Pdf_Page 對象。Zend_Pdf::newPage() 方法生成已經附加到文檔的頁面,和未附加的頁面不同的是它不能和若幹個 PDF 文檔一起用,但是性能會稍好一些。有一個參數可選:

Zend_Pdf_Page::SIZE_A4

Zend_Pdf_Page::SIZE_A4_LANDSCAPE

Zend_Pdf_Page::SIZE_LETTER

Zend_Pdf_Page::SIZE_LETTER_LANDSCAPE

文檔存儲在 Zend_Pdf 類的 public 成員 $pages 裡,它是 Zend_Pdf_Page 對象的一個數組。它完整地定義了設定和文檔頁面的順序并可以當做普通的數組來處理:

...
    // Reverse page order
    $pdf->pages = array_reverse($pdf->pages);
    //array_reverse 以相反順序傳回元素
    ...
    // Add new page  Object
    $pdf->pages[] = new Zend_Pdf_Page(Zend_Pdf_Page::SIZE_A4);
    // Add new page  method
    $pdf->pages[] = $pdf->newPage(Zend_Pdf_Page::SIZE_A4);

    // Remove specified page.
    unset($pdf->pages[$id]);

    ...
           

頁面克隆

...
    // 将模闆頁面存儲在單獨的變量中
    $template = $pdf->pages[$templatePageIndex];
    ...
    // Add new page
    $page1 = new Zend_Pdf_Page($template);
    $pdf->pages[] = $page1;
    ...

    // Add another page
    $page2 = new Zend_Pdf_Page($template);
    $pdf->pages[] = $page2;
    ...

    // Remove source template page from the documents.
    unset($pdf->pages[$templatePageIndex]);

    ...
           

繪制圖形

1.坐标體系

它從頁面的左下角開始,預設情況下以磅(1/72英寸)為機關進行測量。

從一個pages對象中擷取Width和Hight

$width  = $pdfPage->getWidth();
$height = $pdfPage->getHeight();
           

2.顔色

Zend_Pdf子產品支援Gray Scale,RGB和CMYK顔色空間,還提供HTML樣式顔色:

// $grayLevel (float number). 0.0 (black) - 1.0 (white)
$color1 = new Zend_Pdf_Color_GrayScale($grayLevel);

// $r, $g, $b (float numbers). 0.0 (min intensity) - 1.0 (max intensity)
$color2 = new Zend_Pdf_Color_Rgb($r, $g, $b);

// $c, $m, $y, $k (float numbers). 0.0 (min intensity) - 1.0 (max intensity)
$color3 = new Zend_Pdf_Color_Cmyk($c, $m, $y, $k);

//html
$color1 = new Zend_Pdf_Color_Html('#3366FF');
$color2 = new Zend_Pdf_Color_Html('silver');
$color3 = new Zend_Pdf_Color_Html('forestgreen');
           

3.形狀繪圖

/**
 * Draw a line from x1,y1 to x2,y2.
 *
 * @param float $x1
 * @param float $y1
 * @param float $x2
 * @param float $y2
 * @return Zend_Pdf_Page 
 */
public function drawLine($x1, $y1, $x2, $y2);
           
/**
 * Draw a rectangle.
 *
 * Fill types:
 * Zend_Pdf_Page::SHAPE_DRAW_FILL_AND_STROKE - fill rectangle
 *                                             and stroke (default)
 * Zend_Pdf_Page::SHAPE_DRAW_STROKE          - stroke rectangle
 * Zend_Pdf_Page::SHAPE_DRAW_FILL            - fill rectangle
 *
 * @param float $x1
 * @param float $y1
 * @param float $x2
 * @param float $y2
 * @param integer $fillType
 * @return Zend_Pdf_Page 
 */
public function drawRectangle($x1, $y1, $x2, $y2,
                    $fillType = Zend_Pdf_Page::SHAPE_DRAW_FILL_AND_STROKE);
           
/**
 * Draw a polygon.多邊形
 *
 * If $fillType is Zend_Pdf_Page::SHAPE_DRAW_FILL_AND_STROKE or
 * Zend_Pdf_Page::SHAPE_DRAW_FILL, then polygon is automatically closed.
 *
 * @param array $x  - array of float (the X co-ordinates of the vertices)
 * @param array $y  - array of float (the Y co-ordinates of the vertices)
 * @param integer $fillType
 * @param integer $fillMethod
 * @return Zend_Pdf_Page 
 */
public function drawPolygon($x, $y,
                            $fillType =
                                Zend_Pdf_Page::SHAPE_DRAW_FILL_AND_STROKE,
                            $fillMethod =
                                Zend_Pdf_Page::FILL_METHOD_NON_ZERO_WINDING);
           
/**
 * Draw a circle centered on x, y with a radius of radius.
 *
 * Angles are specified in radians
 *
 * Method signatures:
 * drawCircle($x, $y, $radius);
 * drawCircle($x, $y, $radius, $fillType);
 * drawCircle($x, $y, $radius, $startAngle, $endAngle);
 * drawCircle($x, $y, $radius, $startAngle, $endAngle, $fillType);
 *
 *
 * It's not a really circle, because PDF supports only cubic Bezier
 * curves. But very good approximation.
 * It differs from a real circle on a maximum 0.00026 radiuses (at PI/8,
 * 3*PI/8, 5*PI/8, 7*PI/8, 9*PI/8, 11*PI/8, 13*PI/8 and 15*PI/8 angles).
 * At 0, PI/4, PI/2, 3*PI/4, PI, 5*PI/4, 3*PI/2 and 7*PI/4 it's exactly
 * a tangent to a circle.
 *
 * @param float $x
 * @param float $y
 * @param float $radius
 * @param mixed $param4
 * @param mixed $param5
 * @param mixed $param6
 * @return Zend_Pdf_Page 
 */
public function  drawCircle($x,
                            $y,
                            $radius,
                            $param4 = null,
                            $param5 = null,
                            $param6 = null);
           
/**
 * Draw an ellipse inside the specified rectangle.在指定的矩形内繪制一個橢圓
 *
 * Method signatures:
 * drawEllipse($x1, $y1, $x2, $y2);
 * drawEllipse($x1, $y1, $x2, $y2, $fillType);
 * drawEllipse($x1, $y1, $x2, $y2, $startAngle, $endAngle);
 * drawEllipse($x1, $y1, $x2, $y2, $startAngle, $endAngle, $fillType);
 *
 * Angles are specified in radians
 *
 * @param float $x1
 * @param float $y1
 * @param float $x2
 * @param float $y2
 * @param mixed $param5
 * @param mixed $param6
 * @param mixed $param7
 * @return Zend_Pdf_Page 
 */
public function drawEllipse($x1,
                            $y1,
                            $x2,
                            $y2,
                            $param5 = null,
                            $param6 = null,
                            $param7 = null);
           

4.文字繪圖

您可以通過提供基線的x和y坐标在頁面上的任何位置繪制單行文本。目前字型和目前字型大小用于文本繪制操作。

/**
 * Draw a line of text at the specified position.
 *
 * @param string $text
 * @param float $x
 * @param float $y
 * @param string $charEncoding (optional)可選
 * Character encoding of source text.Defaults to current locale.
 * 源文本的字元編碼。預設為目前語言環境,您可以使用PHP的iconv()函數支援的任何編碼方法提供源字元串
 * @throws Zend_Pdf_Exception
 * @return Zend_Pdf_Page 
 */
public function drawText($text, $x, $y, $charEncoding = '');
           

在頁面上繪制一個預設字元串

...
$pdfPage->drawText('Hello world!', , );
...
           

在頁面上繪制一個UTF-8編碼的字元串

...
// Read a UTF--encoded string from disk
$unicodeString = fread($fp, );

// Draw the string on the page
$pdfPage->drawText($unicodeString, , , 'UTF-8');
...
           

5.設定字型

Zend_Pdf_Page :: drawText()

預設使用頁面的目前字型和字型大小,使用

Zend_Pdf_Page :: setFont()

方法設定:

/**
 * Set current font.
 *
 * @param Zend_Pdf_Resource_Font $font
 * @param float $fontSize
 * @return Zend_Pdf_Page 
 */
public function setFont(Zend_Pdf_Resource_Font $font, $fontSize);
           

Zend_Pdf目前支援标準的14種PDF字型以及您自己的自定義TrueType字型。

字型對象通過兩種工廠方法之一獲得:标準14 PDF字型的

Zend_Pdf_Font :: fontWithName($fontName)

或自定義字型的

Zend_Pdf_Font :: fontWithPath($ filePath)

标準14 PDF字型名稱的常量在Zend_Pdf_Font類中定義:

Zend_Pdf_Font :: FONT_COURIER

Zend_Pdf_Font :: FONT_COURIER_BOLD

Zend_Pdf_Font :: FONT_COURIER_ITALIC

Zend_Pdf_Font :: FONT_COURIER_BOLD_ITALIC

Zend_Pdf_Font :: FONT_TIMES

Zend_Pdf_Font :: FONT_TIMES_BOLD

Zend_Pdf_Font :: FONT_TIMES_ITALIC

Zend_Pdf_Font :: FONT_TIMES_BOLD_ITALIC

Zend_Pdf_Font :: FONT_HELVETICA

Zend_Pdf_Font :: FONT_HELVETICA_BOLD

Zend_Pdf_Font :: FONT_HELVETICA_ITALIC

Zend_Pdf_Font :: FONT_HELVETICA_BOLD_ITALIC

Zend_Pdf_Font :: FONT_SYMBOL

Zend_Pdf_Font :: FONT_ZAPFDINGBATS

建立标準字型

...
// Create new font
$font = Zend_Pdf_Font::fontWithName(Zend_Pdf_Font::FONT_HELVETICA);

// Apply font
$pdfPage->setFont($font, );
...
           

您還可以使用任何單獨的TrueType字型(通常具有’.ttf’擴充名)或OpenType字型(’.otf’擴充名)。

要使用TrueType字型,必須提供字型程式的完整檔案路徑。如果由于某種原因無法讀取字型,或者它不是TrueType字型,則工廠方法将引發異常:

建立TrueType字型

...
// Create new font
$goodDogCoolFont = Zend_Pdf_Font::fontWithPath('/path/to/GOODDC__.TTF');

// Apply font
$pdfPage->setFont($goodDogCoolFont, );
...
           

預設情況下,自定義字型将嵌入到生成的PDF文檔中。這允許收件人按預期檢視頁面,即使他們的系統上沒有安裝正确的字型。如果您擔心檔案大小,可以通過将

do not embed

選項傳遞給factory方法來請求不嵌入字型程式:

如果未嵌入字型程式但PDF檔案的收件人在其系統上安裝了字型,則他們将按預期看到該文檔。如果他們沒有安裝正确的字型,PDF檢視器應用程式替換預設字型。

建立TrueType字型,但不将其嵌入PDF文檔中。

...
// Create new font
$goodDogCoolFont = Zend_Pdf_Font::fontWithPath('/path/to/GOODDC__.TTF',
                                               Zend_Pdf_Font::EMBED_DONT_EMBED);

// Apply font
$pdfPage->setFont($goodDogCoolFont, );
...
           

某些字型具有非常特定的許可規則,這些規則阻止它們嵌入PDF文檔中。是以,如果您嘗試使用無法嵌入的字型,那麼工廠方法将引發異常。如果允許最終使用者選擇自己的字型,則首選此抑制技術。

您仍然可以使用這些字型,但您必須如上所述傳遞

do not embed

标志,或者您可以簡單地抑制異常:

抑制無法嵌入的字型抛出的異常。

...
$font = Zend_Pdf_Font::fontWithPath(
           '/path/to/unEmbeddableFont.ttf',
           Zend_Pdf_Font::EMBED_SUPPRESS_EMBED_EXCEPTION
        );
...
           

字型程式可能相當大,有些可達數十兆位元組。預設情況下,使用Flate壓縮方案壓縮所有嵌入字型,平均節省50%的空間。如果由于某種原因,您不想壓縮字型程式,可以使用以下選項禁用它:

不要壓縮嵌入的字型

...
$font = Zend_Pdf_Font::fontWithPath('/path/to/someReallyBigFont.ttf',
                                    Zend_Pdf_Font::EMBED_DONT_COMPRESS);
...
           

最後,必要時,可以使用按位OR運算符組合嵌入選項:

結合字型嵌入選項

...
$font = Zend_Pdf_Font::fontWithPath(
            $someUserSelectedFontPath,
            (Zend_Pdf_Font::EMBED_SUPPRESS_EMBED_EXCEPTION |
            Zend_Pdf_Font::EMBED_DONT_COMPRESS));
...
           

Zend_Pdf使用CP1252(WinLatin1)繪制帶有标準字型的文本,Zend_Pdf文本仍然可以以任何其他編碼提供,但隻會繪制WinLatin1字元。

字元限制

...
$font = Zend_Pdf_Font::fontWithName(Zend_Pdf_Font::FONT_COURIER);
$pdfPage->setFont($font, )
        ->drawText('Euro sign - €', , , 'UTF-8')
        ->drawText('Text with umlauts - à è ì', , , 'UTF-8');
...
           

提取字型

Zend_Pdf子產品提供從加載的文檔中提取字型的可能性。

它可能對增量文檔更新很有用。如果沒有此功能,則每次要更新時都必須附加并可能将字型嵌入到文檔中。

Zend_Pdf和Zend_Pdf_Page對象提供了提取文檔或頁面中提到的所有字型的特殊方法:

例32.15。從加載的文檔中提取字型。

...
$pdf = Zend_Pdf::load($documentPath);
...
// Get all document fonts
$fontList = $pdf->extractFonts();
$pdf->pages[] = ($page = $pdf->newPage(Zend_Pdf_Page::SIZE_A4));
$yPosition = ;
foreach ($fontList as $font) {
    $page->setFont($font, );
    $fontName = $font->getFontName(Zend_Pdf_Font::NAME_POSTSCRIPT,
                                   'en',
                                   'UTF-8');
    $page->drawText($fontName . ':  The quick brown fox jumps over the lazy dog',
                    ,
                    $yPosition,
                    'UTF-8');
    $yPosition -= ;
}
...
// Get fonts referenced within the first document page
$firstPage = reset($pdf->pages);//reset()把數組指針指向第一項
$firstPageFonts = $firstPage->extractFonts();
...
           

通過指定字型名稱從加載的文檔中提取字型。

...
$pdf = new Zend_Pdf();
...
$pdf->pages[] = ($page = $pdf->newPage(Zend_Pdf_Page::SIZE_A4));

$font = Zend_Pdf_Font::fontWithPath($fontPath);
$page->setFont($font, $fontSize);
$page->drawText($text, $x, $y);
...
// This font name should be stored somewhere...
$fontName = $font->getFontName(Zend_Pdf_Font::NAME_POSTSCRIPT,
                               'en',
                               'UTF-8');
...
$pdf->save($docPath);
...
           
...
$pdf = Zend_Pdf::load($docPath);
...
$pdf->pages[] = ($page = $pdf->newPage(Zend_Pdf_Page::SIZE_A4));

/* $srcPage->extractFont($fontName) can also be used here */
$font = $pdf->extractFont($fontName);

$page->setFont($font, $fontSize);
$page->drawText($text, $x, $y);
...
$pdf->save($docPath, true /* incremental update mode */);
...
           

提取的字型可用于替代任何其他字型,但具有以下限制:

提取的字型隻能在提取它的文檔的上下文中使用。

實際上可能沒有提取嵌入字型程式。是以,提取的字型無法提供正确的字型名額,原始字型必須用于文本寬度計算:

...
$font = $pdf->extractFont($fontName);
$originalFont = Zend_Pdf_Font::fontWithPath($fontPath);

$page->setFont($font /* use extracted font for drawing */, $fontSize);
$xPosition = $x;
for ($charIndex = ; $charIndex < strlen($text); $charIndex++) {
    $page->drawText($text[$charIndex], xPosition, $y);

    // Use original font for text width calculation
    $width = $originalFont->widthForGlyph(
                 $originalFont->glyphNumberForCharacter($text[$charIndex])
             );
    $xPosition += $width/$originalFont->getUnitsPerEm()*$fontSize;
}
...
           

圖像繪制

Zend_Pdf_Page類提供

drawImage()

方法來繪制圖像:

/**
 * Draw an image at the specified position on the page.
 *
 * @param Zend_Pdf_Resource_Image $image
 * @param float $x1
 * @param float $y1
 * @param float $x2
 * @param float $y2
 * @return Zend_Pdf_Page 
 */
public function drawImage(Zend_Pdf_Resource_Image $image, $x1, $y1, $x2, $y2);
           

應使用

Zend_Pdf_Image :: imageWithPath($filePath)

方法建立圖像對象(現在支援JPG,PNG和TIFF圖像),JPEG支援需要配置PHP GD擴充,PNG支援要求将ZLIB擴充配置為使用Alpha通道圖像:

圖像繪制

...
// load image
$image = Zend_Pdf_Image::imageWithPath('my_image.jpg');

$pdfPage->drawImage($image, , , , );
...
           

線描樣式

線描樣式由線寬,線條顔色和線條劃線圖案定義。所有這些參數都可以通過Zend_Pdf_Page類方法配置設定:

/** Set line color. */
public function setLineColor(Zend_Pdf_Color $color);

/** Set line width. */
public function setLineWidth(float $width);

/**
 * Set line dashing pattern.
 *
 * Pattern is an array of floats:
 *     array(on_length, off_length, on_length, off_length, ...)
 * Phase is shift from the beginning of line.
 *
 * @param array $pattern
 * @param array $phase
 * @return Zend_Pdf_Page 
 */
public function setLineDashingPattern($pattern, $phase = );
           

填充樣式

Zend_Pdf_Page :: drawRectangle()

Zend_Pdf_Page :: drawPolygon()

Zend_Pdf_Page :: drawCircle()

Zend_Pdf_Page :: drawEllipse()

方法将

$ fillType

參數作為可選參數:

Zend_Pdf_Page :: SHAPE_DRAW_STROKE

- 描邊形狀

Zend_Pdf_Page :: SHAPE_DRAW_FILL

- 僅填充形狀

Zend_Pdf_Page :: SHAPE_DRAW_FILL_AND_STROKE

- 填充和描邊(預設行為)

Zend_Pdf_Page :: drawPolygon()

方法還需要一個額外的參數

$fillMethod

Zend_Pdf_Page :: FILL_METHOD_NON_ZERO_WINDING

(預設)

對于由五角星組成的路徑,由五個互相交叉的互相連接配接的直線段繪制,規則認為内部是由恒星包圍的整個區域,包括中心的五邊形。對于由兩個同心圓組成的路徑,兩個圓圈所包圍的區域被認為是在内部,隻要兩者都在相同的方向上繪制。如果圓圈是以相反的方向繪制的,根據規則,它們之間隻有“圓環”形狀在裡面; “甜甜圈洞”在外面。

Zend_Pdf_Page :: FILL_METHOD_EVEN_ODD

對于五角星,規則認為三角形點位于路徑内,而不是中心的五邊形。對于兩個同心圓,在内部僅考慮兩個圓之間的“圓環”形狀,而不管繪制圓的方向如何。

線性變換

1.旋轉。

在應用任何繪制操作之前,可以旋轉PDF頁面。它可以通過

Zend_Pdf_Page :: rotate()

方法完成:

/**
 * Rotate the page.
 *
 * @param float $x  - the X co-ordinate of rotation point
 * @param float $y  - the Y co-ordinate of rotation point
 * @param float $angle - rotation angle
 * @return Zend_Pdf_Page
 */
public function rotate($x, $y, $angle);
           

2.縮放。

Zend_Pdf_Page :: scale()

/**
 * Scale coordination system.
 *
 * @param float $xScale - X dimention scale factor
 * @param float $yScale - Y dimention scale factor
 * @return Zend_Pdf_Page
 */
public function scale($xScale, $yScale);
           

3.移動。

Zend_Pdf_Page :: translate()

/**
 * Translate coordination system.
 *
 * @param float $xShift - X coordinate shift
 * @param float $yShift - Y coordinate shift
 * @return Zend_Pdf_Page
 */
public function translate($xShift, $yShift);
           

4.傾斜。

Zend_Pdf_Page :: skew()

/**
 * Translate coordination system.
 *
 * @param float $x  - the X co-ordinate of axis skew point
 * @param float $y  - the Y co-ordinate of axis skew point
 * @param float $xAngle - X axis skew angle
 * @param float $yAngle - Y axis skew angle
 * @return Zend_Pdf_Page
 */
public function skew($x, $y, $xAngle, $yAngle);
           

儲存/恢複圖形狀态

在任何時候頁面圖形狀态(目前字型,字型大小,線條顔色,填充顔色,線條樣式,頁面旋轉,剪輯區域)都可以儲存然後恢複。儲存操作将資料放入圖形狀态堆棧,還原操作從那裡檢索它。

Zend_Pdf_Page類中有兩種方法可用于這些操作:

/**
 * Save the graphics state of this page.
 * This takes a snapshot of the currently applied style, position,
 * clipping area and any rotation/translation/scaling that has been
 * applied.
 *
 * @return Zend_Pdf_Page 
 */
public function saveGS();

/**
 * Restore the graphics state that was saved with the last call to
 * saveGS().
 *
 * @return Zend_Pdf_Page 
 */
public function restoreGS();
           

剪裁繪制區域

PDF和Zend_Pdf子產品支援繪制區域的剪切。Zend_Pdf_Page類為剪切操作提供了一組方法。

/**
 * Intersect current clipping area with a rectangle.
 *
 * @param float $x1
 * @param float $y1
 * @param float $x2
 * @param float $y2
 * @return Zend_Pdf_Page 
 */
public function clipRectangle($x1, $y1, $x2, $y2);


/**
 * Intersect current clipping area with a polygon.
 *
 * @param array $x  - array of float (the X co-ordinates of the vertices)
 * @param array $y  - array of float (the Y co-ordinates of the vertices)
 * @param integer $fillMethod
 * @return Zend_Pdf_Page 
 */
public function clipPolygon($x,
                            $y,
                            $fillMethod =
                                Zend_Pdf_Page::FILL_METHOD_NON_ZERO_WINDING);


/**
 * Intersect current clipping area with a circle.
 *
 * @param float $x
 * @param float $y
 * @param float $radius
 * @param float $startAngle
 * @param float $endAngle
 * @return Zend_Pdf_Page 
 */
public function clipCircle($x,
                           $y,
                           $radius,
                           $startAngle = null,
                           $endAngle = null);


/**
 * Intersect current clipping area with an ellipse.
 *
 * Method signatures:
 * drawEllipse($x1, $y1, $x2, $y2);
 * drawEllipse($x1, $y1, $x2, $y2, $startAngle, $endAngle);
 *
 * @todo process special cases with $x2-$x1 == 0 or $y2-$y1 == 0
 *
 * @param float $x1
 * @param float $y1
 * @param float $x2
 * @param float $y2
 * @param float $startAngle
 * @param float $endAngle
 * @return Zend_Pdf_Page 
 */
public function clipEllipse($x1,
                            $y1,
                            $x2,
                            $y2,
                            $startAngle = null,
                            $endAngle = null);
           

樣式

Zend_Pdf_Style類提供樣式功能。

樣式可用于存儲一組圖形狀态參數,并通過一個操作将其應用于PDF頁面:

/**
 * Set the style to use for future drawing operations on this page
 *
 * @param Zend_Pdf_Style $style
 * @return Zend_Pdf_Page 
 */
public function setStyle(Zend_Pdf_Style $style);

/**
 * Return the style, applied to the page.
 *
 * @return Zend_Pdf_Style|null
 */
public function getStyle();
           

Zend_Pdf_Style類提供了一組設定或擷取不同圖形狀态參數的方法:

/**
 * Set line color.
 *
 * @param Zend_Pdf_Color $color
 * @return Zend_Pdf_Page 
 */
public function setLineColor(Zend_Pdf_Color $color);


/**
 * Get line color.
 *
 * @return Zend_Pdf_Color|null
 */
public function getLineColor();


/**
 * Set line width.
 *
 * @param float $width
 * @return Zend_Pdf_Page 
 */
public function setLineWidth($width);


/**
 * Get line width.
 *
 * @return float
 */
public function getLineWidth();


/**
 * Set line dashing pattern
 *
 * @param array $pattern
 * @param float $phase
 * @return Zend_Pdf_Page 
 */
public function setLineDashingPattern($pattern, $phase = );


/**
 * Get line dashing pattern
 *
 * @return array
 */
public function getLineDashingPattern();


/**
 * Get line dashing phase
 *
 * @return float
 */
public function getLineDashingPhase();


/**
 * Set fill color.
 *
 * @param Zend_Pdf_Color $color
 * @return Zend_Pdf_Page 
 */
public function setFillColor(Zend_Pdf_Color $color);


/**
 * Get fill color.
 *
 * @return Zend_Pdf_Color|null
 */
public function getFillColor();


/**
 * Set current font.
 *
 * @param Zend_Pdf_Resource_Font $font
 * @param float $fontSize
 * @return Zend_Pdf_Page 
 */
public function setFont(Zend_Pdf_Resource_Font $font, $fontSize);


/**
 * Modify current font size
 *
 * @param float $fontSize
 * @return Zend_Pdf_Page 
 */
public function setFontSize($fontSize);


/**
 * Get current font.
 *
 * @return Zend_Pdf_Resource_Font $font
 */
public function getFont();


/**
 * Get current font size
 *
 * @return float $fontSize
 */
public function getFontSize();
           

32.5.15。 透明度

Zend_Pdf子產品支援透明度處理。

可以使用

Zend_Pdf_Page :: setAlpha()

方法設定透明度:

/**
 * Set the transparency
 *
 * $alpha == 0  - transparent
 * $alpha == 1  - opaque
 *
 * Transparency modes, supported by PDF:
 * Normal (default), Multiply, Screen, Overlay, Darken, Lighten,
 * ColorDodge, ColorBurn, HardLight, SoftLight, Difference, Exclusion
 *
 * @param float $alpha
 * @param string $mode
 * @throws Zend_Pdf_Exception
 * @return Zend_Pdf_Page 
 */
public function setAlpha($alpha, $mode = 'Normal');
           

Zend_Pdf子產品用法示例

此示例可以在demos / Zend / Pdf / demo.php檔案中找到。還有test.pdf檔案,可以與此示範一起用于測試目的。

/**
 * @package Zend_Pdf
 * @subpackage demo
 */

if (!isset($argv[])) {
    echo "USAGE: php demo.php <pdf_file> [<output_pdf_file>]\n";
    exit;
}

try {
    $pdf = Zend_Pdf::load($argv[]);
} catch (Zend_Pdf_Exception $e) {
    if ($e->getMessage() == 'Can not open \'' . $argv[] .
                            '\' file for reading.') {
        // Create new PDF if file doesn't exist
        $pdf = new Zend_Pdf();

        if (!isset($argv[])) {
            // force complete file rewriting (instead of updating)
            $argv[] = $argv[];
        }
    } else {
        // Throw an exception if it's not the "Can't open file
        // exception
        throw $e;
    }
}

//------------------------------------------------------------------------
// Reverse page order
$pdf->pages = array_reverse($pdf->pages);

// Create new Style
$style = new Zend_Pdf_Style();
$style->setFillColor(new Zend_Pdf_Color_Rgb(, , ));
$style->setLineColor(new Zend_Pdf_Color_GrayScale());
$style->setLineWidth();
$style->setLineDashingPattern(array(, , , ), );
$fontH = Zend_Pdf_Font::fontWithName(Zend_Pdf_Font::FONT_HELVETICA_BOLD);
$style->setFont($fontH, );

try {
    // Create new image object
    $imageFile = dirname(__FILE__) . '/stamp.jpg';
    $stampImage = Zend_Pdf_Image::imageWithPath($imageFile);
} catch (Zend_Pdf_Exception $e) {
    // Example of operating with image loading exceptions.
    if ($e->getMessage() != 'Image extension is not installed.' &&
        $e->getMessage() != 'JPG support is not configured properly.') {
        throw $e;
    }
    $stampImage = null;
}

// Mark page as modified
foreach ($pdf->pages as $page){
    $page->saveGS()
         ->setAlpha()
         ->setStyle($style)
         ->rotate(, , M_PI_2/);

    $page->saveGS();
    $page->clipCircle(, -, );
    if ($stampImage != null) {
        $page->drawImage($stampImage, , -, , );
    }
    $page->restoreGS();

    $page->drawText('Modified by Zend Framework!', , )
         ->restoreGS();
}

// Add new page generated by Zend_Pdf object
// (page is attached to the specified the document)
$pdf->pages[] = ($page1 = $pdf->newPage('A4'));

// Add new page generated by Zend_Pdf_Page object
// (page is not attached to the document)
$page2 = new Zend_Pdf_Page(Zend_Pdf_Page::SIZE_LETTER_LANDSCAPE);
$pdf->pages[] = $page2;

// Create new font
$font = Zend_Pdf_Font::fontWithName(Zend_Pdf_Font::FONT_HELVETICA);

// Apply font and draw text
$page1->setFont($font, )
      ->setFillColor(Zend_Pdf_Color_Html::color('#9999cc'))
      ->drawText('Helvetica 36 text string', , );

// Use font object for another page
$page2->setFont($font, )
      ->drawText('Helvetica 24 text string', , );

// Use another font
$fontT = Zend_Pdf_Font::fontWithName(Zend_Pdf_Font::FONT_TIMES);
$page2->setFont($fontT, )
      ->drawText('Times-Roman 32 text string', , );

// Draw rectangle
$page2->setFillColor(new Zend_Pdf_Color_GrayScale())
      ->setLineColor(new Zend_Pdf_Color_GrayScale())
      ->setLineDashingPattern(array(, , , ), )
      ->drawRectangle(, , , );

// Draw circle
$page2->setLineDashingPattern(Zend_Pdf_Page::LINE_DASHING_SOLID)
      ->setFillColor(new Zend_Pdf_Color_Rgb(, , ))
      ->drawCircle(, , );

// Draw sectors
$page2->drawCircle(, , , *M_PI/, -M_PI/)
      ->setFillColor(new Zend_Pdf_Color_Cmyk(, , , ))
      ->drawCircle(, , , M_PI/, *M_PI/)
      ->setFillColor(new Zend_Pdf_Color_Rgb(, , ))
      ->drawCircle(, , , -M_PI/, M_PI/);

// Draw ellipse
$page2->setFillColor(new Zend_Pdf_Color_Rgb(, , ))
      ->drawEllipse(, , , )
      ->setFillColor(new Zend_Pdf_Color_Cmyk(, , , ))
      ->drawEllipse(, , , , M_PI/, *M_PI/)
      ->setFillColor(new Zend_Pdf_Color_Rgb(, , ))
      ->drawEllipse(, , , , -M_PI/, M_PI/);

// Draw and fill polygon
$page2->setFillColor(new Zend_Pdf_Color_Rgb(, , ));
$x = array();
$y = array();
for ($count = ; $count < ; $count++) {
    $x[] =  + *cos(*M_PI_4*$count);
    $y[] =  + *sin(*M_PI_4*$count);
}
$page2->drawPolygon($x, $y,
                    Zend_Pdf_Page::SHAPE_DRAW_FILL_AND_STROKE,
                    Zend_Pdf_Page::FILL_METHOD_EVEN_ODD);

// ----------- Draw figures in modified coordination system --------------

// Coordination system movement
$page2->saveGS();
$page2->translate(, ); // Shift coordination system

// Draw rectangle
$page2->setFillColor(new Zend_Pdf_Color_GrayScale())
      ->setLineColor(new Zend_Pdf_Color_GrayScale())
      ->setLineDashingPattern(array(, , , ), )
      ->drawRectangle(, , , );

// Draw circle
$page2->setLineDashingPattern(Zend_Pdf_Page::LINE_DASHING_SOLID)
      ->setFillColor(new Zend_Pdf_Color_Rgb(, , ))
      ->drawCircle(, , );

// Draw sectors
$page2->drawCircle(, , , *M_PI/, -M_PI/)
      ->setFillColor(new Zend_Pdf_Color_Cmyk(, , , ))
      ->drawCircle(, , , M_PI/, *M_PI/)
      ->setFillColor(new Zend_Pdf_Color_Rgb(, , ))
      ->drawCircle(, , , -M_PI/, M_PI/);

// Draw ellipse
$page2->setFillColor(new Zend_Pdf_Color_Rgb(, , ))
      ->drawEllipse(, , , )
      ->setFillColor(new Zend_Pdf_Color_Cmyk(, , , ))
      ->drawEllipse(, , , , M_PI/, *M_PI/)
      ->setFillColor(new Zend_Pdf_Color_Rgb(, , ))
      ->drawEllipse(, , , , -M_PI/, M_PI/);

// Draw and fill polygon
$page2->setFillColor(new Zend_Pdf_Color_Rgb(, , ));
$x = array();
$y = array();
for ($count = ; $count < ; $count++) {
    $x[] =  + *cos(*M_PI_4*$count);
    $y[] =  + *sin(*M_PI_4*$count);
}
$page2->drawPolygon($x, $y,
                    Zend_Pdf_Page::SHAPE_DRAW_FILL_AND_STROKE,
                    Zend_Pdf_Page::FILL_METHOD_EVEN_ODD);

// Draw line
$page2->setLineWidth()
      ->drawLine(, , , );

$page2->restoreGS();


// Coordination system movement, skewing and scaling
$page2->saveGS();
$page2->translate(, )     // Shift coordination system
      ->skew(, , , -M_PI/) // Skew coordination system
      ->scale(, );       // Scale coordination system

// Draw rectangle
$page2->setFillColor(new Zend_Pdf_Color_GrayScale())
      ->setLineColor(new Zend_Pdf_Color_GrayScale())
      ->setLineDashingPattern(array(, , , ), )
      ->drawRectangle(, , , );

// Draw circle
$page2->setLineDashingPattern(Zend_Pdf_Page::LINE_DASHING_SOLID)
      ->setFillColor(new Zend_Pdf_Color_Rgb(, , ))
      ->drawCircle(, , );

// Draw sectors
$page2->drawCircle(, , , *M_PI/, -M_PI/)
      ->setFillColor(new Zend_Pdf_Color_Cmyk(, , , ))
      ->drawCircle(, , , M_PI/, *M_PI/)
      ->setFillColor(new Zend_Pdf_Color_Rgb(, , ))
      ->drawCircle(, , , -M_PI/, M_PI/);

// Draw ellipse
$page2->setFillColor(new Zend_Pdf_Color_Rgb(, , ))
      ->drawEllipse(, , , )
      ->setFillColor(new Zend_Pdf_Color_Cmyk(, , , ))
      ->drawEllipse(, , , , M_PI/, *M_PI/)
      ->setFillColor(new Zend_Pdf_Color_Rgb(, , ))
      ->drawEllipse(, , , , -M_PI/, M_PI/);

// Draw and fill polygon
$page2->setFillColor(new Zend_Pdf_Color_Rgb(, , ));
$x = array();
$y = array();
for ($count = ; $count < ; $count++) {
    $x[] =  + *cos(*M_PI_4*$count);
    $y[] =  + *sin(*M_PI_4*$count);
}
$page2->drawPolygon($x, $y,
                    Zend_Pdf_Page::SHAPE_DRAW_FILL_AND_STROKE,
                    Zend_Pdf_Page::FILL_METHOD_EVEN_ODD);

// Draw line
$page2->setLineWidth()
      ->drawLine(, , , );

$page2->restoreGS();

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

if (isset($argv[])) {
    $pdf->save($argv[]);
} else {
    $pdf->save($argv[], true /* update */);
}