FPDF: Решите, когда устанавливать данные верхнего/нижнего колонтитула
Я уже довольно давно борюсь с данными верхнего и нижнего колонтитулов и подумал, что пришло время задать их здесь, на форуме.
Что я пытаюсь сделать, так это решить, будет ли добавлена страница, следует ли добавлять верхний/нижний колонтитул или нет. поэтому с точки зрения кода я хочу включить или выключить верхний/нижний колонтитул при добавлении страницы.
Я попытался манипулировать функцией addPage, установив дополнительный аргумент $setfooterheader, для которого по умолчанию установлено значение true. А затем пытается установить это аргумент в пользу false всякий раз, когда я делаю addPage (",",false); но он по какой-то причине игнорирует его, и я не могу понять, почему.
Если я установлю значение аргумента по умолчанию равным false в самой функции, это сработает как заклинание, но когда я пытаюсь сделать это в своем скрипте и установить его в качестве аргумента, он полностью игнорирует его.
Вот фрагмент кода fpdf.php файл (функция addPage)
function AddPage($orientation='', $size='', $setHeaderFooter=true)
{
// Start a new page
if($this->state==0)
$this->Open();
$family = $this->FontFamily;
$style = $this->FontStyle.($this->underline ? 'U' : '');
$fontsize = $this->FontSizePt;
$lw = $this->LineWidth;
$dc = $this->DrawColor;
$fc = $this->FillColor;
$tc = $this->TextColor;
$cf = $this->ColorFlag;
if($this->page>0)
{
// Page footer
if ($setHeaderFooter == true)
{
$this->InFooter = true;
$this->Footer();
$this->InFooter = false;
// Close page
$this->_endpage();
}
}
// Start new page
$this->_beginpage($orientation,$size,$setHeaderFooter);
// 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,$fontsize);
// 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
if ($setHeaderFooter == true)
{
$this->InHeader = true;
$this->Header();
$this->InHeader = false;
}
// 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,$fontsize);
// 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;
}
Ниже приведен фрагмент кода моего PHP-скрипта, который использует FPDF
/** PHP FPDF */
require_once 'classes/FPDF/fpdf.php';
require_once 'classes/FPDI/fpdi.php';
class PDF extends FPDI
{
function Header()
{
$this->SetFont( 'Arial', 'B', 18 ); //set font to Arial, Bold, and 16 Size
//create heading with params
//0 - 100% width
//9 height
//"Page Heading" - With this text
//1 - border around it, and center aligned
//1 - Move pionter to new line after writing this heading
//'C' - center aligned
$this->Cell( 0, 9, 'Page Heading', 1, 1, 'C' );
$this->ln( 5 );
}
function Footer()
{
//move pionter at the bottom of the page
$this->SetY( -15 );
//set font to Arial, Bold, size 10
$this->SetFont( 'Arial', 'B', 10 );
//set font color to blue
$this->SetTextColor( 52, 98, 185 );
$this->Cell( 0, 10, 'Footer Text', 0, 0, 'L' );
//set font color to gray
$this->SetTextColor( 150, 150, 150 );
//write Page No
$this->Cell( 0, 10, 'Page No: ' . $this->PageNo(), 0, 0, 'R' );
}
}
// Create new PDF object
$pdf = new PDF('P','mm','A4');
$pdf->addPage('','',false);
// Output pdf file
$pdf->Output('test.pdf','D');
Ваша помощь заключается в очень признателен!!
3 answers
Я решил эту проблему, установив флаг вне класса и используя этот флаг в функции верхнего и нижнего колонтитулов
Исправление находится в разделе страницы, а не в функции addPage
Непосредственно перед выполнением $pdf->addPage Вы устанавливаете флаг, так как addPage автоматически вызывает функцию верхнего и нижнего колонтитулов.
Вот правильный код (фрагмент PHP-скрипта, который использует FPDF)
/** PHP FPDF */
require_once 'classes/FPDF/fpdf.php';
require_once 'classes/FPDI/fpdi.php';
class PDF extends FPDI
{
function Header()
{
if ($this->header == 1)
{
$this->SetFont( 'Arial', 'B', 18 ); //set font to Arial, Bold, and 16 Size
//create heading with params
//0 - 100% width
//9 height
//"Page Heading" - With this text
//1 - border around it, and center aligned
//1 - Move pionter to new line after writing this heading
//'C' - center aligned
$this->Cell( 0, 9, 'Page Heading', 1, 1, 'C' );
$this->ln( 5 );
}
}
function Footer()
{
if ($this->footer == 1)
{
//move pionter at the bottom of the page
$this->SetY( -15 );
//set font to Arial, Bold, size 10
$this->SetFont( 'Arial', 'B', 10 );
//set font color to blue
$this->SetTextColor( 52, 98, 185 );
$this->Cell( 0, 10, 'Footer Text', 0, 0, 'L' );
//set font color to gray
$this->SetTextColor( 150, 150, 150 );
//write Page No
$this->Cell( 0, 10, 'Page No: ' . $this->PageNo(), 0, 0, 'R' );
}
}
}
// Create new PDF object
$pdf = new PDF('P','mm','A4');
$pdf->header = 0;
$pdf->footer = 0;
$pdf->addPage('','',false);
// Output pdf file
$pdf->Output('test.pdf','D');
Я знаю, что вы уже сами узнали об этом, но, как отметил один из комментаторов, это не сработало для меня с нижним колонтитулом.
Хорошая новость в том, что вы можете обойтись без установки внешних флагов. Вы можете использовать $this->pageno(), чтобы определить, включать ли верхний и нижний колонтитулы или нет.
Например, если вы хотите исключить верхний и нижний колонтитулы на первой странице, как я сделал:
function Footer() {
if($this->PageNo() != 1){
// footer code
}
}
Если вы хотите, скажем, исключить их на нескольких страницах, а не напишите бесконечный оператор if, вы должны просто поместить номера страниц для исключения в массив и проверить с помощью in_array(), следует ли включать верхний и/или нижний колонтитулы.
Вы можете определить несколько различных типов верхних и нижних колонтитулов, вызывая функции вне класса:
class PDF extends FPDF {
function Header(){
if(!empty($this->enableheader))
call_user_func($this->enableheader,$this);
}
function Footer(){
if(!empty($this->enablefooter))
call_user_func($this->enablefooter,$this);
}
}
$pdf = new PDF('P');
$pdf->SetTextColor(0);
$pdf->SetFont('Arial','B',10);
$pdf->AliasNbPages();
$pdf->AddPage();
$pdf->Cell(50,6,'Headerless & Footerless page');
$pdf->enableheader = 'header1';
$pdf->AddPage();
$pdf->enablefooter = 'footer1';
$pdf->AddPage();
$pdf->AddPage();
$pdf->enableheader = 'header2';
$pdf->AddPage();
$pdf->enablefooter = 'footer2';
$pdf->Output();
function header1($pdf){
$pdf->Cell(50,6,'Header type 1',1,0,'L');
}
function footer1($pdf){
$pdf->SetY(280);
$pdf->Cell(50,6,'Footer type 1',1,0,'L');
$pdf->Cell(0,6,"Page: {$pdf->PageNo()} of {nb}",1,0,'R');
}
function header2($pdf){
$pdf->Cell(50,6,'Header type 2',1,0,'L');
}
function footer2($pdf){
$pdf->SetY(280);
$pdf->Cell(50,6,'Footer type 2',1,0,'L');
$pdf->Cell(0,6,"Page: {$pdf->PageNo()} of {nb}",1,0,'R');
}
Хитрость с нижними колонтитулами заключается в том, что нижний колонтитул добавляется при создании следующей страницы, а последний нижний колонтитул добавляется при закрытии вывода. Поэтому вы должны определить верхний колонтитул до добавления страницы, а нижний колонтитул - после, но перед следующей страницей.