PHP: pdf 関数 - Manual
PHP  
downloads | documentation | faq | getting help | mailing lists | | php.net sites | links | my php.net 
search for in the  
<parsekit_func_arginfopdf_add_annotation>
view the version of this page
Last updated: Tue, 21 Dec 2004

LXXXVIII. pdf 関数

導入

PHPのPDF関数は、により作成されたPDFlibライブラリを使用してPDFファイル を作成することが可能です。

本節のドキュメントは、PDFlibライブラリで利用可能な関数の概要のみ を説明することを意図しています。ここで扱う各関すの完全で詳細な説 明については、PDFlibのソース配布ファイルと共に配布されているドキュ メントを参照下さい。このドキュメントは、PDFlib の機能に関 する概要を非常に良くまとめており、全ての関数に関する最新のドキュ メントが含まれています。

PDFlibのほとんどの関数とPHPモジュール内の関数の名前とパラメータは 共通になっています。このモジュールを効率的に使用するには、PDFまた はPostScriptに関する基本的な考え方も理解しておく必要があります。 全ての長さと座標は、Postscriptのポイント数で計られます。通常、1イ ンチ当たり72 Postscript ポイントですが、これは、出力解像度に依存 します。使用する座表系に関するより詳細な説明については、PDFlibの ソース配布に含まれるPDFlibドキュメントを参照下さい。

ほとんど全てのPDF関数は、最初の引数パラメータとして pdf object を必要とすることに注意して下さ い。より詳細な情報については以下の例を参照下さい。

要件

PDFlibは、 でダウンロード 可能ですが、商用で使用する場合はライセンスを購入する必要がありま す。この拡張モジュールをコンパイルするには、および が必要です。

古いバージョンのPDFlibに関する問題

2000年3月9日以降のバージョンのPHPでは、3.0より古いバージョンの PDFlibをサポートしていません。

PDFlib 3.0以降が、PHP 3.0.19以降でサポートされています。

インストール手順

以下の関数が動作するようにするには、 --with-pdflib[=DIR]を指定してPHPを コンパイルする必要があります。DIRはPDFlibのベースインストールディレ クトリで、デフォルトは/usr/localです。 さらに、PDFlibでjpeg, tiff, pngライブラリを使用することを指定できま す。これは、PDFlib 4.xではオプションです。 これを行うには、configureにオプション --with-jpeg-dir[=DIR] --with-png-dir[=DIR] --with-tiff-dir[=DIR]を追加します。

バージョン3.xのPDFlibを使用する場合、PDFlibのconfigureのオプションに --enable-shared-pdflibを指定する必要があります。

実行用の設定

この拡張モジュールは設定ディレクティブを全く定義しません。

古いバージョンのPDFlibとの混乱

PHP v4.0.5以降、PHPlib用のPHP拡張モジュールは、PDFlib GmbH から正 式にサポートされています。これにより、PDFlibマニュアル(バージョン 3.00以降)に記述された全ての関数がPHP4で全く同じ意味、同じパラメー タでサポートされています。返り値のみは、エラーの場合に FALSEを返すというPHPの流儀に合わせるために PDFlibマニュアルと異なっていることがあります。互換性を保つために PDFlibサポート関数ではまだ古い関数もサポートしていますが、上記の ように新しいバージョンに置換される予定です。PDFlib GmbH は、これら の古い関数を使用した場合に生じた際に生じた問題に関してはサポートを 行いません。

表 1. 古い関数と代替関数

古い関数代替関数
pdf_put_image()もう不要です。
pdf_execute_image()もう不要です。
pdf_get_annotation() 同じパラメータでpdf_get_bookmark()を使用。
pdf_get_font() pdf_get_value() に2番目のパラメータとして "font"を渡す。
pdf_get_fontsize() pdf_get_value() に2番目のパラメータとして "fontsize"を渡す。
pdf_get_fontname() pdf_get_parameter()に2番目のパラメータとして "fontname" を渡す。
pdf_set_info_creator() pdf_set_info()に2番目のパラメータとして "Creator"を渡す。
pdf_set_info_title() pdf_set_info()に2番目のパラメータとして "Title"を渡す。
pdf_set_info_subject() pdf_set_info()に2番目のパラメータとして "Subject"を渡す。
pdf_set_info_author() pdf_set_info()に2番目のパラメータとして "Author"を渡す。
pdf_set_info_keywords() pdf_set_info()に2番目のパラメータとして "Keywords"を渡す。
pdf_set_leading() pdf_set_value()に2番目のパラメータとして "leading"を渡す。
pdf_set_text_rendering() pdf_set_value()に2番目のパラメータとして "textrendering"を渡す。
pdf_set_text_rise() pdf_set_value()に2番目のパラメータとして "textrise"を渡す。
pdf_set_horiz_scaling() pdf_set_value()に2番目のパラメータとして "horizscaling"を渡す。
pdf_set_text_matrix()もう使用できません。
pdf_set_char_spacing() pdf_set_value()に2番目のパラメータとして "charspacing"を渡す。
pdf_set_word_spacing() pdf_set_value()に2番目のパラメータとして "wordspacing"を渡す。
pdf_set_transition() pdf_set_parameter()に2番目のパラメータとして "transition"を渡す。
pdf_open() pdf_new()の後に pdf_open_file()をコールする。
pdf_set_font() pdf_findfont()の後に pdf_setfont()をコールする。
pdf_set_duration() pdf_set_value()に2番目のパラメータとして "duration"を渡す。
pdf_open_gif() pdf_open_image_file()に2番目のパラメータとして "gif" を渡す。
pdf_open_jpeg() pdf_open_image_file()に2番目のパラメータとして "jpeg" を渡す。
pdf_open_tiff() pdf_open_image_file()に2番目のパラメータとして "tiff" を渡す。
pdf_open_png() pdf_open_image_file()に2番目のパラメータとして "png" を渡す。
pdf_get_image_width() pdf_get_value()に2番目のパラメータとして "imagewidth"、3番目のパラメータとして imageを渡す。
pdf_get_image_height() pdf_get_value()に2番目のパラメータとして "imageheight"、3番目のパラメータとして imageを渡す。

