Use Zend PDF to Load Multiple PDFs and Draw on Each One - php

I'm trying to use zend pdf to load multiple pdfs from file (each a 1 page pdf) then draw text, images etc. onto each one. Ideally the drawn text and images would be added within a function. However when I try to do some basic draw it comes back with an error in the pdf. The code works perfectly fine until I try draw text onto the page.
require_once 'zendframework/library/Zend/Loader/Autoloader.php';
include 'form-structures.php'; //
$loader = Zend_Loader_Autoloader::getInstance();
$pdfMerged = new Zend_Pdf();
//load pdf
$loadedpdf = Zend_Pdf::load("form-url.pdf");
//clone pdf
$page1 = clone $loadedpdf->pages[0];
// add text etc.
$page1->drawText('Some text...', 400, 500);
drawmore($page1);
//merge pdf
$pdfMerged->pages[] = $page1;
// do again
$loadedpdf = Zend_Pdf::load("form-url.pdf");
$page = clone $loadedpdf->pages[0];
$pdfMerged->pages[] = $page;
echo $pdfMerged->render();
The form-structure.php file is below with a function to draw something extra on the page:
function drawmore($page)
{
$page->drawText("Height is: 600px", 300,800);
return $page;
}

Resolved.
Zend PDF can't draw text on the screen unless you already specified the font.
I just added:
$page1->setFont(Zend_Pdf_Font::fontWithName(Zend_Pdf_Font::FONT_HELVETICA), 20);
and it fixed the error.

Related

Adding logo image on pdf file with fpdi class

I managed quite easily to add an image to a pdf file with fpdi class with the script below in Laravel environment.
$pdf = new \setasign\Fpdi\Fpdi();
// set PDF file & get page count
$pageCount = $pdf->setSourceFile("MultiplePage.pdf");
// loop pages
for ($p = 1; $p <= $pageCount; $p++) {
// import page p
$tppl = $pdf->importPage($p);
// add page p
$pdf->AddPage();
// use the imported page and adjust the page size
$pdf->useTemplate($tppl, ['adjustPageSize' => true]);
// insert image at position x,y,w,h (in mm)
$pdf->Image("Logo.png",170,5,36,22);
}
// save new pdf
$pdf->Output("NewPDF.pdf", "F");
It works 100% but I struggled to find detailed info how to use each of the command and which parameter units are used (i.e. for $pdf->Image).
Can someone point to that doc please?

how to add dynamically generated qrcodes to pdf for labels using fpdf and pdf_label

I have some records stored on a database. I would like to print them onto some Avery labels. I can use FPDF to create a pdf document. I can use PDF_Label which extends FPDF to easily position the information to align with Avery labels. So far so good.
In addition to outputting text, I would like to represent some of the data in a qr code. I can create the qr codes, storing them temporarily on disk as .png files. I can insert the qr_codes as images into a .pdf document. So far so good.
But here is the problem: PDF_label creates 'cells' which align with Avery labels and specifically handles text, not images. How can I 'easily' insert each qr code into each label?
I have looked online for two days but there seems very little guidance on this - other than one piece of advice that sepcicially warns NOT to insert images into FPDF Cells.
One option perhaps would be to use TCPDF but I would appreciate some recommendations on what extension if any would be useful.
For the record, my code so far is:
<?php
require_once( 'vendor/fpdf181/fpdf.php' );
require_once( 'vendor/fpdf_label/PDF_Label.php');
require_once( 'vendor/phpqrcode/qrlib.php' );
// fetch data from database
/* … works fine and creates an array of locations … */
foreach( $locations as $location )
{
$title = "Location " . $location['id'];
$name = $location['name'];
$footer = "https://www.example.com/something/";
$barcode_text = "https://www.example.com/something/?t=1&u=1&l=" . $location['id'];
// create a temporary file to hold the barcode.png
$filePath = './qr_codes/temp_'. $location['id'] . '.png';
$qr_code = new QRcode();
QRcode::png( $barcode_text, $filePath );
$text = "";
$text .= sprintf( $title . "\n" . $name . "\n");
$text .= $pdf->Image( $filePath, $pdf->GetX(), $pdf->GetY(), 20 );
$text .= sprintf( "\n" . $footer );
//$pdf->Add_Label($text);
$pdf->Add_Label($text);
}
From 7 records, this generates just 3 qrcodes on the pdf. Possibly several images overlay one another. The qr_codes are vertically aligned for the top of each row of labels but not correctly positioned horizontally. Presumably this is because that is the position given by GetX and GetY at the time those methods are called.
Any help much appreciated ...
Solved with help to the response to this question:
How can I use TCPDF to make 2x6 sheets of labels that include 2D barcodes WITHOUT using columns OR 3rd-party classes?
I used TCPDF and the recommended method of creating the qrcode and then a cell 'around' it to print out text

Rescale inserted PDF using FPDI in PHP

