I am using Python version of FPDF, PyFPDF to generate PDFs. I want to add transparency to a rectangle I created using PyFPDF.
I found PHP code in fpdf documentation that lets us add transparency - trasnparency. I tried to follow this and write code in python but it didn't work.
Code snippet found in documentation(in PHP):
source
<?php
require('fpdf.php');
class AlphaPDF extends FPDF
{
var $extgstates = array();
// alpha: real value from 0 (transparent) to 1 (opaque)
// bm: blend mode, one of the following:
// Normal, Multiply, Screen, Overlay, Darken, Lighten, ColorDodge, ColorBurn,
// HardLight, SoftLight, Difference, Exclusion, Hue, Saturation, Color, Luminosity
function SetAlpha($alpha, $bm='Normal')
{
// set alpha for stroking (CA) and non-stroking (ca) operations
$gs = $this->AddExtGState(array('ca'=>$alpha, 'CA'=>$alpha, 'BM'=>'/'.$bm));
$this->SetExtGState($gs);
}
function AddExtGState($parms)
{
$n = count($this->extgstates)+1;
$this->extgstates[$n]['parms'] = $parms;
return $n;
}
function SetExtGState($gs)
{
$this->_out(sprintf('/GS%d gs', $gs));
}
function _enddoc()
{
if(!empty($this->extgstates) && $this->PDFVersion<'1.4')
$this->PDFVersion='1.4';
parent::_enddoc();
}
function _putextgstates()
{
for ($i = 1; $i <= count($this->extgstates); $i++)
{
$this->_newobj();
$this->extgstates[$i]['n'] = $this->n;
$this->_out('<</Type /ExtGState');
$parms = $this->extgstates[$i]['parms'];
$this->_out(sprintf('/ca %.3F', $parms['ca']));
$this->_out(sprintf('/CA %.3F', $parms['CA']));
$this->_out('/BM '.$parms['BM']);
$this->_out('>>');
$this->_out('endobj');
}
}
function _putresourcedict()
{
parent::_putresourcedict();
$this->_out('/ExtGState <<');
foreach($this->extgstates as $k=>$extgstate)
$this->_out('/GS'.$k.' '.$extgstate['n'].' 0 R');
$this->_out('>>');
}
function _putresources()
{
$this->_putextgstates();
parent::_putresources();
}
}
?>
usage
<?php
require('alphapdf.php');
$pdf = new AlphaPDF();
$pdf->AddPage();
$pdf->SetLineWidth(1.5);
// draw opaque red square
$pdf->SetFillColor(255,0,0);
$pdf->Rect(10,10,40,40,'DF');
// set alpha to semi-transparency
$pdf->SetAlpha(0.5);
// draw green square
$pdf->SetFillColor(0,255,0);
$pdf->Rect(20,20,40,40,'DF');
// draw jpeg image
$pdf->Image('lena.jpg',30,30,40);
// restore full opacity
$pdf->SetAlpha(1);
// print name
$pdf->SetFont('Arial', '', 12);
$pdf->Text(46,68,'Lena');
$pdf->Output();
?>
This is what I wrote in python:
source
class EXPDF(FPDF):
def __init__(self, orientation='P', unit='mm', style='A4'):
super(EXPDF, self).__init__(orientation=orientation, unit=unit, format=style)
self.page_format = style.lower()
self.extgstates = {}
def set_alpha(self, alpha, bm='Normal'):
gs = self.add_ext_gstate({'ca': alpha, 'CA': alpha, 'BM': '/'+bm})
self.set_ext_gstate(gs)
def add_ext_gstate(self, parms):
n = len(self.extgstates.keys())+1
if n not in self.extgstates.keys():
self.extgstates[n] = { 'parms': parms }
else:
self.extgstates[n]['parms'] = parms
return n
def set_ext_gstate(self, gs):
self._out(sprintf('/GS%d gs', gs))
def _enddoc(self):
if self.extgstates and self.pdf_version < '1.4':
self.pdf_version = '1.4'
super()._enddoc()
def _putextgstates(self):
for i in range(1, len(self.extgstates.keys())+1):
self._newobj()
self.extgstates[i]['n'] = self.n
self._out('<</Type /ExtGState')
parms = self.extgstates[i]['parms']
self._out(sprintf('/ca %.3F', parms['ca']))
self._out(sprintf('/CA %.3F', parms['CA']))
self._out('/BM'+parms['BM'])
self._out('>>')
self._out('endobj')
def _putresourcedict(self):
super()._putresourcedict()
self._out('/ExtGState <<')
for k in self.extgstates:
self._out('/GS'+str(k)+' '+str(self.extgstates[k]['n'])+' O R')
self._out('>>')
usage
pdf = EXPDF()
pdf.set_alpha(0.5)
pdf.rectangle(20, 20, 40, 40, 'DF')
The code didn't throw any error when I ran it. But when I tried to open the generated pdf in Adobe Acrobat, it said There was a problem reading this document (135). I tried opening the pdf in google chrome. It opened but the rectangle was still opaque.
I think your python code has a couple of errors:
it is missing the _putresources method.
in the method _putresourcesdict the following line has a capital O rather than a zero 0. So change to 0 R.
self._out('/GS'+str(k)+' '+str(self.extgstates[k]['n'])+' O R')
You need a class like this (pyFPDF used https://github.com/reingart/pyfpdf):
class PDF (fpdf.FPDF):
def __init__ (self, orientation = 'P', unit = 'mm', format = 'A4'):
self.__extgstates = []
super().__init__ (orientation, unit, format)
# alpha: real value from 0 (transparent) to 1 (opaque)
# bm: blend mode, one of the following:
# Normal, Multiply, Screen, Overlay, Darken, Lighten, ColorDodge, ColorBurn,
# HardLight, SoftLight, Difference, Exclusion, Hue, Saturation, Color, Luminosity
def set_alpha(self, alpha, bm='Normal'):
# set alpha for stroking (CA) and non-stroking (ca) operations
data = {'ca':alpha,'CA':alpha,'BM':'/' + bm, 'n' : 0}
gs = self.add_ext_gstate(data)
self.set_ext_gstate(gs + 1)
def add_ext_gstate(self, data):
n = len(self.__extgstates)
self.__extgstates.append(data)
return n
def _enddoc(self):
if len(self.__extgstates) > 0 and self.pdf_version < '1.4':
self.pdf_version ='1.4'
super()._enddoc()
def set_ext_gstate(self, gs):
self._out('/GS%d gs' % (gs))
def _putextgstates(self):
i = 0
while i < len(self.__extgstates):
self._newobj()
self._out('<</Type /ExtGState')
self.__extgstates[i]["n"] = self.n
parms = self.__extgstates[i]
self._out('/ca %.3F' % (parms["ca"]))
self._out('/CA %.3F' % (parms["CA"]))
self._out('/BM ' + parms["BM"])
self._out('>>')
self._out('endobj')
i += 1
def _putresourcedict(self):
super()._putresourcedict()
self._out('/ExtGState <<')
for index, eg in enumerate(self.__extgstates):
self._out('/GS' + str(index + 1) + ' ' + str(eg["n"]) + ' 0 R')
self._out('>>')
def _putresources(self):
self._putextgstates()
super()._putresources()
Related
with help of below code, i successfully displaying tracking_id in pdf , Now i am trying to displaying bar code image....
Its working fine if i use static value . but when i passed column value instead of static value it gave error :
Static : $text = isset($_GET['text']) ? $_GET['text'] : "1234";
:
Dynamic :
$text = isset($_GET['text']) ? $_GET['text'] : $tracking_id;
Result :
I guess I am passing tracking_id column value not in proper manner :
<?php
$con = mysqli_connect("localhost","root","iJ564645qA9v3J","do_management4");
include('database.php');
$result = mysqli_query($con,"SELECT * FROM orders");
while($row = mysqli_fetch_array($result))
{
$id = $row['id'];
$tracking_id = $row['tracking_id'];
}
$database = new Database();
$result = $database->runQuery("SELECT tracking_id FROM orders where id = '".$_REQUEST['id']."'");
$header = $database->runQuery("SELECT UCASE(`COLUMN_NAME`)
FROM `INFORMATION_SCHEMA`.`COLUMNS`
WHERE `TABLE_SCHEMA`='do_management4'
AND `TABLE_NAME`='orders'
and `COLUMN_NAME` in ('tracking_id')");
require __DIR__ . '/../vendor/autoload.php';
use BarcodeBakery\Barcode\BCGcode11;
// Loading Font
$font = new BCGFontFile(__DIR__ . '/../font/Arial.ttf', 18);
// Don't forget to sanitize user inputs
$text = isset($_GET['text']) ? $_GET['text'] : $tracking_id;
// The arguments are R, G, B for color.
$color_black = new BCGColor(0, 0, 0);
$color_white = new BCGColor(255, 255, 255);
$drawException = null;
try {
$code = new BCGcode11();
$code->setScale(2); // Resolution
$code->setThickness(30); // Thickness
$code->setForegroundColor($color_black); // Color of bars
$code->setBackgroundColor($color_white); // Color of spaces
$code->setFont($font); // Font (or 0)
$code->parse($text); // Text
} catch (Exception $exception) {
$drawException = $exception;
}
$drawing = new BCGDrawing('', $color_white);
if ($drawException) {
$drawing->drawException($drawException);
} else {
$drawing->setBarcode($code);
$drawing->draw();
}
// Header that says it is an image (remove it if you save the barcode to a file)
header('Content-Type: image/png');
header('Content-Disposition: inline; filename="barcode.png"');
// Draw (or save) the image into PNG format.
$drawing->finish(BCGDrawing::IMG_FORMAT_PNG);
?>
Considering the documentation BCGcode11 allows only the numbers from 0 to 9 and a hyphen (-)
You either can
Remove the unwanted characters from $tracking_id which may lead to wrong datas
Use the proper class for the barecode you want.
BCGcode39 allows more characters to build your barecode : Code 39 contains all the capital letters, the numbers from 0 to 9, the following special characters "-.$/+%" and spaces.
Use BCGcode39 it allows you to use more characters lik capital letters and some special characters. or keep using BCGcode11 but then you need to remove the unallowed characters.
Following is my code which prints "HELLO", then a dotted line. This thing gets repeated 50 times. Everything is working fine but when 2nd page starts, dotted lines disappear. What modification is required in this code?
<?php
require("fpdf.php");
class PDF extends FPDF
{
function SetDash($black=null, $white=null)
{
if($black!==null)
$s=sprintf('[%.3F %.3F] 0 d',$black*$this->k,$white*$this->k);
else
$s='[] 0 d';
$this->_out($s);
}
}
$pdf = new PDF('P', 'mm', 'A4');
$pdf->AliasNbPages();
$pdf->AddPage();
$margin = 0;
$pdf->SetFont('Arial','B',12);
for ($i = 0; $i < 50; $i++)
{
$pdf->Cell(90, 10, "Hello", 0, 1);
$pdf->SetDrawColor(0,0,0);
$pdf->SetDash(2,2);
$margin = $margin + 10;
$pdf->Line(10,$margin,200,$margin);
}
$pdf->Output();
?>
You're incrementing the value of your $margin variable by 10 after each line even if a page break occurs in the middle of the loop. Thus, the top margin of the first line on the second page will be 10 millimeters greater than the top margin of the last line on the first page.
You need to reset the margin when a new page is added.
A solution for this problem would be to override FPDF's AcceptPageBreak method. This method intercepts the adding of a new page when the bottom of a page is reached.
class PDF extends FPDF
{
var $lineY = 0;
// ...
function AcceptPageBreak()
{
$this->lineY = 0;
return parent::AcceptPageBreak();
}
}
Then, in your loop, you can do:
$pdf->Line(10, $pdf->lineY, 200, $pdf->lineY);
I'm using QRCode from Google API and I put this code in the function.
Now I want to show two images, for example: Two images with different sizes or datas!
It does not matter if you use class or function, I just want to get different output on the page.
This is code:
<?php
function CreateQRCode($data, $size, $logo) {
header('Content-type: image/png');
// Get QR Code image from Google Chart API
// http://code.google.com/apis/chart/infographics/docs/qr_codes.html
$QR = imagecreatefrompng('https://chart.googleapis.com/chart?cht=qr&chld=H|1&chs='.$size.'&chl='.urlencode($data));
if($logo !== FALSE){
$logo = imagecreatefromstring(file_get_contents($logo));
$QR_width = imagesx($QR);
$QR_height = imagesy($QR);
$logo_width = imagesx($logo);
$logo_height = imagesy($logo);
// Scale logo to fit in the QR Code
$logo_qr_width = $QR_width/3;
$scale = $logo_width/$logo_qr_width;
$logo_qr_height = $logo_height/$scale;
imagecopyresampled($QR, $logo, $QR_width/3, $QR_height/3, 0, 0, $logo_qr_width, $logo_qr_height, $logo_width, $logo_height);
}
imagepng($QR);
imagedestroy($QR);
}
CreateQRCode('http://google.com', '200x200', FALSE);
?>
Like this:
example 2
example 1
Alright so first things first:
I've searched over this site for 6+ hours and I keep coming up with the same results. The main answer I keep getting is: How to Generate Barcode using PHP and Display it as an Image on the same page
But this is not working for me. Even the answer on that page that was accepted ends with "After you have added all the codes, you will get this way:" which is so vague I feel like I'm supposed to already be an expert to understand it. I'm getting frustrated with this problem because I cannot seem to find any "moron directions" that can help me understand how everything works in this library for barcode generator for php.
Here is what I have:
I'm using fpdf to print a pdf file which works great!
Page Name: PrintMyPDF.php
<?php
//error_reporting(E_ALL);
//ini_set('display_errors', 1);
$thisorderID = $_GET['Xort'];
require ('UFunctions.php');
if (trim($thisorderID) == ""){
$value = '0';
}
if (!is_digit($thisorderID) || $thisorderID < 0)
{
header('Location:ErrorInt.php');
exit;
}
//Database connection established
require_once('DBASEConnector.php');
$sql2 = "SELECT users.name, users.storenum, users.storename, Orders.OrderID, Orders.name
FROM users, Orders
WHERE Orders.name = users.name
AND Orders.OrderID = '$thisorderID'";
$result = $db->query($sql2);
$row = $result->fetch_assoc();
$ThisStoreNum = $row['storenum'];
$ThisStoreName = $row['storename'];
require('fpdf.php');
$pdf = new FPDF();
//$fpdf->SetMargins(0, 0, 0);
//$fpdf->SetAutoPageBreak(true, 0);
$pdf->SetAuthor('Walter Ballsbig');
$pdf->SetTitle('Order Form');
$pdf->SetFont('Helvetica','B',16);
$pdf->SetTextColor(0,0,0);
$pdf->AddPage('P');
$pdf->SetDisplayMode(real,'default');
$pdf->SetXY(50,20);
$pdf->SetDrawColor(0,0,0);
$pdf->Cell(100,10,'Order Form',1,1,'C',0);
$pdf->SetFontSize(10);
$pdf->SetX(50);
$pdf->Cell(100,10, 'Order: '.$thisorderID.' | Store: '.$ThisStoreNum.'-'.$ThisStoreName,1,1,'C',0);
$pdf->SetXY(10,50);
$pdf->SetFontSize(12);
$pdf->Cell(6,6,'X',1,0,'C',0);
$pdf->Cell(14,6,'QTY',1,0,'C',0);
$pdf->Cell(130,6, 'ITEM',1,0,'C',0);
$pdf->Cell(30,6, 'UNIT',1,1,'C',0);
$query = "SELECT Inventory.ProductI, Inventory.ProductName, Inventory.CurrentQty, Inventory.Pull, Inventory.Unit, OrderItems.ProductI, OrderItems.QtyO, OrderItems.OrderI
FROM Inventory, OrderItems
WHERE OrderItems.OrderI = '$thisorderID'
AND OrderItems.ProductI = Inventory.ProductI
ORDER BY Inventory.Pull, Inventory.ProductName";
$result = $db->query($query);
$num_results = $result->num_rows;
for ($i=0; $i <$num_results; $i++)
{
$row = $result->fetch_assoc();
$pdf->SetFontSize(12);
IF ($row['CurrentQty'] <=0)
{
$pdf->SetFontSize(10);
$pdf->Cell(6,6,'BO',1,0,'C',0);
$pdf->SetFontSize(12);
}else{
$pdf->Cell(6,6,' ',1,0,'C',0);
}
$pdf->Cell(14,6, $row['QtyO'],1,0,'C',0);
$pdf->Cell(130,6, $row['ProductName'],1,0,'L',0);
$pdf->Cell(30,6, $row['Unit'],1,1,'C',0);
}
$pdf->Output();
$db->close();
?>
This prints up my pdf beautifully! Now I wanted to add a barcode on the page that will represent the order number for scanning purposes.
Now here is what I have for my code that contains the barcode... code.
Name of barcode page: BarCodeIt.php
<?php
function BarCodeIt($MyID) {
// Including all required classes
require_once('./class/BCGFontFile.php');
require_once('./class/BCGColor.php');
require_once('./class/BCGDrawing.php');
// Including the barcode technology
require_once('./class/BCGcode39.barcode.php');
// Loading Font
$font = new BCGFontFile('./font/Arial.ttf', 18);
// Don't forget to sanitize user inputs
$text = isset($_GET['text']) ? $_GET['text'] : $MyID;
// The arguments are R, G, B for color.
$color_black = new BCGColor(0, 0, 0);
$color_white = new BCGColor(255, 255, 255);
$drawException = null;
try {
$code = new BCGcode39();
$code->setScale(2); // Resolution
$code->setThickness(30); // Thickness
$code->setForegroundColor($color_black); // Color of bars
$code->setBackgroundColor($color_white); // Color of spaces
$code->setFont($font); // Font (or 0)
$code->parse($text); // Text
} catch(Exception $exception) {
$drawException = $exception;
}
/* Here is the list of the arguments
1 - Filename (empty : display on screen)
2 - Background color */
$drawing = new BCGDrawing('', $color_white);
if($drawException) {
$drawing->drawException($drawException);
} else {
$drawing->setBarcode($code);
$drawing->draw();
}
//Header that says it is an image (remove it if you save the barcode to a file)
header('Content-Type: image/png');
header('Content-Disposition: inline; filename="barcode.png"');
// Draw (or save) the image into PNG format.
$drawing->finish(BCGDrawing::IMG_FORMAT_PNG);
}
?>
Now in my PDF file just before this line:
$pdf->Output();
I have added this:
$pdf->AddPage('P');
$pdf->SetDisplayMode(real,'default');
require('/BarCodeIt.php');
$MyBarCode = BarCodeIt($thisorderID);
echo $MyBarCode;
But what it does is all of my other pdf elements disappear and I'm left with only a big barcode (the right one! that part works) but that's all that is on the screen. It's like when the barcode section runs it negates everything else and just prints the barcode. I want to print just the barcode where I want it on the PDF but I'm not clever enough to figure out what I'm doing wrong. Any help on this would be greatly appreciated.
In $pdf->SetDisplayMode(real,'default');, real is not an identifier. I believe you've forgotten the $ prefix.
Have you warnings reporting at maximum level? If not, include:
error_reporting(E_ALL);
in your script and see that it shows additional issues.
I'm not familiar with fpdf, but what you are doing seems wrong just by looking at it: Everywhere you add elements to your pdf by using methods on your $pdf object like $pdf->... and when you want to add the barcode, you echo it out directly.
Don't echo your image out. Instead get rid of the header() calls in your barcode script, save your image and look for the right method to add an image to the $pdf object.
Here is a question with answers that deals with adding an image: Inserting an image with PHP and FPDF
I've been struggling with the header and footer data for quite some time now and thought it was time to ask it here on the forum.
What I'm trying to do is decide that if a page is added if the header / footer should be added or not. so code-wise I want to set the header/footer to on or off when adding a page.
I've tried to manipulate the function AddPage by setting an extra argument $setFooterHeader which default is set to true. And then trying to set this argument to false whenever I do an addPage('','',false); but it ignores it for some reason and I can't figure out why.
If I set the default value of the argument to false in the function itself it works like a charm, but when I try to do it in my script and set it as an argument, it totally ignores it.
Here's a code snippet of the fpdf.php file (function 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;
}
Below is a code snippet of my PHP script which uses 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');
Your help is greatly appreciated!!
I have solved this issue by setting a flag outside the class and use this flag in the header and footer function
The fix is in the page section, not in the addPage function
Just before doing an $pdf->addPage You set the flag as addPage automatically calls the header and footer function.
Here's the correct code (snippet of PHP script which uses 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');
I know you found out the awnser already for yourself, but as one of the commenters pointed out this didn't work for me with the footer.
The good news is you can do without setting the external flags. You can use $this->PageNo() to determine whether to include the header and footer or not.
For instance if you'd want to exclude the header and footer on the first page, like I did:
function Footer() {
if($this->PageNo() != 1){
// footer code
}
}
If you'd want to let's say exclude them on several pages and not write an endless if statement you should just put the page numbers to exclude in an array and check with in_array() whether the header and/or footer should be included.
You can define multiple different types of headers and footers by calling functions outside the class:
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');
}
The trick to footers is that the footer is added when the next page is created, with the last footer being added when the output is closed.
Therefore, you have to define the header before the page is added, and the footer afterwards but before the next page.