多くの関数の使用法は簡単です。最も困難なのは、非常に簡単なpdfドキュ メントを作成する場合でしょう。次の例は、入門の際の助けとなるはず です。この例では、1ページを有するファイル test.pdfが作成されます。このページには、30ポ イントのアウトラインフォントでテキスト"Times-Roman outlined"が描 かれます。このテキストには、下線も引かれます。

例 1. PDFlibでPDFドキュメントを作成する

<?php
$pdf
= pdf_new();
pdf_open_file($pdf, "test.pdf");
pdf_set_info($pdf, "Author", "Uwe Steinmann");
pdf_set_info($pdf, "Title", "Test for PHP wrapper of PDFlib 2.0");
pdf_set_info($pdf, "Creator", "See Author");
pdf_set_info($pdf, "Subject", "Testing");
pdf_begin_page($pdf, 595, 842);
pdf_add_outline($pdf, "Page 1");
pdf_set_font($pdf, "Times-Roman", 30, "host");
pdf_set_value($pdf, "textrendering", 1);
pdf_show_xy($pdf, "Times Roman outlined", 50, 750);
pdf_moveto($pdf, 50, 740);
pdf_lineto($pdf, 330, 740);
pdf_stroke($pdf);
pdf_end_page($pdf);
pdf_close($pdf);
pdf_delete($pdf);
echo
"<A HREF=getpdf.php>完了しました</A>";
?>

以下のスクリプトgetpdf.phpは、PDFドキュメ ントを返すだけのものです。

<?php
$len = filesize($filename);
header("Content-type: application/pdf");
header("Content-Length: $len");
header("Content-Disposition: inline; filename=foo.pdf");
readfile($filename);
?>

PDFlibの配布ファイルには、アナログクロックで本格的なページを作成す るより複雑な例が含まれています。ここでは、PDFlibのメモリ内作成機 能を使用しており、このため、テンポラリファイルは不要です。この例 をPHPからPDFlibを使用するように変換すると以下のようになります。 (CLibPDFモジュール)のドキュメント にも同じ例があります。)

例 2. PDFlib配布ファイル中の pdfclockの例

<?php
$radius = 200;
$margin = 20;
$pagecount = 10;

$pdf = pdf_new();

if (!pdf_open_file($pdf, "")) {
    print error;
    exit;
};

pdf_set_parameter($pdf, "warning", "true");

pdf_set_info($pdf, "Creator", "pdf_clock.php");
pdf_set_info($pdf, "Author", "Uwe Steinmann");
pdf_set_info($pdf, "Title", "Analog Clock");