I am creating a PDF for our clients website. The PDF is paginated for an A4 print. At the end I need to insert several existing PDFs.
Using the FPDI library works fine except when the inserted PDF is wider than the the A4 width, it doesn't rescale.
In the documentation I've found 2 examples of how to do it, none seems to deliver:
First example
$varPageId = $objPDF->ImportPage($intPageNumber);
$varTemplateSize = $objPDF->getTemplatesize($varPageId);
$objPDF->AddPage(
$varTemplateSize['orientation']
, $varTemplateSize
);
$objPDF->useImportedPage($varPageId);
Second example
$varPageId = $objPDF->ImportPage($intPageNumber);
$objPDF->AddPage();
$objPDF->useTemplate(
$varPageId
, ['adjustpageSize' => true]
);
Would anyone know how I can make sure the inserted PDF gets rescaled and all the content is displayed in the new denerated PDF?
Thanks in advance!
Works as expected. Here is a real example using following following code:
<?php
require_once 'vendor/autoload.php';
$pdf = new \setasign\Fpdi\TcpdfFpdi();
$pageCount = $pdf->setSourceFile('p.pdf');
for ($pageNo = 1; $pageNo <= $pageCount; $pageNo++) {
$pageId = $pdf->importPage($pageNo);
$s = $pdf->getTemplatesize($pageId);
$pdf->AddPage($s['orientation'], $s);
$pdf->useImportedPage($pageId);
}
$pdf->Output();

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

CKEditor PHP integration

I am using CKEditor with PHP.
Using the sample PHP where the $code variable gets echoed printing the code that triggers the CKEditor to show. I do the same only in a real layout and the what happens is the Editor engulfs the surroding HTML inside it as if it was the initialValue for it.
Any idea why I am getting this, please?
Here is the code:
// Include CKEditor class.
#require_once("ckeditor/ckeditor.php");
// Create class instance.
$CKEditor = new CKEditor();
// Do not print the code directly to the browser, return it instead
$CKEditor->returnOutput = true;
// Path to CKEditor directory, ideally instead of relative dir, use an absolute path:
// $CKEditor->basePath = '/ckeditor/'
// If not set, CKEditor will try to detect the correct path.
$CKEditor->basePath = 'ckeditor/';
// Set global configuration (will be used by all instances of CKEditor).
$CKEditor->config['width'] = 600;
// Change default textarea attributes
//$CKEditor->textareaAttributes = array("cols" => 80, "rows" => 10);
//Set formatting options
$config['toolbar'] = array(
array( 'Source','-',
'NewPage','Preview','Templates','-',
'Cut','Copy','Paste','PasteText','PasteFromWord','-',
'Undo','Redo','-',
'Find','Replace','-',
'SelectAll','RemoveFormat','-',
'Maximize', 'ShowBlocks'),
'/',
array('Bold','Italic','Underline','Strike','-',
'Subscript','Superscript','-',
'NumberedList','BulletedList','-',
'Outdent','Indent','Blockquote','-',
'JustifyLeft','JustifyCenter','JustifyRight','JustifyBlock','-',
'Link','Unlink','Anchor','-',
'Image','Flash','Table','HorizontalRule','SpecialChar'
),
'/',
array('Format','Font','FontSize','-',
'TextColor','BGColor')
);
//Set skin
//$config['skin'] = 'kama';//kama si defailt skin for 3.4
//Set language and UI Color
$config['language']='ro';
//$config['uiColor']='#AADC6E';
//Remove the html tags in the status bar (e.g. body p strong for when cursor is in a strong tag within a p tag within the body)
$config['removePlugins']='elementspath';
//Allow / deny resizing of editor from dragging the bottom-right corner. Maximize will still work.
$config['removePlugins']='resize';//Remove resize image
$config['resize_enabled ']=false;//Disallow resizing
//Remove the collapse formatting area button (arrow on the middle-right part of the editor
//$config['toolbarCanCollapse']=false;
// The initial value to be displayed in the editor.
$initialValue = '';
//Add the CKFinder for upload of files directly from the `Add Image` / `Add Flash` buttons.
include_once($CKEditor->basePath.'ckfinder/ckfinder.php');
// You can use the "CKFinder" class to render CKFinder in a page:
$finder = new CKFinder();
$finder->BasePath = 'ckeditor/ckfinder/'; // The path for the installation of CKFinder (default = "/ckfinder/").
//$finder->SetupCKEditor($CKEditor,$CKEditor->basePath.'/ckfinder/');
// Create first instance.
$CKEditorOutput = $CKEditor->editor("continut",$initialValue,$config);
Afterwards, I just do: $output.='<div>'.$CKEditorOutput.'</div>;
Of course, the layout around the div in which the CKEditor resides is larger.
Thank you!
Ah, got it...
This line: $CKEditorOutput = $CKEditor->editor("continut",$initialValue,$config);
The layout contains a div with an ID selector of "continut", so <div id="continut">. Thus messing everything up and turning that div and all inner HTML into the RTE Textarea.
Sorry and thanks everyone!

Categories