Trying to Import PDF into FPDF/FPDI Adds Blank Page - php

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);
}

Related

pdf file output created with FPDF are empty (PHP)

Hi and thanks by advance for you helps.
I'm trying to write on a PDF with FPDF on PHP.
I'm actually working on WordPress.
If I'm using this code on my first website, it's working well:
if (isset($_GET["obtenir-mon-analyse"])){
$pdfFile = getcwd() . '/wp-content/themes/childtheme/ressources/PDF_analyse_template.pdf';
require_once('library/fpdf/fpdf.php');
require_once('library/fdpi/src/autoload.php');
// initiate FPDI
$pdf = new setasign\Fpdi\Fpdi();
// add a page
$pdf->AddPage("L");
// set the source file
$pdf->setSourceFile($pdfFile);
// 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 );
$pdf->Output('I');
}
But, with the same code on another website, the PDF generated by the output function is empty (0kb).
Also, the template is working because FDPF is well detecting the available page number.
PS:
The 2 website are hosting on the same host.
I have not any error.
I really don't know where is the problem.
Thanks a lot.
I think nobody will see this answer but:
On wordpress
With the plugin WP-optimize
If you use the mimify option on HTML, you will not be able to use FPDF

Edit PDF with Laravel [duplicate]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
Does anyone know of a good method for editing PDFs in PHP? Preferably open-source/zero-license cost methods. :)
I am thinking along the lines of opening a PDF file, replacing text in the PDF and then writing out the modified version of the PDF?
On the front-end
If you are taking a 'fill in the blank' approach, you can precisely position text anywhere you want on the page. So it's relatively easy (if not a bit tedious) to add the missing text to the document. For example with Zend Framework:
<?php
require_once 'Zend/Pdf.php';
$pdf = Zend_Pdf::load('blank.pdf');
$page = $pdf->pages[0];
$font = Zend_Pdf_Font::fontWithName(Zend_Pdf_Font::FONT_HELVETICA);
$page->setFont($font, 12);
$page->drawText('Hello world!', 72, 720);
$pdf->save('zend.pdf');
If you're trying to replace inline content, such as a "[placeholder string]," it gets much more complicated. While it's technically possible to do, you're likely to mess up the layout of the page.
A PDF document is comprised of a set of primitive drawing operations: line here, image here, text chunk there, etc. It does not contain any information about the layout intent of those primitives.
There is a free and easy to use PDF class to create PDF documents. It's called FPDF. In combination with FPDI (http://www.setasign.de/products/pdf-php-solutions/fpdi) it is even possible to edit PDF documents.
The following code shows how to use FPDF and FPDI to fill an existing gift coupon with the user data.
require_once('fpdf.php');
require_once('fpdi.php');
$pdf = new FPDI();
$pdf->AddPage();
$pdf->setSourceFile('gift_coupon.pdf');
// import page 1
$tplIdx = $this->pdf->importPage(1);
//use the imported page and place it at point 0,0; calculate width and height
//automaticallay and ajust the page size to the size of the imported page
$this->pdf->useTemplate($tplIdx, 0, 0, 0, 0, true);
// now write some text above the imported page
$this->pdf->SetFont('Arial', '', '13');
$this->pdf->SetTextColor(0,0,0);
//set position in pdf document
$this->pdf->SetXY(20, 20);
//first parameter defines the line height
$this->pdf->Write(0, 'gift code');
//force the browser to download the output
$this->pdf->Output('gift_coupon_generated.pdf', 'D');
If you need really simple PDFs, then Zend or FPDF is fine. However I find them difficult and frustrating to work with. Also, because of the way the API works, there's no good way to separate content from presentation from business logic.
For that reason, I use dompdf, which automatically converts HTML and CSS to PDF documents. You can lay out a template just as you would for an HTML page and use standard HTML syntax. You can even include an external CSS file. The library isn't perfect and very complex markup or css sometimes gets mangled, but I haven't found anything else that works as well.
Don't know if this is an option, but it would work very similar to Zend's pdf library, but you don't need to load a bunch of extra code (the zend framework). It just extends FPDF.
http://www.setasign.de/products/pdf-php-solutions/fpdi/
Here you can basically do the same thing. Load the PDF, write over top of it, and then save to a new PDF. In FPDI you basically insert the PDF as an image so you can put whatever you want over it.
But again, this uses FPDF, so if you don't want to use that, then it won't work.
Zend Framework can load and edit existing PDF files. I think it supports revisions too.
I use it to create docs in a project, and it works great. Never edited one though.
Check out the doc here
The PDF/pdflib extension documentation in PHP is sparse (something that has been noted in bugs.php.net) - I reccommend you use the Zend library.
Tcpdf is also a good liabrary for generating pdf in php
http://www.tcpdf.org/
We use pdflib to create PDF files from our rails apps. It has bindings for PHP, and a ton of other languages.
We use the commmercial version, but they also have a free/open source version which has some limitations.
Unfortunately, this only allows creation of PDF's.
If you want to open and 'edit' existing files, pdflib do provide a product which does this this, but costs a LOT
<?php
//getting new instance
$pdfFile = new_pdf();
PDF_open_file($pdfFile, " ");
//document info
pdf_set_info($pdfFile, "Auther", "Ahmed Elbshry");
pdf_set_info($pdfFile, "Creator", "Ahmed Elbshry");
pdf_set_info($pdfFile, "Title", "PDFlib");
pdf_set_info($pdfFile, "Subject", "Using PDFlib");
//starting our page and define the width and highet of the document
pdf_begin_page($pdfFile, 595, 842);
//check if Arial font is found, or exit
if($font = PDF_findfont($pdfFile, "Arial", "winansi", 1)) {
PDF_setfont($pdfFile, $font, 12);
} else {
echo ("Font Not Found!");
PDF_end_page($pdfFile);
PDF_close($pdfFile);
PDF_delete($pdfFile);
exit();
}
//start writing from the point 50,780
PDF_show_xy($pdfFile, "This Text In Arial Font", 50, 780);
PDF_end_page($pdfFile);
PDF_close($pdfFile);
//store the pdf document in $pdf
$pdf = PDF_get_buffer($pdfFile);
//get the len to tell the browser about it
$pdflen = strlen($pdfFile);
//telling the browser about the pdf document
header("Content-type: application/pdf");
header("Content-length: $pdflen");
header("Content-Disposition: inline; filename=phpMade.pdf");
//output the document
print($pdf);
//delete the object
PDF_delete($pdfFile);
?>