while($pagecount-- > 0) {
    pdf_begin_page($pdf, 2 * ($radius + $margin), 2 * ($radius + $margin));

    pdf_set_parameter($pdf, "transition", "wipe");
    pdf_set_value($pdf, "duration", 0.5);
  
    pdf_translate($pdf, $radius + $margin, $radius + $margin);
    pdf_save($pdf);
    pdf_setrgbcolor($pdf, 0.0, 0.0, 1.0);

    /* 1分刻みの目盛 */
    pdf_setlinewidth($pdf, 2.0);
    for ($alpha = 0; $alpha < 360; $alpha += 6) {
        pdf_rotate($pdf, 6.0);
        pdf_moveto($pdf, $radius, 0.0);
        pdf_lineto($pdf, $radius-$margin/3, 0.0);
        pdf_stroke($pdf);
    }

    pdf_restore($pdf);
    pdf_save($pdf);

    /* 5分刻みの目盛 */
    pdf_setlinewidth($pdf, 3.0);
    for ($alpha = 0; $alpha < 360; $alpha += 30) { 
        pdf_rotate($pdf, 30.0);
        pdf_moveto($pdf, $radius, 0.0);
        pdf_lineto($pdf, $radius-$margin, 0.0);
        pdf_stroke($pdf);
    }

    $ltime = getdate();

    /* 時針を描画 */
    pdf_save($pdf);
    pdf_rotate($pdf,-(($ltime['minutes']/60.0)+$ltime['hours']-3.0)*30.0);
    pdf_moveto($pdf, -$radius/10, -$radius/20);
    pdf_lineto($pdf, $radius/2, 0.0);
    pdf_lineto($pdf, -$radius/10, $radius/20);
    pdf_closepath($pdf);
    pdf_fill($pdf);
    pdf_restore($pdf);

    /* 分針を描画 */
    pdf_save($pdf);
    pdf_rotate($pdf,-(($ltime['seconds']/60.0)+$ltime['minutes']-15.0)*6.0);
    pdf_moveto($pdf, -$radius/10, -$radius/20);
    pdf_lineto($pdf, $radius * 0.8, 0.0);
    pdf_lineto($pdf, -$radius/10, $radius/20);
    pdf_closepath($pdf);
    pdf_fill($pdf);
    pdf_restore($pdf);

    /* 秒針を描画 */
    pdf_setrgbcolor($pdf, 1.0, 0.0, 0.0);
    pdf_setlinewidth($pdf, 2);
    pdf_save($pdf);
    pdf_rotate($pdf, -(($ltime['seconds'] - 15.0) * 6.0));
    pdf_moveto($pdf, -$radius/5, 0.0);
    pdf_lineto($pdf, $radius, 0.0);
    pdf_stroke($pdf);
    pdf_restore($pdf);

    /* 中心に小さな円を描画 */
    pdf_circle($pdf, 0, 0, $radius/30);
    pdf_fill($pdf);

    pdf_restore($pdf);

    pdf_end_page($pdf);

    /* 変化を見るために待つ */
    sleep(1);
}

pdf_close($pdf);

$buf = pdf_get_buffer($pdf);
$len = strlen($buf);

header("Content-type: application/pdf");
header("Content-Length: $len");
header("Content-Disposition: inline; filename=foo.pdf");
print $buf;

pdf_delete($pdf);
?>

以下も参照下さい

注意: PDFドキュメントを作成するための別のPHPモジュールとして ClibPDFが利用可能です。 詳細については、ClibPDFの節を参 照下さい。ClibPDF はPDFlibとはや や異なるAPIを使用していることに注意して下さい。

