good evening ! I need your help, I am trying to generate several PDFs with the TCPDF, I have been able to create a PDF one by one by passing the ID of the database to the function, but what I need is for it to automatically create several PDFs for each ID that it brings from the database, how can I achieve this?
Controller:
public function reportpdf($id){
ob_start();
$allowance= $this->allowance_m->get_allowance_byid($id);
$this->load->library('tcpdf');
$pdf = new
TCPDF('P','mm','A4',true,'UTF-8',false);
$pdf->AddPage();
$pdf->setXY(12,40);
$txt_pembuka = 'Allowance Report';
//$pdf->SetFontSize(16);
$pdf->SetFont('times', 'B', 16, '', 'false');
$pdf->MultiCell(0, 5, $txt_pembuka, 0, 'C', 0, 2, '', '', true);
$pdf->setXY(20,$pdf->getY()+7);
$pdf->SetFont('times', '', 12, '', 'false');
$pdf->cell(35,5,"Nama");
$pdf->cell(0,5,": ".$allowance->tarjeta);
$pdf->setXY(20,$pdf->getY()+7);
$pdf->cell(35,5,"Periode");
$periode = strtotime($allowance->monto);
$formatperiode = date('F Y',$periode);
$pdf->cell(0,5,": ".$formatperiode);
$pdf->setXY(20,$pdf->getY()+7);
$pdf->cell(35,5,"Uang Makan");
$pdf->cell(0,5,": Rp.".$allowance->nombre);
$pdf->Output();
ob_end_flush();
}
Model:
public function get_allowance_byid($id)
{
$db6 = $this->load->database('db6', TRUE);
$sql = "SELECT * FROM registros WHERE tarjeta='".$id."'";
return $db6->query($sql)->row();
}
If you want to create "several PDFs for each ID" it is recommended to first save the created PDF files in a local folder on your server before making them available to your user instead of prompting the created PDF directly in the browser as in your example. It is not practical to send multiple PDFs at once to the browser.
Add a path and a filename to the Output Method to save the PDF, preferably with an ID so you can find it again:
$pdf->Output('allowance_report_'.$id.'.pdf');
Documentation: https://tcpdf.org/docs/srcdoc/TCPDF/classes-TCPDF/#method_Output
In your case, you can either create multiple PDFs inside the method reportpdf() or make a new method for each file.
If you choose to do it inside your current method you can do something like:
public function reportpdf($id){
$allowance= $this->allowance_m->get_allowance_byid($id);
$this->load->library('tcpdf');
//CREATE YOUR FIRST PDF....
$pdf = new
TCPDF('P','mm','A4',true,'UTF-8',false);
$pdf->AddPage();
... ETC ...
// SAVE THE FIRST PDF BY PROVIDING A PATH AND A FILENAME
$pdf->Output('folder/allowance_report_'.$id.'.pdf');
//CREATE YOUR SECOND PDF....
$pdf = new
TCPDF('P','mm','A4',true,'UTF-8',false);
$pdf->AddPage();
... ETC ...
// SAVE THE SECOND PDF BY PROVIDING A PATH AND A FILENAME
$pdf->Output('folder/another_report_'.$id.'.pdf');
}
If you then want to send the PDFs to the browser I suggest you create a zip file containing all the created PDFs and prompt it through the browser.
Related
I'm trying with PHP to fill form fields on an existing PDF and add an image to it.
I found the FPDM library to fill the form fields:
$formInputArray = ['field1' => 'test value', 'field2' => 'second value'];
$pdf = new FPDM('orginal-file.pdf');
$pdf->getEntries($templatePDF, 'PDF');
$pdf->Load($formInputArray);
$pdf->Merge();
$pdf->Output('F', 'form-filled-file.pdf');
That works so far.
In the next step i try to add an image with the Fpdi class to the edited document:
$pdf = new Fpdi();
$pdf->setSourceFile('form-filled-file.pdf');
$pageId = $pdf->importPage(1, \setasign\Fpdi\PdfReader\PageBoundaries::MEDIA_BOX);
$pdf->addPage();
$pdf->useTemplate($pageId);
$pdf->Image('test-image.jpg', 150*0.39, 150*0.39, 100*0.39);
$pdf->Output('F', 'finished-file.pdf');
The problem is, that Fpdi is converting the template pdf structure into an new pdf structure. So all given form fields are gone.
So the question is:
How can i add an image to an existing PDF with form fields?
I also looked at the iText / PDFtk (Serverside) and the mPDF PHP library, but they are not the right one because of the GPL license.
Is there an other way or an other library to fill form fields and add an image to an PDF in PHP?
We (Setasign - also author of FPDI) offer a commercial solution for both tasks: Filling PDF forms and fill fields with images in pure PHP.
If you'd used FPDM you was only able to fill in text fields. A replacement would be the SetaPDF-FormFiller Lite Component. The Full version would allow you to fill in also other field types such as checkboxes or radiobutton groups.
A simple example of filling a single text field and an additional field with an image would be:
<?php
require_once('library/SetaPDF/Autoload.php');
// or if you use composer require_once('vendor/autoload.php');
// create a file writer
$writer = new SetaPDF_Core_Writer_File('image-in-form-field.pdf');
// get the main document instance
$document = SetaPDF_Core_Document::loadByFilename($filename, $writer);
// now get an instance of the form filler
$formFiller = new SetaPDF_FormFiller($document);
// Get the form fields of the document
$fields = $formFiller->getFields();
// Let's fill a field
$fields['Text Field']->setValue("Some example text.");
// Now prepare an appearance for the Logo field
// First of all let's get the annotation of the form field
$annotation = $fields['Logo']->getAnnotation();
// Remember the width and height for further calculations
$width = $annotation->getWidth();
$height = $annotation->getHeight();
// Create a form xobject to which we are going to write the image.
// This form xobject will be the resulting appearance of our form field.
$xobject = SetaPDF_Core_XObject_Form::create($document, array(0, 0, $width, $height));
// Get the canvas for this xobject
$canvas = $xobject->getCanvas();
// Let's create an image xobject
$image = SetaPDF_Core_Image::getByPath('Logo.png')->toXObject($document);
// scale image into available space and align in the center
if ($image->getHeight($width) >= $height) {
$image->draw($canvas, $width / 2 - $image->getWidth($height) / 2, 0, null, $height);
} else {
$image->draw($canvas, 0, $height / 2 - $image->getHeight($width) / 2, $width);
}
// Now add the appearance to the annotation
$annotation->setAppearance($xobject);
// Flatten all appearances to the pages content stream
$fields->flatten();
// finish the document
$document->save()->finish();
This script is a short version of this demo.
I am using TCDPF to generate barcode in invoice. Thus, when I download invoice by clicking "View Invoice" from Orders page, it should download with a barcode generated. At the moment, I am just testing a random number.
In HTMLTemplateInvoice.php, I added the following codes:
// Random number for testing
$barcodeobj = new TCPDFBarcode('1234567890123', 'C39');
// Assign to template
// All other unnecessary variables not displayed
'barcode' => base64_encode($barcodeobj->getBarcodePNG(1, 30, array(255,255,255))),
);
For testing purpose, I added the following codes in invoice.addresses.tab.tpl
<img src="data:image/png;base64,{$barcode}>">
The barcode is displayed. Unfortunately, it is dislaying as a page and it is not generated in the invoice. The invoice will not download too.
I am using Prestashop 1.7.4.2 and upgraded to PHP 7.2.
I've tried this code
$barcodeobj = new TCPDFBarcode("123456789123", 'C39');
$Barcode = $barcodeobj->getBarcodePngData(2, 40, array(0,0,0));
and then i created a new pdf :
$Barcode_pdf = new TCPDF('P', 'mm', 'A5', true, 'UTF-8', false);
$Barcode_pdf->SetMargins(7, 10.4, 8);
$Barcode_pdf->setImageScale(0.5);
$Barcode_pdf->AddPage();
$Barcode_pdf->Image('#'.$Barcode,'10','20','60' );
$Barcode_pdf->Output('Barcode.pdf', 'I')
you can attach it to email if you want but change the output type to 'S':
$Barcode_attachment = array();
$Barcode_attachment['content'] = $Barcode_pdf->Output('Barcode.pdf', 'S');
$Barcode_attachment['name'] = 'Barcode.pdf'; // getting pdf file name
$Barcode_attachment['invoice']['mime'] = 'application/pdf';
$Barcode_attachment['mime'] = 'application/pdf';
and then just add $Barcode_attachment to your email .
In my Certificate plugin in Moodle, I can choose from 4 signatures. The signature images are shown in the certificate and loaded trough CERT_IMAGE_SIGNATURE:
certificate_print_image($pdf, $certificate, CERT_IMAGE_SIGNATURE, $sigx, $sigy, '', '');
The file names are jacob.png vanessa.png stan.png `lilly.png.
How to add automatically text under the image? For example the names of the person from the signature image?
If I choose the file jacob.png from the dropdown list, It should load under the image also the names, here "Jacob Svenson".
I would do something like this
in /mod/certificate/type/xxx/certificate.php
if (!empty($certificate->printsignature)) {
certificate_print_image($pdf, $certificate, CERT_IMAGE_SIGNATURE, $sigx, $sigy, '', '');
$signame = get_string($certificate->printsignature, 'certificate');
certificate_print_text($pdf, $x, $y + 20, 'C', $fontserif, '', 20, $signame);
}
and in /mod/certificate/lang/en/certificate.php use the file name as the string id.
$string['jacob.png'] = 'Jacob Svenson';
I am facing an issue while editing the existing pdf.
Here I have a pdf where I just want to add a employee name on the first line of every page in pdf.
But when I try to do this using fpdf and fpdi then it will save the new pdf with employee name and all the other data has been removed from the pdf.
Here is the code which I am using for editing and saving a pdf.
<code>
<?php
define('FPDF_FONTPATH','font/');
require_once('fpdf.php');
require_once('fpdi.php');
$pdf = new FPDI();
// add a page
$pdf->AddPage();
// set the sourcefile
$pagecount = $pdf->setSourceFile('upload/linebreak.pdf');
// import page 1
$tplidx = $pdf->importPage(1);
for ($i = 1; $i < $pagecount; $i++) {
$tplidx = $pdf->ImportPage($i);
$pdf->useTemplate($tplidx, 10, 10, 200);
$pdf->AddPage();
$pdf->SetFont('Arial');
$pdf->SetTextColor(0,0,0);
$pdf->SetFontSize(8);
if ($i>=1) {
//$pdf->SetXY(50, 124);
$pdf->Write(1, "Emp Name : Sanjay Singh");
}
}
$pdf->Output("upload/new_linebreak_pdf.pdf", "F");
?>
<code>
My linebreak.pdf have data some thing like this (This is the employee rule for our organization..........This is the employee rule for our organization......This is the employee rule for our organization.....This is the employee rule for our organization....This is the employee rule for our organization)
On this I want to add a Employee Name on the first line but after editing it will generate new pdf like this(Emp Name : Sanjay Singh)
Where other data which is already their will get deleted.
Thanks In Advance !
Your problem is that you're calling methods for FPDI in the wrong order. Here are the steps to take:
Import the page you want to modify, get the template
Add a new blank page to the document
Load the template into that document
Write additional content to that document
Here is a brief code example illustrating the above concept. I have tested this and gotten the output expected.
$pdf = new FPDI();
$pageCount = $pdf->setSourceFile('file.pdf');
// Iterate through every page
for( $pageNo=1; $pageNo<=$pageCount; $pageNo++ )
{
// Import page
$templateId = $pdf->importPage($pageNo);
$pdf->getTemplateSize($templateId);
$pdf->addPage('P');
$pdf->useTemplate($templateId);
// Modify page
$pdf->SetFont('Arial');
$pdf->SetTextColor(0,0,0);
$pdf->SetFontSize(8);
$pdf->Text(50,124,"Emp Name : Sanjay Singh");
}
$pdf->Output("upload/new_linebreak_pdf.pdf", "F");
I'm wondering if there's a keep together function for TCPDF. I have one for FPDF, but I can't get it to work in TCPDF.
Here's how I see it working within the PDF generation code:
// ... PDF code/stuff
// while not kept together
// add PDF stuff that should be kept together
// .. more PDF code/stuff
I'm thinking the function would return false if the a new page was added, roll back and then do the while loop again.
I do have the following working, but I'd rather it was in a function/method of TCPDF so it was more reusable:
$pdf->startTransaction();
$block_page = $pdf->getPage();
$print_block = 2; // max 2 tries
while ($print_block > 0) {
// do PDF stuff
if ($pdf->getPage() == $block_page) {
$print_block = 0;
} else {
// rollback
$pdf = $pdf->rollbackTransaction();
$pdf->AddPage();
$block_page = $pdf->getPage();
-- $print_block;
}
}
It would also be cool if it didn't depend on the built in transaction functionality so transactions can be used within the loop, since things like writeHTML() use transactions.
I wanted similar functionality and settled on using transactions. This on TCPDF version 5.9.125.
I inherited my own PDF class from TCPDF and added my own method:
public function writeHTMLTogether($html, $ln=true, $fill=false, $reseth=false, $cell=false, $align='') {
$cp = $this->getPage();
$this->startTransaction();
$this->writeHTML($html, $ln, $fill, $reseth, $cell, $align);
if ($this->getPage() > $cp) {
$this->rollbackTransaction(true);//true is very important
$this->AddPage();
$this->writeHTML($html, $ln, $fill, $reseth, $cell, $align);
} else {
$this->commitTransaction();
}
}
Seemed to work fine. Without the true in the rollback it breaks horribly, as writeHTML seems to store lots of properties somewhere.
May not need to create a local variable for current page ($cp) as I think it's stored. But hey.
If you're inheriting to write your own Header and Footer functions anyway, not much extra work.