Keep only the first page of a PDF document with PHP

I have many PDFs that are generated and uploaded to my server.
The problem is they contain the same page three times (3 pages in total with the same content).
My goal is to edit the PDF with PHP so that it contains only one page.
Is there any library that allows me to simply load a PDF and keep only the first page?
Thank you!
Using FPDI, you can create a function to extract the first page of a PDF file:
function first_page ($path) {
$pdf = new FPDI();
$pdf->AddPage();
$pdf->setSourceFile($path);
$pdf->useTemplate($pdf->importPage(1));
return $pdf;
}
Then output the extracted PDF as you would do with FPDF:
// Extract first page from /path/to/my.pdf
// and output it to browser with filename "MyPDF".
first_page('/path/to/my.pdf')->Output('MyPDF', 'I');
FPDF (http://www.fpdf.org/) or MDPF (http://www.mpdf1.com/mpdf/index.php) are great libraries for work with PDF files. I have experiences only with creating PDF; but I assume that one of those libraries can solve your problem.
Edit: Here is some example with FPDF
https://gist.github.com/maccath/3981205

Modify first page of PDF file in PHP [duplicate]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
Does anyone know of a good method for editing PDFs in PHP? Preferably open-source/zero-license cost methods. :)
I am thinking along the lines of opening a PDF file, replacing text in the PDF and then writing out the modified version of the PDF?
On the front-end
If you are taking a 'fill in the blank' approach, you can precisely position text anywhere you want on the page. So it's relatively easy (if not a bit tedious) to add the missing text to the document. For example with Zend Framework:
<?php
require_once 'Zend/Pdf.php';
$pdf = Zend_Pdf::load('blank.pdf');
$page = $pdf->pages[0];
$font = Zend_Pdf_Font::fontWithName(Zend_Pdf_Font::FONT_HELVETICA);
$page->setFont($font, 12);
$page->drawText('Hello world!', 72, 720);
$pdf->save('zend.pdf');
If you're trying to replace inline content, such as a "[placeholder string]," it gets much more complicated. While it's technically possible to do, you're likely to mess up the layout of the page.
A PDF document is comprised of a set of primitive drawing operations: line here, image here, text chunk there, etc. It does not contain any information about the layout intent of those primitives.
There is a free and easy to use PDF class to create PDF documents. It's called FPDF. In combination with FPDI (http://www.setasign.de/products/pdf-php-solutions/fpdi) it is even possible to edit PDF documents.
The following code shows how to use FPDF and FPDI to fill an existing gift coupon with the user data.
require_once('fpdf.php');
require_once('fpdi.php');
$pdf = new FPDI();
$pdf->AddPage();
$pdf->setSourceFile('gift_coupon.pdf');
// import page 1
$tplIdx = $this->pdf->importPage(1);
//use the imported page and place it at point 0,0; calculate width and height
//automaticallay and ajust the page size to the size of the imported page
$this->pdf->useTemplate($tplIdx, 0, 0, 0, 0, true);
// now write some text above the imported page
$this->pdf->SetFont('Arial', '', '13');
$this->pdf->SetTextColor(0,0,0);
//set position in pdf document
$this->pdf->SetXY(20, 20);
//first parameter defines the line height
$this->pdf->Write(0, 'gift code');
//force the browser to download the output
$this->pdf->Output('gift_coupon_generated.pdf', 'D');
If you need really simple PDFs, then Zend or FPDF is fine. However I find them difficult and frustrating to work with. Also, because of the way the API works, there's no good way to separate content from presentation from business logic.
For that reason, I use dompdf, which automatically converts HTML and CSS to PDF documents. You can lay out a template just as you would for an HTML page and use standard HTML syntax. You can even include an external CSS file. The library isn't perfect and very complex markup or css sometimes gets mangled, but I haven't found anything else that works as well.
Don't know if this is an option, but it would work very similar to Zend's pdf library, but you don't need to load a bunch of extra code (the zend framework). It just extends FPDF.
http://www.setasign.de/products/pdf-php-solutions/fpdi/
Here you can basically do the same thing. Load the PDF, write over top of it, and then save to a new PDF. In FPDI you basically insert the PDF as an image so you can put whatever you want over it.
But again, this uses FPDF, so if you don't want to use that, then it won't work.
Zend Framework can load and edit existing PDF files. I think it supports revisions too.
I use it to create docs in a project, and it works great. Never edited one though.
Check out the doc here
The PDF/pdflib extension documentation in PHP is sparse (something that has been noted in bugs.php.net) - I reccommend you use the Zend library.
Tcpdf is also a good liabrary for generating pdf in php
http://www.tcpdf.org/
We use pdflib to create PDF files from our rails apps. It has bindings for PHP, and a ton of other languages.
We use the commmercial version, but they also have a free/open source version which has some limitations.
Unfortunately, this only allows creation of PDF's.
If you want to open and 'edit' existing files, pdflib do provide a product which does this this, but costs a LOT
<?php
//getting new instance
$pdfFile = new_pdf();
PDF_open_file($pdfFile, " ");
//document info
pdf_set_info($pdfFile, "Auther", "Ahmed Elbshry");
pdf_set_info($pdfFile, "Creator", "Ahmed Elbshry");
pdf_set_info($pdfFile, "Title", "PDFlib");
pdf_set_info($pdfFile, "Subject", "Using PDFlib");
//starting our page and define the width and highet of the document
pdf_begin_page($pdfFile, 595, 842);
//check if Arial font is found, or exit
if($font = PDF_findfont($pdfFile, "Arial", "winansi", 1)) {
PDF_setfont($pdfFile, $font, 12);
} else {
echo ("Font Not Found!");
PDF_end_page($pdfFile);
PDF_close($pdfFile);
PDF_delete($pdfFile);
exit();
}
//start writing from the point 50,780
PDF_show_xy($pdfFile, "This Text In Arial Font", 50, 780);
PDF_end_page($pdfFile);
PDF_close($pdfFile);
//store the pdf document in $pdf
$pdf = PDF_get_buffer($pdfFile);
//get the len to tell the browser about it
$pdflen = strlen($pdfFile);
//telling the browser about the pdf document
header("Content-type: application/pdf");
header("Content-length: $pdflen");
header("Content-Disposition: inline; filename=phpMade.pdf");
//output the document
print($pdf);
//delete the object
PDF_delete($pdfFile);
?>

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