目次
pdf_add_annotation -- 古い関数: 注記を追加する
pdf_add_bookmark -- ブックマークをカレントのページに追加する
pdf_add_launchlink -- カレントのページに起動用注記を追加する
pdf_add_locallink -- カレントのページにリンク注記を追加
pdf_add_note -- カレントのページに注記を追加する
pdf_add_outline -- 古い関数: カレントのページにブックマークを追加する
pdf_add_pdflink -- カレントページにリンク注記を追加
pdf_add_thumbnail -- カレントのページにサムネールを追加する
pdf_add_weblink -- カレントのページにWebリンクを追加する
pdf_arc -- (反時計回りに)円弧を描く
pdf_arcn -- (時計回りに)円弧を描く
pdf_attach_file -- カレントのページに添付ファイルを追加する
pdf_begin_page -- 新規ページを開始する
pdf_begin_pattern -- 新規パターンを開始する
pdf_begin_template -- 新規テンプレートを開始する
pdf_circle -- 円を描く
pdf_clip -- カレントのパスに切り取る
pdf_close_image -- 画像を閉じる
pdf_close_pdi_page --  ページハンドルを閉じる
pdf_close_pdi --  PDFドキュメント入力(PDI)を閉じる
pdf_close -- pdf ドキュメントを閉じる
pdf_closepath_fill_stroke -- カレントのパスを閉じ、塗りつぶし、輪郭を描く
pdf_closepath_stroke -- パスを閉じ、パスに沿って線を描く
pdf_closepath -- パスを閉じる
pdf_concat -- 行列をCTMに追加
pdf_continue_text -- 次の行にテキストを出力する
pdf_curveto -- 曲線を描く
pdf_delete -- PDFオブジェクトを削除
pdf_end_page -- ページを終了する
pdf_end_pattern -- パターンを終了する
pdf_end_template -- テンプレートを終了する
pdf_endpath -- 古い関数: カレントのパスを終了する
pdf_fill_stroke -- カレントのパスを塗りつぶし、パスの輪郭を描く
pdf_fill -- カレントのパスを塗りつぶす
pdf_findfont --  後でpdf_setfont()で使用するフォントを準備する
pdf_get_buffer --  生成されたPDFデータを含むバッファを取得する
pdf_get_font -- 古い関数: フォント処理
pdf_get_fontname -- 古い関数: フォント処理
pdf_get_fontsize -- 古い関数: フォント処理
pdf_get_image_height -- 古い関数: イメージの高さを返す
pdf_get_image_width -- 古い関数: イメージの幅を返す
pdf_get_majorversion --  PDFlibのメジャーバージョン番号を返す
pdf_get_minorversion --  PDFlibのマイナーバージョン番号を返す
pdf_get_parameter -- パラメータを得る
pdf_get_pdi_parameter -- PDF文字列パラメータを得る
pdf_get_pdi_value -- 数値型のPDIパラメータを取得する
pdf_get_value -- 数値を得る
pdf_initgraphics -- 描画状態をリセットする
pdf_lineto -- 線を描く
pdf_makespotcolor -- スポット色を作成する
pdf_moveto -- 現在の位置を設定する
pdf_new -- 新規PDFオブジェクトを作成する
pdf_open_CCITT --  生のCCITTデータから新規イメージファイルをオープンする
pdf_open_file -- 新規PDFオブジェクトをオープンする
pdf_open_gif -- 古い関数: GIFイメージをオープンする
pdf_open_image_file -- ファイルからイメージを読み込む
pdf_open_image -- イメージ読み込み関数
pdf_open_jpeg -- 古い関数: JPEGイメージをオープンする
pdf_open_memory_image --  PHPのイメージ関数で作成されたイメージをオープンする
pdf_open_pdi_page -- ページを準備する
pdf_open_pdi -- PDFファイルをオープンする
pdf_open_png --  古い関数: PNGイメージをオープンする
pdf_open_tiff -- 古い関数: TIFFイメージをオープンする
pdf_open -- 古い関数: 新規の pdfオブジェクトをオープンする
pdf_place_image -- イメージをページ上に置く
pdf_place_pdi_page -- ページにイメージを置く
pdf_rect -- 長方形を描く
pdf_restore -- 以前保存された環境を復元する
pdf_rotate -- 回転を設定する
pdf_save -- 現在の環境を保存する
pdf_scale -- スケールを設定する
pdf_set_border_color -- リンクや注記の周りの境界色を設定する
pdf_set_border_dash -- リンクおよび注記の周りの境界の破線形式を設定する
pdf_set_border_style --  リンクおよび注記の周りの境界の形式を設定する
pdf_set_char_spacing -- 古い関数: 文字間隔を設定する
pdf_set_duration -- 古い関数: ページ間隔を設定
pdf_set_font -- 古い関数: フォントの形式とサイズを選択
pdf_set_horiz_scaling -- 古い関数: テキストの横方向倍率を設定
pdf_set_info_author --  ドキュメントのauthorフィールドを設定する
pdf_set_info_creator --  ドキュメントのcreatorフィールドを設定する
pdf_set_info_keywords --  ドキュメントのkeywordフィールドを設定する
pdf_set_info_subject --  ドキュメントのsubjectフィールドを設定する
pdf_set_info_title --  ドキュメントのtitleフィールドを設定する
pdf_set_info -- ドキュメント情報のフィールドを設定する
pdf_set_leading -- 古い関数: テキストの行間を設定する
pdf_set_parameter -- パラメータを設定する
pdf_set_text_matrix -- Deprecated: Sets the text matrix
pdf_set_text_pos -- テキストの位置を設定する
pdf_set_text_rendering -- 古い関数: テキストの描画方法を設定
pdf_set_text_rise -- 古い関数: テキストの傾きを設定する
pdf_set_value -- 数値を設定する
pdf_set_word_spacing -- 古い関数: 単語間の空白を設定する
pdf_setcolor -- 塗りつぶし色および輪郭色を設定する
pdf_setdash -- 破線パターンを設定する
pdf_setflat -- 平面度を設定する
pdf_setfont -- カレントのフォントを設定する
pdf_setgray_fill -- 塗りつぶし色をグレー値に設定する
pdf_setgray_stroke -- 描画色をグレー値に設定する
pdf_setgray -- 描画および塗りつぶし色をグレー値に設定する
pdf_setlinecap -- linecap パラメータを設定する
pdf_setlinejoin -- linejoinパラメータを設定する
pdf_setlinewidth -- 線幅を設定する
pdf_setmatrix -- カレントの変換行列を設定する
pdf_setmiterlimit -- miter limitを設定する
pdf_setpolydash -- 複雑な破線パターンを設定
pdf_setrgbcolor_fill -- 塗りつぶし色をRGBカラー値に設定する
pdf_setrgbcolor_stroke -- 描画色をRGBカラー値に設定する
pdf_setrgbcolor -- 描画色および塗りつぶし色をRGBカラー値で設定する
pdf_show_boxed -- ボックスにテキストを出力する
pdf_show_xy -- 指定した位置にテキストを出力する
pdf_show -- カレントの位置にテキストを出力する
pdf_skew -- 座標系を歪ませる
pdf_stringwidth -- カレントフォントを用いた際のテキスト幅を返す
pdf_stroke -- パスに沿って線を描く
pdf_translate -- 座標系の原点を設定する


add a note add a note User Contributed Notes
pdf 関数
chu61 dot tw at gmail dot com
07-Mar-2005 03:57
How to get how many pages in a PDF? I read PDF spec. V1.6 and find this:

PDF set  a "Page Tree Node" to define the ordering of pages in the document. The tree structure allows PDF applications, using little memory to quickly open a document containing thousands of pages.

