Модераторы: skyboy, MoLeX, Aliance, ksnk
  

Поиск:

Ответ в темуСоздание новой темы Создание опроса
> Class PDF 
V
    Опции темы
overmetallist
Дата 28.8.2010, 13:51 (ссылка) | (нет голосов) Загрузка ... Загрузка ... Быстрая цитата Цитата


Шустрый
*


Профиль
Группа: Участник
Сообщений: 51
Регистрация: 19.8.2010

Репутация: нет
Всего: нет



Как самому писать такие большие классы без ошибок? Здесь приведена только маленькая часть кода. У вас есть какаето система в этом деле? smile 
Код

if(!class_exists('FPDF'))
{
define('FPDF_VERSION','1.53');

class FPDF
{
//Private properties
var $page;               //current page number
var $n;                  //current object number
var $offsets;            //array of object offsets
var $buffer;             //buffer holding in-memory PDF
var $pages;              //array containing pages
var $state;              //current document state
var $compress;           //compression flag
var $DefOrientation;     //default orientation
var $CurOrientation;     //current orientation
var $OrientationChanges; //array indicating orientation changes
var $k;                  //scale factor (number of points in user unit)
var $fwPt,$fhPt;         //dimensions of page format in points
var $fw,$fh;             //dimensions of page format in user unit
var $wPt,$hPt;           //current dimensions of page in points
var $w,$h;               //current dimensions of page in user unit
var $lMargin;            //left margin
var $tMargin;            //top margin
var $rMargin;            //right margin
var $bMargin;            //page break margin
var $cMargin;            //cell margin
var $x,$y;               //current position in user unit for cell positioning
var $lasth;              //height of last cell printed
var $LineWidth;          //line width in user unit
var $CoreFonts;          //array of standard font names
var $fonts;              //array of used fonts
var $FontFiles;          //array of font files
var $diffs;              //array of encoding differences
var $images;             //array of used images
var $PageLinks;          //array of links in pages
var $links;              //array of internal links
var $FontFamily;         //current font family
var $FontStyle;          //current font style
var $underline;          //underlining flag
var $CurrentFont;        //current font info
var $FontSizePt;         //current font size in points
var $FontSize;           //current font size in user unit
var $DrawColor;          //commands for drawing color
var $FillColor;          //commands for filling color
var $TextColor;          //commands for text color
var $ColorFlag;          //indicates whether fill and text colors are different
var $ws;                 //word spacing
var $AutoPageBreak;      //automatic page breaking
var $PageBreakTrigger;   //threshold used to trigger page breaks
var $InFooter;           //flag set when processing footer
var $ZoomMode;           //zoom display mode
var $LayoutMode;         //layout display mode
var $title;              //title
var $subject;            //subject
var $author;             //author
var $keywords;           //keywords
var $creator;            //creator
var $AliasNbPages;       //alias for total number of pages
var $PDFVersion;         //PDF version number

/*******************************************************************************
*                                                                              *
*                               Public methods                                 *
*                                                                              *
*******************************************************************************/
function FPDF($orientation='P',$unit='mm',$format='A4')
{
        //Some checks
        $this->_dochecks();
        //Initialization of properties
        $this->page=0;
        $this->n=2;
        $this->buffer='';
        $this->pages=array();
        $this->OrientationChanges=array();
        $this->state=0;
        $this->fonts=array();
        $this->FontFiles=array();
        $this->diffs=array();
        $this->images=array();
        $this->links=array();
        $this->InFooter=false;
        $this->lasth=0;
        $this->FontFamily='';
        $this->FontStyle='';
        $this->FontSizePt=12;
        $this->underline=false;
        $this->DrawColor='0 G';
        $this->FillColor='0 g';
        $this->TextColor='0 g';
        $this->ColorFlag=false;
        $this->ws=0;
        //Standard fonts
        $this->CoreFonts=array('courier'=>'Courier','courierB'=>'Courier-Bold','courierI'=>'Courier-Oblique','courierBI'=>'Courier-BoldOblique',
                'helvetica'=>'Helvetica','helveticaB'=>'Helvetica-Bold','helveticaI'=>'Helvetica-Oblique','helveticaBI'=>'Helvetica-BoldOblique',
                'times'=>'Times-Roman','timesB'=>'Times-Bold','timesI'=>'Times-Italic','timesBI'=>'Times-BoldItalic',
                'symbol'=>'Symbol','zapfdingbats'=>'ZapfDingbats');
        //Scale factor
        if($unit=='pt')
                $this->k=1;
        elseif($unit=='mm')
                $this->k=72/25.4;
        elseif($unit=='cm')
                $this->k=72/2.54;
        elseif($unit=='in')
                $this->k=72;
        else
                $this->Error('Incorrect unit: '.$unit);
        //Page format
        if(is_string($format))
        {
                $format=strtolower($format);
                if($format=='a3')
                        $format=array(841.89,1190.55);
                elseif($format=='a4')
                        $format=array(595.28,841.89);
                elseif($format=='a5')
                        $format=array(420.94,595.28);
                elseif($format=='letter')
                        $format=array(612,792);
                elseif($format=='legal')
                        $format=array(612,1008);
                else
                        $this->Error('Unknown page format: '.$format);
                $this->fwPt=$format[0];
                $this->fhPt=$format[1];
        }
        else
        {
                $this->fwPt=$format[0]*$this->k;
                $this->fhPt=$format[1]*$this->k;
        }
        $this->fw=$this->fwPt/$this->k;
        $this->fh=$this->fhPt/$this->k;
        //Page orientation
        $orientation=strtolower($orientation);
        if($orientation=='p' || $orientation=='portrait')
        {
                $this->DefOrientation='P';
                $this->wPt=$this->fwPt;
                $this->hPt=$this->fhPt;
        }
        elseif($orientation=='l' || $orientation=='landscape')
        {
                $this->DefOrientation='L';
                $this->wPt=$this->fhPt;
                $this->hPt=$this->fwPt;
        }
        else
                $this->Error('Incorrect orientation: '.$orientation);
        $this->CurOrientation=$this->DefOrientation;
        $this->w=$this->wPt/$this->k;
        $this->h=$this->hPt/$this->k;
        //Page margins (1 cm)
        $margin=28.35/$this->k;
        $this->SetMargins($margin,$margin);
        //Interior cell margin (1 mm)
        $this->cMargin=$margin/10;
        //Line width (0.2 mm)
        $this->LineWidth=.567/$this->k;
        //Automatic page break
        $this->SetAutoPageBreak(true,2*$margin);
        //Full width display mode
        $this->SetDisplayMode('fullwidth');
        //Enable compression
        $this->SetCompression(true);
        //Set default PDF version number
        $this->PDFVersion='1.3';
}

function SetMargins($left,$top,$right=-1)
{
        //Set left, top and right margins
        $this->lMargin=$left;
        $this->tMargin=$top;
        if($right==-1)
                $right=$left;
        $this->rMargin=$right;
}

function SetLeftMargin($margin)
{
        //Set left margin
        $this->lMargin=$margin;
        if($this->page>0 && $this->x<$margin)
                $this->x=$margin;
}

function SetTopMargin($margin)
{
        //Set top margin
        $this->tMargin=$margin;
}

function SetRightMargin($margin)
{
        //Set right margin
        $this->rMargin=$margin;
}

function SetAutoPageBreak($auto,$margin=0)
{
        //Set auto page break mode and triggering margin
        $this->AutoPageBreak=$auto;
        $this->bMargin=$margin;
        $this->PageBreakTrigger=$this->h-$margin;
}

function SetDisplayMode($zoom,$layout='continuous')
{
        //Set display mode in viewer
        if($zoom=='fullpage' || $zoom=='fullwidth' || $zoom=='real' || $zoom=='default' || !is_string($zoom))
                $this->ZoomMode=$zoom;
        else
                $this->Error('Incorrect zoom display mode: '.$zoom);
        if($layout=='single' || $layout=='continuous' || $layout=='two' || $layout=='default')
                $this->LayoutMode=$layout;
        else
                $this->Error('Incorrect layout display mode: '.$layout);
}

function SetCompression($compress)
{
        //Set page compression
        if(function_exists('gzcompress'))
                $this->compress=$compress;
        else
                $this->compress=false;
}

function SetTitle($title)
{
        //Title of document
        $this->title=$title;
}

function SetSubject($subject)
{
        //Subject of document
        $this->subject=$subject;
}

function SetAuthor($author)
{
        //Author of document
        $this->author=$author;
}

function SetKeywords($keywords)
{
        //Keywords of document
        $this->keywords=$keywords;
}

function SetCreator($creator)
{
        //Creator of document
        $this->creator=$creator;
}

function AliasNbPages($alias='{nb}')
{
        //Define an alias for total number of pages
        $this->AliasNbPages=$alias;
}

function Error($msg)
{
        //Fatal error
        die('<B>FPDF error: </B>'.$msg);
}

function Open()
{
        //Begin document
        $this->state=1;
}

function Close()
{
        //Terminate document
        if($this->state==3)
                return;
        if($this->page==0)
                $this->AddPage();
        //Page footer
        $this->InFooter=true;
        $this->Footer();
        $this->InFooter=false;
        //Close page
        $this->_endpage();
        //Close document
        $this->_enddoc();
}

function AddPage($orientation='')
{
        //Start a new page
        if($this->state==0)
                $this->Open();
        $family=$this->FontFamily;
        $style=$this->FontStyle.($this->underline ? 'U' : '');
        $size=$this->FontSizePt;
        $lw=$this->LineWidth;
        $dc=$this->DrawColor;
        $fc=$this->FillColor;
        $tc=$this->TextColor;
        $cf=$this->ColorFlag;
        if($this->page>0)
        {
                //Page footer
                $this->InFooter=true;
                $this->Footer();
                $this->InFooter=false;
                //Close page
                $this->_endpage();
        }
        //Start new page
        $this->_beginpage($orientation);
        //Set line cap style to square
        $this->_out('2 J');
        //Set line width
        $this->LineWidth=$lw;
        $this->_out(sprintf('%.2f w',$lw*$this->k));
        //Set font
        if($family)
                $this->SetFont($family,$style,$size);
        //Set colors
        $this->DrawColor=$dc;
        if($dc!='0 G')
                $this->_out($dc);
        $this->FillColor=$fc;
        if($fc!='0 g')
                $this->_out($fc);
        $this->TextColor=$tc;
        $this->ColorFlag=$cf;
        //Page header
        $this->Header();
        //Restore line width
        if($this->LineWidth!=$lw)
        {
                $this->LineWidth=$lw;
                $this->_out(sprintf('%.2f w',$lw*$this->k));
        }
        //Restore font
        if($family)
                $this->SetFont($family,$style,$size);
        //Restore colors
        if($this->DrawColor!=$dc)
        {
                $this->DrawColor=$dc;
                $this->_out($dc);
        }
        if($this->FillColor!=$fc)
        {
                $this->FillColor=$fc;
                $this->_out($fc);
        }
        $this->TextColor=$tc;
        $this->ColorFlag=$cf;
}

function Header()
{
        //To be implemented in your own inherited class
}

function Footer()
{
        //To be implemented in your own inherited class
}

function PageNo()
{
        //Get current page number
        return $this->page;
}

function SetDrawColor($r,$g=-1,$b=-1)
{
        //Set color for all stroking operations
        if(($r==0 && $g==0 && $b==0) || $g==-1)
                $this->DrawColor=sprintf('%.3f G',$r/255);
        else
                $this->DrawColor=sprintf('%.3f %.3f %.3f RG',$r/255,$g/255,$b/255);
        if($this->page>0)
                $this->_out($this->DrawColor);
}

function SetFillColor($r,$g=-1,$b=-1)
{
        //Set color for all filling operations
        if(($r==0 && $g==0 && $b==0) || $g==-1)
                $this->FillColor=sprintf('%.3f g',$r/255);
        else
                $this->FillColor=sprintf('%.3f %.3f %.3f rg',$r/255,$g/255,$b/255);
        $this->ColorFlag=($this->FillColor!=$this->TextColor);
        if($this->page>0)
                $this->_out($this->FillColor);
}

function SetTextColor($r,$g=-1,$b=-1)
{
        //Set color for text
        if(($r==0 && $g==0 && $b==0) || $g==-1)
                $this->TextColor=sprintf('%.3f g',$r/255);
        else
                $this->TextColor=sprintf('%.3f %.3f %.3f rg',$r/255,$g/255,$b/255);
        $this->ColorFlag=($this->FillColor!=$this->TextColor);
}

function GetStringWidth($s)
{
        //Get width of a string in the current font
        $s=(string)$s;
        $cw=&$this->CurrentFont['cw'];
        $w=0;
        $l=strlen($s);
        for($i=0;$i<$l;$i++)
                $w+=$cw[$s{$i}];
        return $w*$this->FontSize/1000;
}

function SetLineWidth($width)
{
        //Set line width
        $this->LineWidth=$width;
        if($this->page>0)
                $this->_out(sprintf('%.2f w',$width*$this->k));
}

function Line($x1,$y1,$x2,$y2)
{
        //Draw a line
        $this->_out(sprintf('%.2f %.2f m %.2f %.2f l S',$x1*$this->k,($this->h-$y1)*$this->k,$x2*$this->k,($this->h-$y2)*$this->k));
}

function Rect($x,$y,$w,$h,$style='')
{
        //Draw a rectangle
        if($style=='F')
                $op='f';
        elseif($style=='FD' || $style=='DF')
                $op='B';
        else
                $op='S';
        $this->_out(sprintf('%.2f %.2f %.2f %.2f re %s',$x*$this->k,($this->h-$y)*$this->k,$w*$this->k,-$h*$this->k,$op));
}

function AddFont($family,$style='',$file='')
{
        //Add a TrueType or Type1 font
        $family=strtolower($family);
        if($file=='')
                $file=str_replace(' ','',$family).strtolower($style).'.php';
        if($family=='arial')
                $family='helvetica';
        $style=strtoupper($style);
        if($style=='IB')
                $style='BI';
        $fontkey=$family.$style;
        if(isset($this->fonts[$fontkey]))
                $this->Error('Font already added: '.$family.' '.$style);
        include($this->_getfontpath().$file);
        if(!isset($name))
                $this->Error('Could not include font definition file');
        $i=count($this->fonts)+1;
        $this->fonts[$fontkey]=array('i'=>$i,'type'=>$type,'name'=>$name,'desc'=>$desc,'up'=>$up,'ut'=>$ut,'cw'=>$cw,'enc'=>$enc,'file'=>$file);
        if($diff)
        {
                //Search existing encodings
                $d=0;
                $nb=count($this->diffs);
                for($i=1;$i<=$nb;$i++)
                {
                        if($this->diffs[$i]==$diff)
                        {
                                $d=$i;
                                break;
                        }
                }
                if($d==0)
                {
                        $d=$nb+1;
                        $this->diffs[$d]=$diff;
                }
                $this->fonts[$fontkey]['diff']=$d;
        }
        if($file)
        {
                if($type=='TrueType')
                        $this->FontFiles[$file]=array('length1'=>$originalsize);
                else
                        $this->FontFiles[$file]=array('length1'=>$size1,'length2'=>$size2);
        }
}

function SetFont($family,$style='',$size=0)
{
        //Select a font; size given in points
        global $fpdf_charwidths;

        $family=strtolower($family);
        if($family=='')
                $family=$this->FontFamily;
        if($family=='arial')
                $family='helvetica';
        elseif($family=='symbol' || $family=='zapfdingbats')
                $style='';
        $style=strtoupper($style);
        if(strpos($style,'U')!==false)
        {
                $this->underline=true;
                $style=str_replace('U','',$style);
        }
        else
                $this->underline=false;
        if($style=='IB')
                $style='BI';
        if($size==0)
                $size=$this->FontSizePt;
        //Test if font is already selected
        if($this->FontFamily==$family && $this->FontStyle==$style && $this->FontSizePt==$size)
                return;
        //Test if used for the first time
        $fontkey=$family.$style;
        if(!isset($this->fonts[$fontkey]))
        {
                //Check if one of the standard fonts
                if(isset($this->CoreFonts[$fontkey]))
                {
                        if(!isset($fpdf_charwidths[$fontkey]))
                        {
                                //Load metric file
                                $file=$family;
                                if($family=='times' || $family=='helvetica')
                                        $file.=strtolower($style);
                                include($this->_getfontpath().$file.'.php');
                                if(!isset($fpdf_charwidths[$fontkey]))
                                        $this->Error('Could not include font metric file');
                        }
                        $i=count($this->fonts)+1;
                        $this->fonts[$fontkey]=array('i'=>$i,'type'=>'core','name'=>$this->CoreFonts[$fontkey],'up'=>-100,'ut'=>50,'cw'=>$fpdf_charwidths[$fontkey]);
                }
                else
                        $this->Error('Undefined font: '.$family.' '.$style);
        }
        //Select it
        $this->FontFamily=$family;
        $this->FontStyle=$style;
        $this->FontSizePt=$size;
        $this->FontSize=$size/$this->k;
        $this->CurrentFont=&$this->fonts[$fontkey];
        if($this->page>0)
                $this->_out(sprintf('BT /F%d %.2f Tf ET',$this->CurrentFont['i'],$this->FontSizePt));
}

function SetFontSize($size)
{
        //Set font size in points
        if($this->FontSizePt==$size)
                return;
        $this->FontSizePt=$size;
        $this->FontSize=$size/$this->k;
        if($this->page>0)
                $this->_out(sprintf('BT /F%d %.2f Tf ET',$this->CurrentFont['i'],$this->FontSizePt));
}

function AddLink()
{
        //Create a new internal link
        $n=count($this->links)+1;
        $this->links[$n]=array(0,0);
        return $n;
}

function SetLink($link,$y=0,$page=-1)
{
        //Set destination of internal link
        if($y==-1)
                $y=$this->y;
        if($page==-1)
                $page=$this->page;
        $this->links[$link]=array($page,$y);
}

function Link($x,$y,$w,$h,$link)
{
        //Put a link on the page
        $this->PageLinks[$this->page][]=array($x*$this->k,$this->hPt-$y*$this->k,$w*$this->k,$h*$this->k,$link);
}

function Text($x,$y,$txt)
{
        //Output a string
        $s=sprintf('BT %.2f %.2f Td (%s) Tj ET',$x*$this->k,($this->h-$y)*$this->k,$this->_escape($txt));
        if($this->underline && $txt!='')
                $s.=' '.$this->_dounderline($x,$y,$txt);
        if($this->ColorFlag)
                $s='q '.$this->TextColor.' '.$s.' Q';
        $this->_out($s);
}

function AcceptPageBreak()
{
        //Accept automatic page break or not
        return $this->AutoPageBreak;
}


?>



Это сообщение отредактировал(а) overmetallist - 28.8.2010, 13:52
PM MAIL WWW IM ICQ Skype GTalk Jabber AOL YIM MSN   Вверх
sergejzr
Дата 28.8.2010, 13:53 (ссылка) |    (голосов:1) Загрузка ... Загрузка ... Быстрая цитата Цитата


Un salsero
Group Icon


Профиль
Группа: Админ
Сообщений: 13285
Регистрация: 10.2.2004
Где: Германия г .Ганновер

Репутация: 5
Всего: 360



Используй хорошую IDE, например eclipse. Не фонтан, конечно (это уже специфика языка), но реально поможет.


--------------------
PM WWW IM ICQ Skype GTalk Jabber AOL YIM MSN   Вверх
overmetallist
  Дата 28.8.2010, 13:57 (ссылка) | (нет голосов) Загрузка ... Загрузка ... Быстрая цитата Цитата


Шустрый
*


Профиль
Группа: Участник
Сообщений: 51
Регистрация: 19.8.2010

Репутация: нет
Всего: нет



sergejzr спасибо, но какова сама система разработки, начинать надо с каких методов класса, и чем заканчивать?... smile 
p.s. и когда пишите большой проект или CMS , в каком порядке идет разработка?, такого я нигде ни читал, и писал маленькие сайты или редакировал ЦМС smile 

Это сообщение отредактировал(а) overmetallist - 28.8.2010, 13:59
PM MAIL WWW IM ICQ Skype GTalk Jabber AOL YIM MSN   Вверх
overmet
Дата 28.8.2010, 14:10 (ссылка) | (нет голосов) Загрузка ... Загрузка ... Быстрая цитата Цитата


Шустрый
*


Профиль
Группа: Участник
Сообщений: 83
Регистрация: 15.8.2009
Где: Gomel

Репутация: -2
Всего: -2



overmetal 2 вернулся после бана за флуд в других разделах форума smile 
PM MAIL WWW IM ICQ Skype GTalk Jabber AOL YIM MSN   Вверх
overmetallist
Дата 28.8.2010, 22:38 (ссылка) | (нет голосов) Загрузка ... Загрузка ... Быстрая цитата Цитата


Шустрый
*


Профиль
Группа: Участник
Сообщений: 51
Регистрация: 19.8.2010

Репутация: нет
Всего: нет



да, походу это секрет smile 
PM MAIL WWW IM ICQ Skype GTalk Jabber AOL YIM MSN   Вверх
overmetallist
Дата 29.8.2010, 20:58 (ссылка) | (нет голосов) Загрузка ... Загрузка ... Быстрая цитата Цитата


Шустрый
*


Профиль
Группа: Участник
Сообщений: 51
Регистрация: 19.8.2010

Репутация: нет
Всего: нет



ну признаайтесь - очень интересно smile 
PM MAIL WWW IM ICQ Skype GTalk Jabber AOL YIM MSN   Вверх
Sentox
Дата 29.8.2010, 22:44 (ссылка) | (нет голосов) Загрузка ... Загрузка ... Быстрая цитата Цитата


как то так
**


Профиль
Группа: Участник
Сообщений: 392
Регистрация: 27.1.2009
Где: Зимбабве

Репутация: 7
Всего: 7



RUP, OpenUP, Scrum, XP и др.
PM MAIL   Вверх
overmetallist
Дата 29.8.2010, 23:06 (ссылка) | (нет голосов) Загрузка ... Загрузка ... Быстрая цитата Цитата


Шустрый
*


Профиль
Группа: Участник
Сообщений: 51
Регистрация: 19.8.2010

Репутация: нет
Всего: нет



а порядок разработки? по пунктам можно опиисать? smile 
PM MAIL WWW IM ICQ Skype GTalk Jabber AOL YIM MSN   Вверх
  
Ответ в темуСоздание новой темы Создание опроса
Правила форума "PHP"
Aliance
IZ@TOP
skyboy
SamDark
MoLeX

Новичкам:

  • PHP редакторы собираются и обсуждаются здесь
  • Электронные книги по PHP, документацию можно найти здесь
  • Интерпретатор PHP, полную документацию можно скачать на PHP.NET

Важно:

  • Не брезгуйте пользоваться тегами [code=php]КОД[/code] для повышения читабельности текста/кода.
  • Перед созданием новой темы воспользуйтесь поиском и загляните в FAQ
  • Действия модераторов можно обсудить здесь

Внимание:

  • Темы "ищу скрипт", "подскажите скрипт" и т.п. будут переноситься в форум "Web-технологии"
  • Темы с именами: "Срочно", "помогите", "не знаю как делать" будут УДАЛЯТЬСЯ

Если Вам понравилась атмосфера форума, заходите к нам чаще! С уважением, IZ@TOP, skyboy, SamDark, MoLeX, awers.

 
1 Пользователей читают эту тему (1 Гостей и 0 Скрытых Пользователей)
0 Пользователей:
« Предыдущая тема | PHP: Общие вопросы | Следующая тема »


 




[ Время генерации скрипта: 0.0597 ]   [ Использовано запросов: 21 ]   [ GZIP включён ]


Реклама на сайте     Информационное спонсорство

 
По вопросам размещения рекламы пишите на vladimir(sobaka)vingrad.ru
Отказ от ответственности     Powered by Invision Power Board(R) 1.3 © 2003  IPS, Inc.