Using FPDF in an application - php

I have been testing with FPDF and it's going okay in terms of making the PDF.
In my application I plan to have a button that reads 'Convert to PDF' and when the user clicks it, FPDF will create the PDF in a new window using given variables.
The code to generate the PDF is like the below:
require_once("fpdf.php");
$author = "Test";
$title = "Candidate profile";
$width = 10;
$height = 10;
$text = "Test";
$font_family = 'Arial';
$font_size = 11;
$file_name = "candidate-profile-jesse-orange";
$extension = ".pdf";
$output = "I";
$heading_size = 16;
$subheading_size = 13;
class PDF extends FPDF
{
// Page header
function Header()
{
// Logo
$this->Image('logo.png',10,10,30);
// Arial bold 15
$this->SetFont('Arial','B',16);
// Move to the right
$this->Cell(50);
// Title
$this->Cell(100,8,'Candidate profile for: Jesse Orange',1,0,'C');
// Line break
$this->Ln(20);
}
// Page footer
function Footer()
{
// Position at 1.5 cm from bottom
$this->SetY(-15);
// Arial italic 8
$this->SetFont('Arial','I',8);
// Page number
$this->Cell(0,10,'Page '.$this->PageNo(),0,0,'R');
}
}
// Create a new instance
$pdf = new PDF("P", "mm", "A4");
// Set some default options
$pdf->setAuthor($author);
$pdf->setTitle($title);
$pdf->AddPage();
$pdf->SetDisplayMode("real",'default');
$pdf->SetFont($font_family, '', $font_size);
// Field
$pdf->SetFont($font_family, 'B', $font_size);
$pdf->Cell(40, $height, "Position applied for:", 0, 0);
// Value
$pdf->SetFont($font_family, '', $font_size);
$pdf->Cell(60, $height, "Innovation Advisor (Job ID: 221)", 0, 0);
// Field
$pdf->SetFont($font_family, 'B', $font_size);
$pdf->Cell(40, $height, "Date of application:", 0, 0);
// Value
$pdf->SetFont($font_family, '', $font_size);
$pdf->Cell(50, $height, "17th July 2017", 0, 1);
$pdf->Output($file_name.$extension, $output);
On a separate page you have the output from a database query and variables for each field eg:
$name = "John";
$surname = "Smith";
Or more correctly...
$name = $row['name'];
My question is: should I post the already stored variables to a seperate script to generate the PDF or should it be on the same page?
Theoretically on button press you could call $pdf->Output();
Addition:
The variables displayed on the page are for viewing in the browser, then when a user would click convert to PDF it would simply grab these variables and use them with FPDF.
A similar example is how Google Analytics allows you to download a report as a PDF.

Given this flow:
Database values are displayed to end user
User reviews values and optionally generates the PDF files
... where the user is not allowed to edit the values (i.e. they aren't defaults but final ones), submitting them to the server does not make sense. The server already has direct access to such values, if you make them come from external sources they become untrusted input and you're forced to validate them.
Just make sure you have a reusable design so you don't need to implement the read values code twice.
In fact it's an anti-pattern I've actually seen in the wild now and then. In the worst case, it was a "Modify my profile" page that took user ID from the URL (rather than grabbing the ID of the currently validated user from session). Go figure the risk ;-)

Related

dompdf - text on a single page / page_script doesnt work