If a PDF have 63 pages, the page tree node will like this...

2 0 obj
<< /Type /Pages
   /Kidsn [ 4 0 R
               10 0 R
             ]
     /Count 63        <---- YES, got it
>>
endobj

[P.S]  a  PDF may not only a pages tree node, The right answer is in "root page tree node", if  /Count XX with  /Parent XXX node, it not "root page tree node"

SO, You must find the node with /Count XX and Without /Parent  terms, and you'll get total pages of PDF

%PDF-1.0  ~  %PDF-1.5 all works

Alex form Taipei,Taiwan
mattb at bluewebstudios dot com
04-Feb-2005 09:44
I recently tested Donatas' code below for the extraction of text from PDF files.  After running into a few problems where PDF files were not being read at all, I've modified it somewhat.  It still isn't perfect, but should work great for searching.  Thanks Donatas.

<?php
$test
= pdf2string("<pathtoPDFfile>");
echo
"$test";

# Returns a -1 if uncompression failed
function pdf2string($sourcefile)
{
  
$fp = fopen($sourcefile, 'rb');
  
$content = fread($fp, filesize($sourcefile));
  
fclose($fp);

  
# Locate all text hidden within the stream and endstream tags
  
$searchstart = 'stream';
  
$searchend = 'endstream';
  
$pdfdocument = "";

  
$pos = 0;
  
$pos2 = 0;
  
$startpos = 0;
  
# Iterate through each stream block
  
while( $pos !== false && $pos2 !== false )
   {
    
# Grab beginning and end tag locations if they have not yet been parsed
    
$pos = strpos($content, $searchstart, $startpos);
    
$pos2 = strpos($content, $searchend, $startpos + 1);
     if(
$pos !== false && $pos2 !== false )
     {
        
# Extract compressed text from between stream tags and uncompress
        
$textsection = substr($content, $pos + strlen($searchstart) + 2, $pos2 - $pos - strlen($searchstart) - 1);
        
$data = @gzuncompress($textsection);
        
# Clean up text via a special function
        
$data = ExtractText($data);
        
# Increase our PDF pointer past the section we just read
        
$startpos = $pos2 + strlen($searchend) - 1;
         if(
$data === false ) { return -1; }
        
$pdfdocument = $pdfdocument . $data;
     }
   }

   return
$pdfdocument;
}

function
ExtractText($postScriptData)
{
   while( ((
$textStart = strpos($postScriptData, '(', $textStart)) && ($textEnd = strpos($postScriptData, ')', $textStart + 1)) && substr($postScriptData, $textEnd - 1) != '\\') )
   {
    
$plainText .= substr($postScriptData, $textStart + 1, $textEnd - $textStart - 1);
     if(
substr($postScriptData, $textEnd + 1, 1) == ']' ) // This adds quite some additional spaces between the words
    
{
        
$plainText .= ' ';
     }

    
$textStart = $textStart < $textEnd ? $textEnd : $textStart + 1;
   }

   return
stripslashes($plainText);
}
?>
ken at thesmallbox.com
30-Oct-2004 03:13
Please note that these functions have been removed from PHP 5. They are still available through the pdflib PECL module.
13-Aug-2004 06:58
for people who are using PDF_FINDFONT there is a catch..
--------------------------------------------------------

int PDF_findfont(PDF *p, const char *fontname, const char *encoding, int embed)

Deprecated, use PDF_load_font( ).

----
use PDF_load_font instead....
arjen at queek dot nl
15-Jul-2004 02:50
If you prefer a OO-approach to the PDF-functions, you can use this snippet of code (PHP5 only! and does add some overhead). It's just a "start-up", extend/improve as you wish...
You can pass all pdf_* functions to your object and stripping pdf_ of the function name. Plus, you don't have to pass the pdf-resource as the first argument.

For example:
<?php
pdf_show
($pdf, $text);    // Where $pdf is your pdf-resource
?>

Can become:
<?php
$pdf
->show($text);        // Where $pdf is your PDF-object
?>

Code:
<?php

class PDF {

  
private $pdf;
  
  
/* public Void __construct(): Constructor */
  
public function __construct() {
      
$this->pdf = pdf_new();
   }
  
  
/* public Mixed __call(): Re-route all function calls to the PHP-functions */
  
public function __call($function, $arguments) {
      
// Prepend the pdf resource to the arguments array
      
array_unshift($arguments, $this->pdf);
      
      
// Call the PHP function
      
return call_user_func_array('pdf_' . $function, $arguments);
   }

}

?>
michi (Alt+Q) marel.at
01-Jul-2004 02:10
<?PHP
/* A little helpful function to calculate millimeters to points */
function calcToPt($intMillimeter) {
 
$intPoints = ($intMillimeter*72)/25.4;
 
$intPoints = round($intPoints);
  return
$intPoints;
}

/* For example: Create DIN A4 210x297 mm */
pdf_begin_page( $pdf, calcToPt(210), calcToPt(297)); // 595x842 pt
?>
donatas at spurgius dot com
22-Jun-2004 07:56
I've been looking for a way to extract plain text from PDF documents (needed to search for text inside 'em). Not being able to find one I wrote the needed functions myself. here you go folks.

