Replicating text with FPDF and setting page size - php

I'm using FPDF. The class is implemented and working in its most basic form. I created a business card (3.5" x 2") and placed it on an 8.5" x 11" page. The card is replicated 10 times on a single page.
Here is what I'm trying to do:
Replicate a variable 10 times and define a custom offset for each (string prints at the bottom of each card)
Change the page size from $unit='mm', $size='A4' to $unit='inch', $size='letter'. Doing so gives me an error FPDF error: Incorrect unit: inch
The code I'm working with is below:
switch($_POST['picker']){
case 'option1':
// initiate FPDI
$pdf = new FPDI();
// add a page
$pdf->AddPage();
// set the sourcefile
$pdf->setSourceFile('10-up.pdf');
// import page 1
$tplIdx = $pdf->importPage(1);
// use the imported page and place it at point 10,10 with a width of 100 mm
$pdf->useTemplate($tplIdx, 0, 0, 216, 279);
// now write some text above the imported page
$pdf->SetFont('Arial');
$pdf->SetTextColor(0,0,0);
$pdf->SetXY(12, 12);
//This is the variable I want to repeat 10 times and define custom offsets for each
$pdf->Write(0, $user);
$pdf->Output('final.pdf', 'D');
break;
The documentation I've read seems really limited. If you know of any good documentation, please let me know. Thanks.

In case anyone else is having the same problem, here is the answer for the second part of my question:
You have to set the page size here...
$pdf->AddPage('P', 'Letter');
This defines the page as "Portrait" , "Letter"
I'm still looking for an answer on part one. If anyone can help, I'd appreciate it.

There is this undocumented function in the class FPDF also called FPDF.
function FPDF($orientation='P', $unit='mm', $size='A4') { ... }
I used it this way (– please note that the $pdf object is a child class of FPDF class. This could, for instance, be an FPDI object; When it is defined as an FPDI object, it is defined in the same way as in your original question, where $pdf is an FPDI object):
$pdf = new FPDI();
$pdf->FPDF('L' /* =$orientation */, 'pt' /* =$unit */, 'A4' /* =$size */);
So, in this code example an object of a class that is derived from the FPDF class is calling the FPDF function of the FPDF class to set the orientation of the PDF document and sets the unit to 'pt' (= points) and the size to DIN A4, which is the standard letter format in Germany.

You do it where you initiate the constructor, where you currently have $pdf = new FPDI()
$pdf = new FPDF('P', 'in', 'Letter');
P - sets the document up as portrait
in - sets the unit up as inches
Letter - sets the document size as US Letter
http://www.fpdf.org/en/doc/fpdf.htm

Related

Trying to Import PDF into FPDF/FPDI Adds Blank Page

I'm new to using FPDF / FPDI. My predecessor here extended the FPDF class and I'm adding onto his code to edit his PDFs and make new ones. I've been able to create the first 3 pages of a PDF I want to make by writing values from my database into blank pages, using FPDF. All good!
Now I want to import an existing single page PDF as page 4 and write some stuff on it, and it looks like I need FPDI to do that.
I used the example here: https://www.setasign.com/products/fpdi/about as suggested by another post. However, it's just adding a blank page to the end of my PDF.
I've written the path of the PDF I want to import into my log and ensured that it is correct (I'm not getting any errors in the php log either, which I would expect if the pdf was not found).
I'm initializing the pdf as FPDF, not FPDI, so that may be the issue? But if I initialize it as FPDI then I get an error that my methods are undefined, because they are defined extending the FPDF class. So I'm not sure how to do what I want...do I need to redefine my classes to extend FPDI? I'm just worried this will break the PDFs already being created using some of the same methods. I'm also not getting any errors about using FPDI methods like useImportedPage...so I feel like maybe that's not the issue?
Sorry if I'm not explaining this well, let me know if you have questions. Here is the relevant code:
require_once(APPPATH.'libraries/fpdf/fpdf.php');
require_once(APPPATH.'libraries/fpdi/autoload.php');
require_once(APPPATH.'libraries/fpdi/Fpdi.php');
public function make_fieldpacketMA(){
$plotID=$this->input->get('PlotID');
$year=$this->input->get('Year');
$pdf = new PDF('P','in','Letter');
// Make additional info first page- this works!
$additional_info=$this->fhm_model->get_additionalplotinfo($plotID, "MA");
$pdf->AdditionalInfoSheet($additional_info, $pdf);
//make plot info pages (same as subplot info pages on VT style plots)- this works!
$plotInfo=$this->fhm_model->get_sheetinfoMA($plotID,$year);
$pdf->SubplotSheet($plotInfo, "MA", $pdf);
//make seedling sheet from existing template- this does not work
$seedlingInfo=$this->fhm_model->get_seedlingInfo($plotID, $year);
$pdf->SeedlingSheet($seedlingInfo, $pdf);
//Write the output
$rand=uniqid();
$filename='./fhm_sheets/PlotPacket_'.$rand.'.pdf';
$pdf->Output($filename,"F");
$this->load->helper('download');
$data = file_get_contents($filename);
force_download($plotID.'_'.($year+1).'_FHMPlotPacket.pdf',$data);
}
//Create PDF creation class
class PDF extends PDF_Rotate{
function SeedlingSheet($seedlingInfo=array()) {
$pageCount = $this->setSourceFile(FCPATH.'fhm_template/MAFHM_Microplot_SeedlingForm.pdf');
$pageId = $this->importPage(1);
$this->AddPage();
// $this->useTemplate($pageId);
$this->useImportedPage($pageId, 10, 10, 90);
}
This works! Looks like I needed a second argument for importPage to define the bounding box
function SeedlingSheet($seedlingInfo=array()) {
$pageCount = $this->setSourceFile(FCPATH.'fhm_template/MAFHM_Microplot_SeedlingForm.pdf');
$pageId = $this->importPage(1, \setasign\Fpdi\PdfReader\PageBoundaries::MEDIA_BOX);
$this->AddPage();
$this->useTemplate($pageId, 0, 0);
}

Class 'setasign\Fpdi\FpdfTpl' not found

everyone I am working with fpdf an fpdi, is my first work and I have a problem. I can not edit a pdf. This is the problem. thanks
Class setasign\Fpdi\FpdfTpl not found in C:\wamp\www\Ale\fpdi\src\Fpdi.php
use setasign\Fpdi\Fpdi;
require_once('fpdf/fpdf.php');
require_once('fpdi/src/Fpdi.php');
require_once('fpdi/src/autoload.php');
// initiate FPDI
$pdf = new Fpdi();
// add a page
$pdf->AddPage();
// set the source file
$pdf->setSourceFile('documento.pdf');
// import page 1
$tplIdx = $pdf->importPage(1);
// use the imported page and place it at position 10,10 with a width of 100 mm
$pdf->useTemplate($tplIdx, 10, 10, 100);
// now write some text above the imported page
$pdf->SetFont('Helvetica');
$pdf->SetTextColor(255, 0, 0);
$pdf->SetXY(30, 30);
$pdf->Write(0, 'This is just a simple text');
$pdf->Output('newDoc.pdf','F');
You cannot edit a PDF with FPDI!
Remove the line:
require_once('fpdi/src/Fpdi.php');
...to give the later required autoload function a chance.
Maybe not related to this exact question but I had a similar situation in my Lumen project...
I resolved it by reintsalling vendor files. I hope if someone is facing similar situation, I hope this helps.

Adding pages from an external pdf using TCPDF and FPDI

I am creating a pdf document using tcpdf which is going well. The issue I am having is that I want to include an external pdf in the middle of the document and then continue to add my own pages afterwards.
I have read that FPDI is the best way to achieve this but I am stuck with trying to implement a solution. All of the examples I have found seem to revolve around using an external pdf as a background or template to the entire document, not just as an insert into a document.
Any help would be gratefully received.
AddPage() Method generates a blank page. Each call generates only 1 page. You need to call AddPage() before useTemplate(); After that you can still add new context.
$pdf = new FPDI();
$pdf->AddPage();
$pdf->AddFont('courier');
$pdf->Write(10, 'page 1 created by TCPDF');
$pages = $pdf->setSourceFile('middle.pdf');
for($i=0; $i<$pages; $i++)
{
$pdf->AddPage();
$tplIdx = $pdf->importPage($i+1);
$pdf->useTemplate($tplIdx, 10, 10, 200);
}
$pdf->AddPage();
$pdf->Write(10, 'page 2 created by TCPDF');

Problem with size of the imported PDF template with FPDI+TCPDF

I am stuck in a very complex situation.
I am working on a PHP Web apps for Greeting card.
For this, I am using some Linux tools and TCPDF and FPDI.
Let me tell you how it all works:
there is 4 page greeting card template PDF file. this is custom size 5x7 inches 300dpi PDF file.
I have added custom size in TCPDF as well
case 'STANDARD_CARD' : {$pf = array(1500.00,2100.00);break;}
what i do is, i use:
pdftk templateX.pdf burst output page_%2d.pdf
to separate each page of temple.
now I use :
$pdf = new FPDI($cardDetails['ORIENTATION'],"mm",$cardDetails['SIZE']);
//set source file for
$pdf->setSourceFile($pdfFile);
$templateIndex = $pdf->importPage(1);
$pdf->AddPage($cardDetails['ORIENTATION'],$cardDetails['SIZE']);
$pdf->useTemplate($templateIndex,0,0);
other things like, writing message printing images. and at the end save the file using:
$pdf->output("file_name.pdf","F");
original PDF file (1st page only): (5x7 inches)
Original pdf file
Modified PDF and some PDF operations : (29x20 inches)
modified PDF
now the output I am getting is not 5x7 pdf it is a 29 x 20 inches file and that destroying my calculation and PDF as well.
Please tell me what I am doing wrong...
Hi Ravish,
I encountered also this issue. Actually my scenario is this. I have an original file which is a Legal size (8.5mm x 14mmmm). When I an displaying it using the FPDI output as you did, it only display a letter size(8.5mm x 11mm). So the result is: CROPPED PDF file.
I made several googling and found several answers too from different posts. Here is the most relevant solution that I found.
First is this piece of function code below: useTemplate
$this->useTemplate($templateIndex, null, null, 0, 0, true);
Normally, some developers set this as TRUE for the last argument. Yes, it is correct if you dont set the width and lenght. However, I would like to emphasize that the 4th and 5th argument specifies the width and length of an imported PDF. So, if you will adopt or get the actual size of the imported document, set the last argument to FALSE as this will tell that it will take the actual or specific size you set.
Please take this sample codes I did:
$pdf = new FPDI();
$pdf -> setSourceFile('birform2316.pdf');
$tplIdx = $pdf -> importPage(1);
$size = $pdf->getTemplateSize($tplIdx);
$pdf -> AddPage();
$pdf ->useTemplate($tplIdx, null, null, $size['w'], 310, FALSE);
$pdf -> SetFont('Arial');
$pdf -> SetTextColor(0, 0, 0);
$pdf -> SetXY(18, 174);
$pdf -> Write(0, $employer_address);
$pdf -> Output('myOwn.pdf', 'D');
With this code, I have produced a new PDF WITHOUT CROPPING the imported file that I set. Meaning, all details of the template(the original file) has been displayed.
Please take note also that I observed something while setting the size of my PDF:
First, my file has an original width of 215.6mm and its length is 350.9mm. Now when I set the size of my PDF using the functions getTemplateSize and useTemplate such as:
$size = $pdf->getTemplateSize($tplIdx);
$pdf ->useTemplate($tplIdx, null, null, $size['w'], $size['h'],FALSE);
or simply:
$pdf ->useTemplate($tplIdx, null, null, 215.6, 350.9,FALSE);
The result is, my new PDF file is CROPPED at the bottom and I dont know why.
With this observation, I made several tests to find out the reason. And the result that came up is, there is a limit of length in generating a PDF file using FPDI. As you can see in my code above, I did not use the actual length of my file. Instead of using 350.9mm which can be derived from $size[h'], I did not use it as it will give a cropped file. I just passed a numeric value near to it and the actual width to produce the desired result.
$pdf->useTemplate($tplIdx, null, null, $size['w'], 310, false);
By the way, 310 mm (length) is the largest numeric value I have used to produce a new PDF file which is NOT CROPPED.
I hope I have given some inputs to all developers using FPDI which encounters the problem of CROPPED PDF results.
Thanks to all...
Levi Palmer
Instead of
$pdf->useTemplate($templateIndex,0,0);
use
$this->useTemplate($templateIndex, null, null, 0, 0, true);
The last argument $adjustPageSize is set to 'false' by default.
I had same problem. My pdf was cropped from right, and from the bottom FDPI was adding space.
I found that my pdf had width=215 and height=279, while FPDI was exporting every time 210x297.
useTemplate function can scale your pdf to certain size, but output will still remain 210x297.
So I left useTemplate with default values and "adjustPageSize"=true:
$pdf->useTemplate($templateId, 0, 0, 0, 0, true);
What is need to be changed is output dimensions, in order to match original size:
$templateSize = $pdf->getTemplateSize($templateId);
$pdf->AddPage('', [$templateSize['w'], $templateSize['h']]);
If you are going to upload landscape oriented pdfs, you must set orientation:
$templateSize = $pdf->getTemplateSize($templateId);
$orientation = $templateSize['w'] > $templateSize['h'] ? 'L' : 'P';
$pdf->AddPage($orientation, [$templateSize['w'], $templateSize['h']]);

How to make business card with fpdf or tcpdf or others? When i have a jpg background and text overlap requires?

I have a jpg image for the business card layout with dimensions: 9,8 cm/5,9 cm. I have to put it as background layout and on top of this layout i have to print name/address/telephone number email etc. And print it/save it as pdf for later use.
But problem is i cant make it work with FPDF or TCPDF. Any idea how can i prepare this? with FPDF or TCPDF?
Using TCPDF you can position elements absolutely as it were, so you could do something like
$pdf = new TCPDF('L', 'mm', 'A4'); //Or whatever your required settings are
//Basic setup
$pdf->setPrintHeader(false);
$pdf->setPrintFooter(false);
$pdf->AddPage();
$pdf->Image('src', x, y); //Where x and y are the offset (probably 0, 0)
$pdf->writeHTMLCell(w, h, x, y, 'html') //Again where x and y are offset
$pdf->Output('filename.pdf', 'D'); //To force download
The TCPDF online documentation isn't great, but the examples help a lot http://www.tcpdf.org/examples.php
You specifically asked about creating a business card sized document, so you should use:
//Sets document size to a 5.9cm x 9.8cm landscape oriented page
$pdf = new TCPDF('L', 'mm', array(59,98));
The documentation gives a list of pre-defined page sizes here: http://www.tcpdf.org/doc/classTCPDF.html#a087d4df77e60b7054e97804069ed32c5
The example n. 51 at http://www.tcpdf.org shows how to create a full page background.
Then, for the page format, check the source code documentation of the getPageSizeFromFormat() method (more than 300 page formats are already defined, including business cards).
To set the background on fpdf you have to call Image() as the first thing when setting up the Header() function in your class.
The way I normally do it is by extending Extend FPDF in my own class, i.e.:
require('path/to/fpdf.php);
class SomeClassName extends FPDF {
// add your instance variables if needed
....
function Header(){
//now call Image()
$this->Image(); //set up your background here
...
}
}
If you look at faqs in the fpdf.org site you will see (vague) instructions on how to do this.
There is a library which implements FPDF called FPDI. To create custom paper sizes, like business cards, which typically use CR80 with dimensions of 54mm x 86mm, you can directly add this size into the class constructor of fpdf.php at stdPageSizes as this: 'cr80'=>array(152.82,243.38). This entry already exists so just add this custom one. Your complete definition will be something like this:
$this->StdPageSizes = array('a3'=>array(841.89,1190.55), 'a4'=>array(595.28,841.89), 'a5'=>array(420.94,595.28), 'letter'=>array(612,792), 'legal'=>array(612,1008), 'cr80'=>array(152.82,243.38));
Your calls, if using FPDI, will now be something like this:
$pdf = new Fpdi();
$pdf->AddPage('L','cr80'); //note our custom name
Note that even though the right size of CR80 is 54x86mm, it seems that the right settings require that these values be multiplied by 2.83 - tested. I hope this helps in code shortenings and quick reuse.

Categories