I'm using dompdf 0.7.0 and try to write down text in PHP on my pdf after rendering. I need text on specific pages and found the following from Answer from Brian
DomPDF {PAGE_NUM} not on first page
The function page_script sound like the correct answer.
I could check if loop is currently on page 3 or whatever.
Does I have to enable any options for this function?
Example:
$dompdf = new Dompdf( $options );
$dompdf->set_option('default_font', 'open sans');
$dompdf->set_option('fontHeightRatio', 1);
$dompdf->setPaper('A4')
$dompdf->set_option('enable_html5_parser', true);
$dompdf->set_option('enable_php', true);
$dompdf->loadHtml( $html );
$dompdf->render();
$canvas = $dompdf->get_canvas();
$canvas->page_script('
if ($PAGE_NUM > 1) {
$current_page = $PAGE_NUM-1;
$total_pages = $PAGE_COUNT-1;
$canvas->text(0, 0, "$current_page / $total_pages", "open sans condensed", 10, array(0,0,0));
}
');
It still be shown on my first page.
$canvas wouldn't be available from the page script as it is out of scope. The canvas object can be referenced inside your page script as $pdf.
Try the following page_script call instead:
$canvas->page_script('
if ($PAGE_NUM > 1) {
$current_page = $PAGE_NUM-1;
$total_pages = $PAGE_COUNT-1;
$font = $fontMetrics->getFont("open sans condensed", "normal"); // or bold, italic, or bold_italic
$pdf->text(0, 0, "$current_page / $total_pages", $font, 10, array(0,0,0));
}
};
There are a few variables available from within page scripts or embedded script:
$PAGE_NUM: current page number
$PAGE_COUNT: total number of pages
$pdf: the canvas object
$fontMetrics: an instance of the FontMetrics class
If you're using page text you have access to the following template variables:
{PAGE_NUM}: current page number
{PAGE_COUNT}: total number of pages
Note: Support for parsing embedded script or page scripts is disabled by default. Enable it with the following command: $dompdf->set_option("isPhpEnabled", true);. This must be done prior to calling $dompdf->render();.

PHP Insert multiple PDF's into PDF on specific page number

My problem is - A user can upload a PDF-File and now I want to add other (between 1 and n) single page PDF's after every Page of the user uploaded PDF.
For example a user uploads a PDF with 4 Pages and I have got 3 single page PDF's on my Webserver that I want to merge with the user PDF. The resulting PDF should then look like this:
Page 1: Page #1 from User uploaded PDF
Page 2: First Single-Page-PDF from Webserver
Page 3: Page #2 from User uploaded PDF
Page 4: Second Single-Page-PDF from Webserver
Page 5: Page #3 from User uploaded PDF
Page 6: Third Single-Page-PDF from Webserver
Page 7: Page #4 from User uploaded PDF
Page 8: First Single-Page-PDF from Webserver
So far I've tried it with PDFMerger
$pdf = new PDFMerger;
$pdf->addPDF('samplepdfs/userpdf.pdf', 'all')
->addPDF('samplepdfs/one.pdf', 'all')
->addPDF('samplepdfs/two.pdf', 'all')
->addPDF('samplepdfs/three.pdf', 'all')
->merge('file', 'xxx/result.pdf');
but this only adds the other PDF's at the end..
Is there a solution in PHP where I can specify the number of the page where the other PDF's shall be inserted?
You should avoid using the PDFMerger class. It is almost 6 (!!!) years old!
You can do the same with FPDI without much effort. Anyhow you should insert the pages in the order you want them to appear. So I guess it's more a logic problem. From what you'd written in your question I assume that you want to import a whole document while spreading another document with 3 pages between the imported pages. So a simple POC could look like this:
<?php
require_once("libs/fpdf/fpdf.php");
require_once("libs/fpdi/fpdi.php");
$pdf = new FPDI();
// let's prepare the static "filler pages"
$staticIds = array();
$pageCount = $pdf->setSourceFile('pdf/on/the/webserver.pdf');
for ($pageNumber = 1; $pageNumber <= $pageCount; $pageNumber++) {
$staticIds[$pageNumber] = $pdf->importPage($pageNumber);
}
// get the page count of the uploaded file
$pageCount = $pdf->setSourceFile('the/uploaded.pdf');
// let's track the page number for the filler page
$fillerPageCount = 1;
// import the uploaded document page by page
for ($pageNumber = 1; $pageNumber <= $pageCount; $pageNumber++) {
$tplId = $pdf->importPage($pageNumber);
$pdf->AddPage();
$pdf->useTemplate($tplId, null, null, 0, 0, true);
// add the current filler page
$pdf->AddPage();
$pdf->useTemplate($staticIds[$fillerPageCount], null, null, 0, 0, true);
// update the filler page number or reset it
$fillerPageCount++;
if ($fillerPageCount > count($staticIds)) {
$fillerPageCount = 1;
}
}
// done
$pdf->Output('xxx/result.pdf', 'F');

Why lines/images draw only on last page of pdf using dompdf in php

I am trying to draw line/image on every page of pdf using dompdf but it starts from second page, why this is so ? anyone has any idea ?
Here is my code
$dompdf = new DOMPDF();
$dompdf->load_html($message2);
$dompdf->set_paper('a4','portrait');
$dompdf->render();
$canvas = $dompdf->get_canvas();
//For Header
$header = $canvas->open_object();
$canvas->image($header_image1,'jpg',0, 0, 595, 100);
$canvas->line(0,100,595,100,array(0,0,0),1);
$canvas->close_object();
$canvas->add_object($header, "all");
//For Footer
$footer = $canvas->open_object();
$canvas->line(0,740,650,740,array(0,0,0),1);
$canvas->image($footer_image1,'jpg',0, 742, 595, 100);
$canvas->close_object();
$canvas->add_object($footer, "all");
$output = $dompdf->output();
this code draw line/image on pdf but it only display on last page.
I have two pages in pdf and my line/images are drawn on second page not on first page.
Please suggest any solution.
Adding objects in DomPDF works from the current page onwards. In other words, your objects will get added, but only from the page you currently have and then onwards to any new pages you add.
In your code, you've already converted your HTML to PDF, so the current page is more than likely the last page in your document. So your header / footer are added there, but not to any previous pages.
To place content on every page, domPDF provides two methods: page_text and page_script.
In your case the following type of code should do the trick:
$canvas->page_script('
$pdf->line(10,730,800,730,array(0,0,0),1);
');
Code in the page_script function is then executed for every PDF page.
The line is not displayed for me because embedded php was disabled.
This solved the problem:
$dompdf->set_option("isPhpEnabled", true);
This line has to be placed before $dompdf->render().
how to add image in all pdf page using header and footer.below is my code.
$pdf = App::make('dompdf');
$pdf->loadFile('invoice.html');
$pdf->output();
$dom_pdf = $pdf->getDomPDF();
$canvas = $dom_pdf ->get_canvas();
$image1="logo.png";
$canvas->image($image1,'png', 0, 0, 50, 25);
$canvas->page_text(10, 10, "Page {PAGE_NUM} of {PAGE_COUNT}", null, 10, array(0, 0, 0));
$pdf->save('pdf_report/eft_payment-'.$RandomAccountNumber.'.pdf');

FPDF Get page numbers at footer on Every A4 size page

I am creating PDF reports using FPDF. Now how do I generate page numbers on each page of a report at the bottom of the page.
Below is the sample code for generating a 2 page PDF.
<?php
require('fpdf.php');
$pdf = new FPDF();
$pdf->AliasNbPages();
$pdf->AddPage();
$pdf->SetFont('Arial','',16);
$start_x=$pdf->GetX();
$current_y = $pdf->GetY();
$current_x = $pdf->GetX();
$cell_width = 25; $cell_height=14;
$j = 20; // This value will be coming from Database so we dont know how many pages the report is going to be
for ($i = 0; $i<$j ; $i++){
$pdf->MultiCell($cell_width,$cell_height,'Hello1',1);
$current_x+=$cell_width;
$pdf->Ln();
}
$pdf->Output();
?>
Note : The $j value will be coming from the database so we don't know how many pages is the report going to be.
To add an A4 page, with portrait orientation, do:
$pdf->AddPage("P","A4");
Create a new class which extends the FPDF class, and override the pre-defined Footer method.
Example:
class PDF extends FPDF
{
function Footer()
{
// Go to 1.5 cm from bottom
$this->SetY(-15);
// Select Arial italic 8
$this->SetFont('Arial','I',8);
// Print centered page number
$this->Cell(0,10,'Page '.$this->PageNo(),0,0,'C');
}
}
According to my comment you can place
$pdf->PageNo();
on your page where ever you like. Also you can add a placeholder to this
$pdf->AliasNbPages();
What would look like
$pdf->AliasNbPages('{totalPages}');
By default it's {nb}. It's not necessary to add a placeholder
Than you could add the pagesum like
$pdf->Cell(0, 5, "Page " . $pdf->PageNo() . "/{totalPages}", 0, 1);
or without your own placeholder
$pdf->Cell(0, 5, "Page " . $pdf->PageNo() . "/{nb}", 0, 1);
this would produce e.g.
Page 1/10
in case there were 10 pages :)
But beware
Using the placeholder will mess up the width of the cell. So if you have e.g. 180 page-width than 90 isn't the mid anymore (In the line where you use the placeholder). You will see if you try :)

Dynamic GD image width text

I'm trying to spice up my website by using custom fonts for headings. For me, the most appropriate way to do this is using PHP and GD. I have written a little script which will output the dynamic text based on the $_GET value, however sometimes the image is too wide, which moves everything else about.
How can I get the image to adjust the width of it, based on the width of the text? Here is the code I've written so far:
<?php
// Settings
$sText = $_GET['t']; // Text of heading
$sFont = "font/AvantGarde-Book.ttf"; // Default font for headings
$sMain = $_GET['c'] ? $_GET['c'] : 0xF2AB27; // Get a font or default it
// Create the image
header("content-type: image/png"); // Set the content-type
$hImage = imagecreatetruecolor(200, 24);
ImageFill($hImage, 0, 0, IMG_COLOR_TRANSPARENT);
imagesavealpha($hImage, true);
imagealphablending($hImage, false);
imagettftext($hImage, 20, 0, 0, 24, $sMain, $sFont, $sText); // Draw the text
imagepng($hImage); // Generate the image
imagedestroy($hImage); // Destroy it from the cache ?>
Thanks!
Ok, I figured it out! For anyone else who may have this problem, you need to add:
// Calcuate the width of the image
$arSize = imagettfbbox(24, 0, $sFont, $sText);
$iWidth = abs($arSize[2] - $arSize[0]);
$iHeight = abs($arSize[7] - $arSize[1]);
Before the imagecreatetruecolor()
The function imagettfbbox will calculate the size of what the text will be based on the font you picked. Use the results in your call to imagecreatetruecolor.

Categories