<?php
 
function pdf2string ($sourceFile)
  {
  
$textArray = array ();
  
$objStart = 0;
  
  
$fp = fopen ($sourceFile, 'rb');
  
$content = fread ($fp, filesize ($sourceFile));
  
fclose ($fp);
  
  
$searchTagStart = chr(13).chr(10).'stream';
  
$searchTagStartLenght = strlen ($searchTagStart);
  
   while (((
$objStart = strpos ($content, $searchTagStart, $objStart)) && ($objEnd = strpos ($content, 'endstream', $objStart+1))))
   {
    
$data = substr ($content, $objStart + $searchTagStartLenght + 2, $objEnd - ($objStart + $searchTagStartLenght) - 2);
    
$data = @gzuncompress ($data);
    
     if (
$data !== FALSE && strpos ($data, 'BT') !== FALSE && strpos ($data, 'ET') !== FALSE)
     {
      
$textArray [] = ExtractText ($data);
     }
    
    
$objStart = $objStart < $objEnd ? $objEnd : $objStart + 1;
   }
  
   return
$textArray;
  }
 
  function
ExtractText ($postScriptData)
  {
   while (((
$textStart = strpos ($postScriptData, '(', $textStart)) && ($textEnd = strpos ($postScriptData, ')', $textStart + 1)) && substr ($postScriptData, $textEnd - 1) != '\\'))
   {
    
$plainText .= substr ($postScriptData, $textStart + 1, $textEnd - $textStart - 1);
     if (
substr ($postScriptData, $textEnd + 1, 1) == ']') //this adds quite some additional spaces between the words
    
{
      
$plainText .= ' ';
     }
    
    
$textStart = $textStart < $textEnd ? $textEnd : $textStart + 1;
   }
  
   return
stripslashes ($plainText);
  }
?>
uwe at steinmann dot cx
13-May-2004 01:25
Those looking for a free replacement of pdflib may consider
pslib at which produces PostScript but it can be easily turned into PDF by Acrobat Distiller or ghostscript. The API is very similar and even hypertext functions are supported. There
is also a php extension for pslib in PECL, called ps.
samcontact at myteks dot com
01-May-2004 11:28
Here is another great tutorial on basic PDF building w/ PHP:


=======================

Computer Repair & Web Design
=======================
james at lanpad dot org
19-Apr-2004 03:36
PDFLib has a free replacement, that also is much easier to work with too (no more working with co-ordinates from the bottom left hand corner!)!



Its also free for commercial use, and is very useable, unlike the PDFlib extensions.
kristian at ruazgo dot com
11-Mar-2004 10:32
If you want an opensource class for creating PDF-files, you can find it at :
matic at koncan dot net
12-Jan-2004 02:22
The solution for IE (refresh):
...
$buf = PDF_get_buffer($p);
$len = strlen($buf);
header("Cache-Control: no-store");
header("Cache-Control: no-cache");
header("Cache-Control: must-revalidate");
header("Content-type: application/pdf");
header("Content-Length: $len");
header("Content-Disposition: inline; filename=file.pdf");
print $buf;
PDF_delete($p);
SenorTZ senortz at nospam dot yahoo dot com
28-Jul-2003 01:23
About creating a PDF document based on the content of another document(let's say a text file):

I have tried to send to the PDF-creator page from a link from the sender page the file name of the file I want to read the content from and generate the PDF document containing this content. The idea is is that when I tried to reffer the pdf-creator page via the link your_root/create_pdf.php?filename=$your_file_name, the pdf-creator page does not behave well when before creating the pdf document I have a line like $filename = $_GET["filename"].
I solved this using on the sender page instead of the link a form with a button, so the form has as action "create_pdf.php", as method "post" and a hidden field containing the "filename" value. And it works like this if, on the pdf-creator page I have a line like $filename = $_POST["filename"].

I would like to understand why this way it works and the other way does not.

I hope this helps. Here are the pieces of code I used.

Sender page:
print("<form name='to_pdf' action='see_pdf_file.php' method='post'>");
print("<br/><input type='submit' value='PDF'><input type='hidden' name='filename' value='$filename'></form>");

PDF-creator page:
<?
$filename
= $_POST["filename"];
$file_handle = fopen($filename, "r");
$file_content = file_get_contents($filename);
fclose($file_handle);
//
$file_content = wordwrap($file_content,72,"|");
$a_row = explode("|",$file_content);
$i = 0;
//
$pdf = pdf_new();
pdf_open_file($pdf, "");
pdf_begin_page($pdf, 595, 842);
pdf_set_font($pdf, "Times-Roman", 16, "host");
pdf_add_outline($pdf, "Page 1");
pdf_set_value($pdf, "textrendering", 1);
pdf_show_xy($pdf, 'The content of the file:',50,700);
while (
$a_row[$i] != "")
{
      
pdf_continue_text($pdf,$a_row[$i]);
      
$i++;
}
pdf_end_page($pdf);
pdf_close($pdf);
//
$data = pdf_get_buffer($pdf);
//
header("Content-type: application/pdf");
header("Content-disposition: inline; filename=test.pdf");
header("Content-length: " . strlen($data));
//
echo $data;
?>

PDFLib and PHP 431 used.

Thanks.
bmironov at jonview dot com
24-Jun-2003 10:46
RedHat 9 + Apache 2.0 + PHP 4.3.2 + Oracle 9i + PDFlib 5.0.1 (binary distribution)

It seems to be a working bundle if you do some magic with ./configure:

RedHat 9:
kernel-2.4.20-18.9

Apache 2.0.46:
./configure --enable-so --enable-rewrite=shared --enable-status --enable-mpm=prefork

PHP 4.3.2:
./configure \
--program-prefix= \
--prefix=/usr \
--exec-prefix=/usr \
--bindir=/usr/bin \
--sbindir=/usr/sbin \
--sysconfdir=/etc \
--datadir=/usr/share \
--includedir=/usr/include \
--libdir=/usr/lib \
--libexecdir=/usr/libexec \
--localstatedir=/var \
--sharedstatedir=/usr/com \
--mandir=/usr/share/man \
--infodir=/usr/share/info \
--with-config-file-path=/etc \
--with-config-file-scan-dir=/etc/php.d \
--without-tsrm-pthreads \    # !!!!!!!!!!!!!!!!!!!!
--with-zlib \
--with-gd \
--enable-gd-native-ttf \
--with-ttf \
--without-mysql \
--with-apxs2filter=/usr/local/apache2/bin/apxs \
--with-oci8 \
--enable-sigchild \
--enable-inline-optimization

Oracle9i:
ln -s $ORACLE_HOME/rdbms/public/nzerror.h $ORACLE_HOME/rdbms/demo/nzerror.h

ln -s $ORACLE_HOME/rdbms/public/nzt.h $ORACLE_HOME/rdbms/demo/nzt.h

ln -s $ORACLE_HOME/rdbms/public/ociextp.h $ORACLE_HOME/rdbms/demo/ociextp.h

If you want to use bundled GD-library then:
1) install following packages: libjpeg, libjpeg-devel, libpng, libpng-devel, freetype, freetype-devel, libtiff, libtiff-devel, zlib, zlib-devel

