|
|
LXXXIII. PDF funkce
PDF funkce v PHP mohou vytvo�it PDF soubory s vyu�it�m knihovny
PDFlib vytvo�en� .
Dokumentace t�to sekce je my�lena pouze jako p�ehled
dostupn�ch funkc� v knihovn� PDFlib a nem�la by b�t
pova�ov�na za vy�erp�vaj�c� p�ehled. Pros�m konzultujte
dokumentaci obsa�enou v distribuci PDFlib pro
�pln� a detailn� vysv�tlen� ka�d� zde uveden� funkce.
Poskytuje velmi dobr� p�ehled toho, co PDFlib dok�e
a obsahuje nej�erstv�j�� dokumentaci ke v�em funkc�m.
V�t�ina funkc� pdflib a p��slu�n�ho PHP modulu m� stejn� jm�no. Argumenty
jsou tak� identick�. Pokud chcete tento modul vyu��vat opravdu efektivn�,
m�li byste ch�pat tak� n�kter� z koncept� PDF nebo Postscriptu.
V�echny rozm�ry a koordin�ty se ud�vaj� v Postscriptov�ch bodech.
Obecn� je 72 PostScriptov�ch bod� na palec, ale z�vis� to na v�stupn�m
rozli�en�.
V�nujte pros�m pozornost dokumentaci pdflib, kter� je sou��st�
distribuce zdrojov�ho k�du, pro bli��� vysv�tlen� pou�it�ho sou�adnicov�ho
syst�mu.
Vemte pros�m na v�dom�, �e v�t�ina PDF funkc� vy�aduje
pdfdoc jako prvn� parametr. Viz
p��klady n�e pro bli���
vysv�tlen�.
Pozn�mka:
Pokud se zaj�m�t� o alternativn� voln� dostupn� PDF gener�tory, kter�
nepot�ebuj� extern� PDF knihovny, pod�vejte se na
tuto souvisej�c� FAQ.
PDFlib lze st�hnout na , ale vy�aduje, abyste zakoupili
licenci pro komer�n� pou�it�. Pro zkompilov�n�
tohoto roz���en� jsou pot�eba knihovny a .
��dn� verze PHP 4 od data 9. b�ezna 2000 nepodporuje podflib star�� ne�
3.0.
PDFlib 3.0 a vy��� je podporov�no PHP 3.0.19 a vy���.
Abyste mohli tyto funkce pou��vat, mus�te PHP zkompilovat s volbou
--with-pdflib[=DIR]. DIR je z�kladn�
instala�n� adres�� PDFlib, v�choz� hodnota je /usr/local.
Nav�c m��ete ur�it knihovny jpeg, tiff a png, kter� m� PDFlib
pou��vat, co� je voliteln� v PDFlib 4.x.
Pokud tak chcete u�init, p�idejte volby configure
--with-jpeg-dir[=DIR]
--with-png-dir[=DIR]
--with-tiff-dir[=DIR].
Od pdflib 3.0 by se pdflib m�la konfigurovat s volbou
--enable-shared-pdflib.
Toto roz���en� nem� definov�no ��dn� konfigura�n�
direktivy.
Od PHP 4.0.5 je PHP roz���en�
ofici�ln� podporov�no spole�nost� PDFlib GmbH. To znamen�, �e v�echny
funkce popsan� v PDFlib manu�lu (V3.00 nebo vy���) jsou
podporov�ny v PHP 4 s p�esn� stejn�m v�znamem a stejn�mi
parametry. Oproti manu�lu PDFlib se mohou li�it pouze n�vratov�
hodnoty, proto�e byla p�evzata konvence PHP
pro vracen� FALSE was adopted. Z d�vodu kompatibility
toto roz���en� PDFlib st�le podporuje star� funkce, ale tyto
by m�ly b�t nahrazeny jejich nov�j��mi verzemi. PDFlib GmbH nepom�h�
s �e�en�m ��dn�ch probl�m� plynouc�ch z pou��v�n� t�chto zastaral�ch
funkc�.
Tabulka 1. Zastaral� funkce a jejich n�hrady
V�t�ina funkc� se pou��v� docela snadno. Nejt쾹� je z�ejm� v�bec n�jak�
jednoduch� PDF dokument v�bec vytvo�it. N�sleduj�c� uk�zka by m�la pomoci
za��t.
Vytvo�� soubor test.pdf s jednou str�nkou. Tato str�nka
obsahuje text "Times Roman outlined" napsan� 30ti bodov�m obrysem. Text je
tak� podtr�en�.
P��klad 1. Tvorba PDF dokumentu s pdflib
<?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");
$font = pdf_findfont($pdf, "Times New Roman", "winansi", 1);
pdf_setfont($pdf, $font, 10);
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>finished</A>";
?>
|
|
Skript getpdf.php pouze vr�t� vytvo�en� pdf dokument.
P��klad 2. Vr�tit p�ipraven� PDF
<?php
$len = filesize($filename);
header("Content-type: application/pdf");
header("Content-Length: $len");
header("Content-Disposition: inline; filename=foo.pdf");
readfile($filename);
?>
|
|
Distribuce pdflib obsahuje rozs�hlej�� uk�zku, kter� obsahuje s�rii str�nek
s analogov�mi hodinami. Tato uk�zka p�eveden� do PHP vypad� takto (stejnou
uk�zku najdete v dokumentaci k
clibpdf modulu):
P��klad 3. pdfclock uk�zka z pdflib distribuce
<?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);
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);
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);
?>
|
|
Pozn�mka:
Existuje dal�� PHP modul na tvorbu PDF dokument�, zalo�en� na ClibPDF od
firmy . Detaily
viz ClibPDF funkce. M� m�rn� jinou API.
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); ?>
Can become:
<?php
$pdf->show($text); ?>
Code:
<?php
class PDF {
private $pdf;
public function __construct() {
$this->pdf = pdf_new();
}
public function __call($function, $arguments) {
array_unshift($arguments, $this->pdf);
return call_user_func_array('pdf_' . $function, $arguments);
}
}
?>
michi (Alt+Q) marel.at
01-Jul-2004 02:10
<?PHP
function calcToPt($intMillimeter) {
$intPoints = ($intMillimeter*72)/25.4;
$intPoints = round($intPoints);
return $intPoints;
}
pdf_begin_page( $pdf, calcToPt(210), calcToPt(297)); ?>
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) == ']') {
$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
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";
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>
<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;
} srand(microtime()*10000);
$usnr= gmdate("Ymd-His-").rand(1000,9999).'-';
$pdf_file=$usnr.'result.pdf';
$src_file='source.pdf';
$pdf = pdf_new();
pdf_open_file($pdf);
pdf_set_parameter($pdf, 'serial', 'if-you-have-one');
pdf_set_parameter($pdf, 'FontAFM', 'TradeGothic=Tg______.afm');
pdf_set_parameter($pdf, 'FontOutline', 'TradeGothic=Tg______.pfb');
pdf_set_parameter($pdf, 'FontPFM', 'TradeGothic=Tg______.pfm');
$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);
{
pdf_place_pdi_page($pdf,$src_page,0,0,1,1);
pdf_close_pdi_page($pdf,$src_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);
$pdfdata = pdf_get_buffer($pdf); $pdfsize = strlen($pdfdata); header('Content-type: application/pdf');
header('Content-disposition: attachment; filename="'.$pdf_file.'"');
header('Content-length: '.$pdfsize);
echo $pdfdata;
exit; ?>
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
| |