generate multiple pdf file and zip it - php

I have a situation like create multiple pdf files and download as zip file.
I have tried with below code
function downloadZip()
{
if ($this->input->post('btn_submit'))
{
$data = array(
'results' => $this->Mdi_download_invoices->download_pdf_files($this->input->post('client_id'))
);
foreach ($data['results'] as $d)
{
$mpdf = new \Mpdf\Mpdf();
$html = $this->load->view('download_all_invoices/pdf',$d,true);
$mpdf->WriteHTML($html);
$mpdf->Output(); //this will create a pdf file in next tab
$this->load->library('zip');
$this->zip->add_data();
$this->zip->archive('/var/www/my_backup.zip');
$this->zip->download('my_backup.zip');
}
}
How can I store all pdf file in the array??

Try this code.
$i = 0;
foreach ($data['results'] as $d)
{
$mpdf = new \Mpdf\Mpdf();
$html = $this->load->view('download_all_invoices/pdf',$d,true);
$mpdf->WriteHTML($html);
$mpdf->Output(); //this will create a pdf file in next tab
$this->zip->add_data('file-'.$i.'.pdf',$d);
$i++;
}
$this->zip->archive('/var/www/my_backup.zip');
$this->zip->download('my_backup.zip');
By this you can add each PDF file in Zip and after you the loop you can generate a zip file and download it. I have not tested it so please ignore syntax error but you will get an idea from it.

Related

Displaying bar Code in PDF file on every page of the PDF, in Laravel

I am Using Imagick to Convert PDF to Images
Uploading PDF to Laravel
public function uploadPdf( Request $request )
{
$model = new Attachment();
if ( $request->hasFile('pdf_file_from_request') ) {
Storage::deleteDirectory('3pagerpdf/pdf');
$pdf = $request->file('pdf_file_from_request');
$fileName = time() . '.' . $pdf->getClientOriginalName();
Storage::putFileAs('3pagerpdf/pdf', $pdf, $fileName);
$model->pdf_file_name_in_datebase = $fileName;
$model->save();
flash()->addSuccess('Pdf Added');
return back();
}
}
Converting that PDF to Images
public function convertpdftoimages()
{
$model = Attachment::first();
set_time_limit(300);
// Get the PDF file from the storage folder
$pdfPath = storage_path('app/3pagerpdf/pdf/'.$model->pdf_file_name_in_datebase);
// Create an Imagick object
$imagick = new Imagick();
// Set the resolution and output format
$imagick->setResolution(300, 300);
$imagick->setFormat('jpeg');
// Read the PDF file into the Imagick object
$imagick->readImage($pdfPath);
// Convert each page of the PDF to an image
foreach ( $imagick as $page ) {
$page->writeImage(public_path("/temp_images/page{$page->getImageIndex()}.jpg"));
}
flash()->addSuccess('Convertion Successfull');
return back();
}
Adding bar code to those images
public function add_bar_code_to_images2()
{
$files = File::files('temp_images');
foreach ( $files as $file ) {
// Generate a barcode image for the file
$barcodeGenerator = new BarcodeGeneratorPNG();
$data = '';
for ($i = 0; $i < 10; $i++) {
$data .= rand(0, 9);
}
$barcodeString = $barcodeGenerator->getBarcode($data, $barcodeGenerator::TYPE_CODE_128);
// Create an image resource from the barcode string
$barcodeImage = imagecreatefromstring($barcodeString);
// Load the original image
$originalImage = imagecreatefromjpeg($file->getPathname());
// Merge the barcode image with the original image
imagecopy($originalImage, $barcodeImage, imagesx($originalImage) - imagesx($barcodeImage) - 10, 10, 0, 0, imagesx($barcodeImage), imagesy($barcodeImage));
// Save the modified image to a new path
imagejpeg($originalImage, 'modified_images/' . $file->getFilename());
}
flash()->addSuccess('Bar Code Added Succesfuully');
return back();
}
Converting those images Back to pdf
public function convertimagestopdf( )
{
// Create a new Imagick object
$imagick = new Imagick();
// Set the resolution of the PDF
$imagick->setResolution(300, 300);
// Iterate over the images in the "modified_images" directory
foreach (glob("modified_images/*.jpg") as $image) {
// Read the image file
$imagick->readImage($image);
}
// Set the format of the PDF to "application/pdf"
$imagick->setImageFormat('pdf');
// Save the PDF to a file
$imagick->writeImages('modified_pdf/document.pdf', true);
flash()->addSuccess('pdf compileed');
return back();
}
What I want is
I want to add bar code to every single page of a pdf but I dont want to use imagick extenstion it needs to be installed on a system to make it work .
I tried the above code
it is taking too long to execute for small pdf's that code it fine but for the pdf with 60 pages and above it starts to give me time out error
Note I am not generating this pdf
the pdf will be uploaded by random user of my application and it will be already a pdf I just need to add barcode to every single page of the pdf .
I will take any alternative solution
in which i dont have to install any application on my computer
like ghostscript

Merge two pdfs with Ilovepdf and dompdf

I have a code to convert an html text into pdf and another to merge this pdf with a pdf that the user uploads, but I can't merge the two together, it downloads the converted pdf and not the merged one.
When I put just to merge with two files that the user uploads it works.
My code:
$dompdf = new Dompdf();
$dompdf->loadHtml('hello world');
// (Optional) Setup the paper size and orientation
$dompdf->setPaper('A4', 'landscape');
// Render the HTML as PDF
$dompdf->render();
// Output the generated PDF to Browser
$arquivo = $dompdf->stream();
$ilovepdf = new Ilovepdf('iLovePdfKey', 'iLovePdfKey');
// Create a new task
$myTaskMerge = $ilovepdf->newTask('merge');
// Add files to task for upload
$arquivo = $this->convertHello();
$file1 = $myTaskMerge->addFile('path to the file that the user upload');
$file2 = $myTaskMerge->addFile($arquivo);
// Execute the task
$myTaskMerge->execute();
// Download the package files
$myTaskMerge->download();
$dompdf->stream() sends the rendered PDF to the browser. As such you can't access the generated PDF that way. You have to capture the output and save to a file.
Based on your sample code, something like this:
$dompdf = new Dompdf();
$dompdf->loadHtml('hello world');
$dompdf->render();
$arquivo = $dompdf->output();
$tmp = tempnam(sys_get_temp_dir(), "pdf")
file_put_contents($tmp, $arquivo);
$ilovepdf = new Ilovepdf('iLovePdfKey', 'iLovePdfKey');
$myTaskMerge = $ilovepdf->newTask('merge');
$file1 = $myTaskMerge->addFile('path to the file that the user upload');
$file2 = $myTaskMerge->addFile($tmp);
$myTaskMerge->execute();
unset($tmp);
$myTaskMerge->download();

how to add images to multiple pages on pdf and download the full pdf

I started to work with fpdi with fpdf and I try to add more than one image to multiple pages and in the end, I want to download one PDF with the images over the PDF pages.
The problem is that always just the last PDF downloaded with the last page. Why I can't download one file with all the images?
foreach ($signatures as $signa) {
$fileContent = file_get_contents('http://www.africau.edu/images/default/sample.pdf','rb');
$pageCount = $pdf->setSourceFile(StreamReader::createByString($fileContent));
$pdf->setSourceFile(StreamReader::createByString($fileContent));
$tplId = $pdf->importPage($signa->page);
$pdf->useTemplate($tplId, 10, 10, 100);
$pdf->Image('signature.jpg', $signa->position->x, $signa->position->y, $signa->size->width, $signa->size->height);
if($signa->page === 2) {
$pdf->Output('D');
}
}
I found this Solution and its work for me.
Solution on my code:
$pdf = new Fpdi();
foreach ($signatures as $signa) {
$pdf->AddPage();
$fileContent = file_get_contents('http://www.africau.edu/images/default/sample.pdf','rb');
$pdf->setSourceFile(StreamReader::createByString($fileContent));
$tplId = $pdf->importPage($signa->page);
$pdf->useTemplate($tplId, 10, 10, 100);
$pdf->Image('signature.png', $signa->position->x, $signa->position->y, $signa->size->width, $signa->size->height);
}
$pdf->Output('newpdf1.pdf', 'D');

Merge two PDF files into single one using MPDF

I am using MPDF library to generate pdf files .I have created two PDF files in my root directory as follows :
$invoice_nos = ['0'=>'ISE-00000014Y18','1'=>'ISE-00000005Y18'];
foreach ($invoice_nos as $key => $invoice_no) {
$html = 'Invoice No - '.$invoice_no;
$pdf_file_name = $invoice_no.'.pdf';
$pdf_file_path = ROOT . '/app/webroot/Service_Invoices/'. DS .$pdf_file_name ;
ob_start();
$mpdf = new \mPDF('utf-8', 'A4' ,'','',5,5,36,10,5,4);
$mpdf->WriteHTML($html,2);
ob_clean();
$mpdf->Output($pdf_file_name,'f');
}
Now I want to merge these two files into a single file with different pages. How can I do this? I have searched many examples of it but nothing is working.
mPDF is not the best tool to merge PDF files. You'll be better off with GhostScript:
gs -dBATCH -dSAFER -dNOPAUSE -sDEVICE=pdfwrite -sOutputFile=combined.pdf invoice1.pdf invoice2.pdf
Alternatively, generate both invoices directly to one file:
$invoice_nos = ['0' => 'ISE-00000014Y18', '1' => 'ISE-00000005Y18'];
$mpdf = new \mPDF('utf-8', 'A4', '', '', 5, 5, 36, 10, 5, 4);
foreach ($invoice_nos as $key => $invoice_no) {
$html = 'Invoice No - ' . $invoice_no;
$mpdf->WriteHTML($html, 2);
$mpdf->WriteHTML('<pagebreak>');
}
$pdf_file_name = $invoice_no . 'invoices.pdf';
$mpdf->Output($pdf_file_name, 'f');
Hi There so i actually used this code to Flatten a PDF that had editable forms but i believe we can change it to merge the pdf's together.
This solution uses php's Imagick() which should be part of your hosting environment.
So here is the code, i have tried to comment it as best possible. you will call the mergePdf() and put the destination folder (where your files are and where you will save the new file) and an array of the files (Just there names) to be merged, and then a new file name. once done it will save the new file in the destination folder.
/**
* mergePdf()
*
* #param mixed $destinationPath
* #param array $files
* #param mixed $newFileName
* #return
*/
public function mergePdf($destinationPath, $files, $newFileName){
//Create array to hold images
$array_images = array();
//Loop through to be merged
foreach($files as $file){
//Firstly we check to see if the file is a PDF
if(mime_content_type($destinationPath.$file)=='application/pdf'){
// Strip document extension
$file_name = pathinfo($file, PATHINFO_FILENAME);
// Convert this document
// Each page to single image
$im = new imagick();
//Keep good resolution
$im->setResolution(175, 175);
$im->readImage($destinationPath.$file);
$im->setImageFormat('png');
$im->writeImages($destinationPath.$file_name.'.png',false);
//loop through pages and add them to array
for($i = 0; $i < $im->getNumberImages(); $i++){
//insert images into array
array_push($array_images, $destinationPath.$file_name.'-'.$i.'.png');
}
//Clear im object
$im->clear();
$im->destroy();
}else{
return false;
}
}
//Now that the array of images is created we will create the PDF
if(!empty($array_images)){
//Create new PDF document
$pdf = new Imagick($array_images);
$pdf->setImageFormat('pdf');
if($pdf->writeImages($destinationPath.$newFileName, true)){
$pdf->clear();
$pdf->destroy();
//delete images
foreach($array_images as $image){
unlink($image);
}
return true;
}else{
return false;
}
}else{
return false;
}
}
public function getMergePdf(){
$destinationPath = "/your/destination/to/the/file/goes/here/";
//put the files in the order you want them to be merged
$files = array('file1.pdf','file2.pdf','file3.pdf');
$this->mergePdf($destinationPath, $files, "NewPdf.pdf");
}

PHPExcel and convert to HTML

I want to create a preview of existing excel file(xlsm,xlsx) in browser. I using phpExcel to convert excel file to html file and after this take HTML code from it but after all this converters the tabs (worksheets) disappear and I cannot go to next one, how may I repair this?.
public function createHtmlPreview($path)
{
$file = preg_replace('/\\.[^.\\s]{3,4}$/', '', $path).'.htm';
$objPHPExcelReader = \PHPExcel_IOFactory::createReader('Excel2007');
$objPHPExcel = $objPHPExcelReader->load($path);
$objPHPExcelWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel,'HTML');
$objPHPExcel = $objPHPExcelWriter->save($file);
$html = new \DOMDocument();
$html->loadHTMLFile($file);
unlink($file);
return $html->saveHTML();
//return $file;
}

Categories