2) ln -s /usr/lib/libjpeg.so.62 /usr/lib/libjpeg.so
ln -s /usr/lib/libpng.so.62 /usr/lib/libpng.so

It seems to be a working combination, because it is NOT give you:
1) error message in Apache's error_log:
Module compiled with module API=20020429, debug=0, thread-safety=0
PHP compiled with module API=20020429, debug=0, thread-safety=1

2) error message in Apache's error_log:
[notice] child pid 12345 exit signal Segmentation fault (11)

3) MS Internet Explorer can show PDF-output from your PHP-script via Acrobat plug-in and does not crush. No confusing messages about opening "Adobe Acrobat Control for ActiveX".

Hope it will save you some time.

Good luck,
Boris
matt at nospam dot org
29-Aug-2002 06:11
Adding to my prior note, IE 6 has a strange feature of using GET when refreshing a pdf document, even though the page was originally POSTed to.  This may be the root cause of all the trouble listed above regarding posting and pdf. 

So, I recommend:
1) using a two page form/action handler when doing pdf rendering instead of the standard $PHP_SELF form/self handler to resolve the problem discussed above
2) Using either GET, or a self posting form that sets cookies and then redirects to the pdf creation page instead of POST, so that the parms get to the page.  HTH
gilbertng at hongkong dot com
11-Jun-2002 10:23
Hope it can help someone:

   $pdf = pdf_new();
   //pdf_open_file($pdf,"");
   if (!pdf_open_file($pdf, "")) {
           print error;
           exit;   
   }
  

             PDF_set_parameter($pdf, "resourcefile", "/usr/local/pdflib/fonts/pdflib.upr");
   PDF_set_parameter($pdf,"prefix","/usr/local/pdflib/fonts");

   pdf_begin_page($pdf, 595, 842);
   pdf_add_outline($pdf, "Page 1");

   //pdf_set_font($pdf, "Times-Roman", 30, "host");
             // set chinese characters,
   $font = pdf_findfont($pdf, "MHei-Medium", "B5pc-H",0);
   if ($font) {
       pdf_setfont($pdf, $font, 30);
   }   

   pdf_set_value($pdf, "textrendering",0);
   pdf_show_xy($pdf, "���� 100 Roman outlined", 50, 750);

   pdf_set_font($pdf, "Times-Roman", 30, "host");
   pdf_show_xy($pdf, "���� Times Roman outlined", 50, 600);
   pdf_moveto($pdf, 50, 740);
   pdf_lineto($pdf, 330, 740);
   pdf_stroke($pdf);
   pdf_end_page($pdf);
   pdf_close($pdf);

   $buf = pdf_get_buffer($pdf);
   $len = strlen($buf);

   header("Content-type: application/pdf");
   header("Content-Length: $len");
   header("Content-Disposition: inline; filename=foo.pdf");
   print $buf;

   pdf_delete($pdf);
chernyshevsky at hotmail dot com
06-May-2002 10:22
If you're wondering how to highlight words inside a PDF file, take a look at this script I've written (doesn't need PDFLib)



It's a whole lot harder than you think. (Rarely has no much code been written that does so little, that's what I say :-) Worth looking at if you want to do searches inside a PDF.
pbierans at lynet dot de
27-Mar-2002 05:56
Load extension, open a PDF, add a font, modify PDF in memory and send
it to browser:

<?php
 
// no cache headers:
 
header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
 
header("Last-Modified: ".gmdate("D, d M Y H:i:s")." GMT");
 
header("Cache-Control: no-store, no-cache, must-revalidate");
 
header("Cache-Control: post-check=0, pre-check=0", false);
 
header("Pragma: no-cache");

 
$ext_name="libpdf_php.so";
  
// libpdf_php.so is the PDFLIB for SunOS by "PDFlib GmbH"
   // visit

  // if the extension is not automatically loaded by Apache
  // dl() will try to load it on demand:
 
if (!extension_loaded($ext_name) && !@dl($ext_name))
  {
  
?>
    <table width="100%" border="0"><tr><td align="center">
     <table style="border: solid #f0f0f0 2px;"><tr>
       <td valign="middle" style="padding: 20px; margin: 0px;">
         <p style="font-family: arial; font-size: 12px; ">
         <b>Sorry,</b><br>
         &nbsp;<br>
         A PDF can not be generated right now.<br>
         The administrator has been informed and will fix this as
         soon as possible.<br>
         Please try again later.
       </p>
     </td></tr></table>
   </td></tr></table>
   <?php
   mail
('[email protected]','Error: PDFLib not found',
        
'Called by script:\n  '.$SCRIPT_FILENAME.'?'.$QUERY_STRING,
        
"From: [email protected]\n");
   exit;
  }
// verify that extension is usable

  // unique serial number:
 
srand(microtime()*10000);
 
$usnr= gmdate("Ymd-His-").rand(1000,9999).'-';
 
$pdf_file=$usnr.'result.pdf';
 
$src_file='source.pdf';

 
// create pdf object
 
$pdf = pdf_new();
 
pdf_open_file($pdf);
 
pdf_set_parameter($pdf, 'serial',      'if-you-have-one');

 
// fonts to embed, they are in the folder of this file:
 
pdf_set_parameter($pdf, 'FontAFM',    'TradeGothic=Tg______.afm');
 
pdf_set_parameter($pdf, 'FontOutline', 'TradeGothic=Tg______.pfb');
 
pdf_set_parameter($pdf, 'FontPFM',    'TradeGothic=Tg______.pfm');

 
// load the source file:
 
$src_doc  =pdf_open_pdi($pdf,$src_file,'', 0);
 
$src_page  =pdf_open_pdi_page($pdf,$src_doc,1,'');
 
$src_width =pdf_get_pdi_value($pdf,'width' ,$src_doc,$src_page,0);
 
$src_height=pdf_get_pdi_value($pdf,'height',$src_doc,$src_page,0);

 
pdf_begin_page($pdf, $src_width, $src_height);
  {
  
// place the sourcefile to the background of the actual page:
  
pdf_place_pdi_page($pdf,$src_page,0,0,1,1);
  
pdf_close_pdi_page($pdf,$src_page);

  
// modify the page:
  
pdf_set_font($pdf, 'TradeGothic', 8, 'host');
  
pdf_show_xy($pdf, 'Now: '.gmdate("Y-m-d H:i:s"),50,50);
  }
 
pdf_end_page($pdf);
 
pdf_close($pdf);

 
// prepare output:
 
$pdfdata = pdf_get_buffer($pdf); // to echo the pdf-data
 
$pdfsize = strlen($pdfdata);    // IE requires the datasize

  // real datatype headers:
 
header('Content-type: application/pdf');
 
header('Content-disposition: attachment; filename="'.$pdf_file.'"');
 
header('Content-length: '.$pdfsize);
  echo
$pdfdata;
  exit;
// keep this one so no #13#10 or #32 will be written
?>
bob at nijman dot de
02-Aug-2001 11:20
Try these tutorials:
************************************




************************************
a dot marchand dot nospam at home dot com
01-May-2001 07:42
To continue on the internet explorer (Iexplorer, IE) requirements, instead of content-length, a simple:
header("Accept-Ranges: bytes");

is enough for the getpdf.php file working right. Even Netscape will without error with this modification.

Aurelien

<parsekit_func_arginfopdf_add_annotation>
 Last updated: Tue, 21 Dec 2004
show source | credits | sitemap | contact | advertising | mirror sites 
Copyright © 2001-2005 The PHP Group
All rights reserved.
This unofficial mirror is operated at: /
Last updated: Mon Mar 14 08:13:06 2005 Local time zone must be set--see zic manual page