/** * Funcion para dividir archivos PDF a partir de una tag encontrada en cada hoja * y nombramiento de archivos resultantes a partir de otra tag de la hoja * @author 4L3J4NDR0 4N4Y4 (energy1011[4t]gmail[d0t]com) 2014 * @uses FPDF Class (IMPORTANTE: Modificada especialmente para este uso ) * @uses FPDI Class * @uses PDFMerger Class ( Modificada especialmente para este uso ) * @param String $filename nombre del archivo PDF a procesar (sin ruta) * @param String $pathSource ruta del archivo PDF a dividir * @param String $pathSplits ruta para guardar los PDF divididos resultantes * @param String $tagRuleToSplit palabra (tag) del PDF que funciona como disparador para la division de hojas * @param String $posTagToNameFile posicion de la tag con coordenadas formato PDF que necesitamos extraer para nombrar el archivo con el contenido de esta etiqueta * @param String $orientationPage orientacion de la pagina 'P' = normal vertical 'L' = landscape * @param String $sheetType tipo o tamaño de hoja 'Letter' , 'A4', etc * @param String $regex para obtener la TagToNameFile dentro del flujo string del PDF * @param String $stringSizeToRegex tamaño de la cadena a tomar despues de encontrar las coordenadas de la TagToNameFile se posteriormente se le aplica el regex * @param String $splitName nombre general para todos los splits que estaran dentro del zip, si no se pasa un splitName a esta funcion, el nombre para cada uno de los splits es igual al del archivo importado * @return String $responseTXT respuesta del proceso en texto */ function PDFSplitter_split($filename = '', $pathSource = '', $pathSplits = '', $tagRuleToSplit = '', $posTagToNameFile = '', $orientationPage = 'P', $sheetType = 'Letter', $regex = '/\\((.*?)\\)/', $stringSizeToRegex = 27, $splitName = NULL) { @session_start(); $responseTXT = ''; // mensajes de lo sucedido durante el proceso $filename = trim($filename); $pathSplits = trim($pathSplits); $posTagToNameFile = trim($posTagToNameFile); $orientationPage = trim(strtoupper($orientationPage)); $sheetType = trim(ucfirst($sheetType)); $stringSizeToRegex = (int) $stringSizeToRegex; if (is_null($filename)) { $responseTXT .= BR . "Es necesario el nombre del archivo a leer."; return $responseTXT; } if (is_null($pathSplits)) { $responseTXT .= BR . "No se ha indicado ruta donde se guardaran los archivos resultantes del split."; return $responseTXT; } if (is_null($tagRuleToSplit)) { //TODO: sin tagrule $responseTXT .= BR . "No se ha definido un texto o tag de criterio para dividir las hojas, por default el criterio de division sera por hojas."; } if (is_null($posTagToNameFile)) { $responseTXT .= BR . "No se ha definido ninguna dato a extraer de las hojas, para usarse en el nombramiento de archivos resultantes, por default sera el num de hoja."; } // Creo objeto FPDI y obtengo el numero de paginas $pdf = new FPDI(); // Defino el archivo a procesar en el objeto PDF $pagecount = $pdf->setSourceFile($pathSource . $filename); // Inicializo la variable que guarda el nombre del ultimo archivo (pagina dividida) $last_filename = ''; // Obtengo el session id $my_session_id = session_id(); // Borro posibles splits anteriores con el mismo session_id PDFSplitter_delete_all_session_files($pathSplits, '.pdf'); if ($pagecount > 0) { // Itero sobre las paginas del documento PDF for ($i = 1; $i <= $pagecount; $i++) { $new_pdf = new FPDI(); $new_pdf->setSourceFile($pathSource . $filename); $importedPage = $new_pdf->importPage($i); $new_pdf->AddPage($orientationPage, $sheetType); $new_pdf->useTemplate($importedPage); try { $thisTagGotContent = ''; // Agrego id de session al nombre del archivo para evitar colisiones de archivos con otros usuarios $thisFilename = $my_session_id . "_" . $filename; // Verifico nuevamente que no exista el archivo if (file_exists($pathSplits . $thisFilename)) { $responseTXT .= BR . "Existe un archivo con el mismo nombre, vuelva a intentarlo."; return $responseTXT; } // Agrego un consecutivo al nombre del archivo (el numero de hoja) $thisFilename = str_replace('.pdf', '-' . $i . '.pdf', $thisFilename); //Verifica si cada split lleva un nombre if ($splitName != NULL) { // cada split se le agrega el nombre pasado por parametro $thisFilename = str_replace(str_replace('.pdf', '', $filename), $splitName, $thisFilename); } $new_pdf->Output($pathSplits . $thisFilename, "F"); $responseTXT .= BR . BR . ICON_IMG . "Hoja " . $i . " dividida "; // Obtengo la posicion de la etiqueta que voy a extraer para utilizara como parte de nombre del archivo $thisPosTagToGet = @strpos($new_pdf->mybuffer, $posTagToNameFile); // Obtengo la posicion de la etiqueta que usare como disparador del split $thisPosTriggerTab = @strpos($new_pdf->mybuffer, $tagRuleToSplit); // Si existe la etiqueta a extraer en la hoja actual y existe la etiqueta trigger del esplit (Es una hoja que inicia el archivo y necesitamos extraer la etiqueta para nombrarlo) if ($thisPosTagToGet != false && $thisPosTriggerTab != false) { // Obtengo la string con las coordenadas y doy 27 caracteres de tolerancia en la cadena a partir de la posicion de las coordenadas en el string $myStringTag = substr($new_pdf->mybuffer, $thisPosTagToGet, $stringSizeToRegex); // Libero memoria unset($new_pdf->mybuffer); // Obtengo el valor de la etiqueta que esta dentro del parentesis preg_match($regex, $myStringTag, $result); //Libero memoria unset($myStringTag); $thisTagGotContent = $result[1]; // Defino nuevo nombre al archivo a partir del tag obtenido $newNameWithTag = str_replace('-' . $i . '.pdf', '_' . $thisTagGotContent . '.pdf', $thisFilename); // $responseTXT .= BR."--Nombre actual:".$thisFilename; // $responseTXT .= BR."--Nuevo nombre:".$newNameWithTag; // Renombro el archivo con el nuevo tag incluido @rename($pathSplits . $thisFilename, $pathSplits . $newNameWithTag); // $responseTXT .= BR."--Archivo renombrado a:".$pathSplits.$newNameWithTag; $thisFilename = $newNameWithTag; } //Necesito un merge con la hoja anterior ? // No tenemos la trigger tab para el split entonces tenemos una hoja que es consecutiva y necesitamos un merge con el archivo anterior if ($thisPosTriggerTab === false && strlen($last_filename) > 0 && $thisPosTagToGet === false) { // Obtengo la cadena dond e se encuentran los datos de X etiqueta (Folio dentro del documento) $responseTXT .= BR . "---->" . ICON_IMG . "Hoja:" . $i . " Esta es una hoja consecutiva, realizo merge con la hoja anterior."; $config = array('myOrientation' => $orientationPage, 'mySheetType' => $sheetType); $pdfMerge = new PDFMerger($config); $pdfMerge->addPDF($last_filename, 'all')->addPDF($pathSplits . $thisFilename, 'all')->merge('file', $last_filename); // borro el archivo que ya hice merge con la hoja anterior if (file_exists($pathSplits . $thisFilename)) { // $responseTXT .= BR."--Borre el archivo:".$thisFilename; unlink($pathSplits . $thisFilename); // Libero memoria del merge merge unset($pdfMerge); continue; } } // Guardo el nombre del archivo tratado en la iteracion actual para usarlo en la siguiente iteracion $last_filename = $pathSplits . $thisFilename; } catch (Exception $e) { PDFSplitter_log_it($this->config->item('ruta_pdfsplitter_log'), "Archivo con compresion no permitida."); // Tenemos una exception $responseTXT = $e->getMessage() . "\n"; $new_pdf->cleanUp(); // Borro el archivo .pdf fuente que se iba a dividir unlink($pathSource . $filename); return $responseTXT; } $new_pdf->cleanUp(); // libero memoria del objeto hoja pdf de esta iteracion unset($new_pdf); } // End for iteracion por hojas del pdf return $responseTXT .= BR . "Proceso completado."; } // end if pages < 0 }
<?php include 'PDFMerger.php'; $pdf = new PDFMerger(); $pdf->addPDF('samplepdfs/one.pdf', '1, 3, 4')->addPDF('samplepdfs/two.pdf', '1-2')->merge('browser', 'kaantunc.pdf'); /* for($i=0; $i<150; $i++){ $pdf->addPDF('samplepdfs/one.pdf', '1'); } $pdf->merge('browser', 'kaantunc.pdf'); */ //REPLACE 'file' WITH 'browser', 'download', 'string', or 'file' for output options //You do not need to give a file path for browser, string, or download - just the name.
<?php include_once "../db.inc.php"; include_once 'PDFMerger.php'; $date = date('Y-m-d'); if (isset($_GET['day'])) { $date = $_GET['day']; switch ($_GET['day']) { case 'yesterday': $date = date('Y-m-d', strtotime($_GET['day'])); break; } } $pdf = new PDFMerger(); $pdf_folder = "/var/www/html/mallerp2011/static/pdf/{$date}/"; if (!file_exists($pdf_folder)) { echo '没有pdf文件!'; return; } // get transaction id $sql = "select transaction_id from epacket_confirm_list where print_label = 1 and input_date like '{$date}%' order by id asc"; $query = mysql_query($sql, $db_conn); while ($result = mysql_fetch_assoc($query)) { $transaction_id = $result['transaction_id']; $pdf_url = $pdf_folder . $transaction_id . '.pdf'; $pdf->addPDF($pdf_url, 'all'); } $pdf->merge('download', "epacket {$date}.pdf");
function createPDFmulti($urlArray, $batchDir) { global $CONF; $i = 1; //do { // $batchDir=rand(0,10000000); //} while (is_dir($CONF['pdf']['tmpPath'].'/'.$batchDir)) ; @mkdir($CONF['pdf']['tmpPath'] . '/' . $batchDir); $i = 1; //print_r($urlArray ); ksort($urlArray); foreach ($urlArray as $ii => $url) { $hashkey = md5($url); $tmpFile = $CONF['pdf']['tmpPath'] . '/' . $batchDir . '/' . sprintf("%05d", $i) . '_' . $hashkey . '.pdf'; if (!is_file($tmpFile)) { $pdf = leoPDF::createPDF($url, $batchDir, sprintf("%05d", $i) . '_' . $hashkey . '.pdf'); if ($pdf) { $pdfFiles[] = $pdf; } } else { $pdfFiles[] = $batchDir . '/' . sprintf("%05d", $i) . '_' . $hashkey . '.pdf'; } $i++; } // print_r($pdfFiles); $filename = $CONF['pdf']['tmpPath'] . '/' . $batchDir . "/logbook.pdf"; if (is_file($filename)) { echo "Final PDF already exists: {$filename}\n"; return $batchDir . "/logbook.pdf"; } if ($CONF['pdf']['pdftk']) { $cmd = " cd " . $CONF['pdf']['tmpPath'] . '/' . $batchDir . " ; pdftk *.pdf cat output logbook.pdf"; // $cmd=" cd ".$CONF['pdf']['tmpPath']." ; gs -dBATCH -dNOPAUSE -q -sDEVICE=pdfwrite -sOutputFile=finished.pdf *.pdf"; echo "Will exec {$cmd}<BR>"; exec($cmd); // print_r($out); } else { require_once dirname(__FILE__) . '/lib/PDFMerger/PDFMerger.php'; $pdf = new PDFMerger(); foreach ($pdfFiles as $pdfFile) { echo "Adding " . $CONF['pdf']['tmpPath'] . '/' . $pdfFile . "<br>\n"; $pdf->addPDF($CONF['pdf']['tmpPath'] . '/' . $pdfFile, 'all'); } //echo "now merging->\n"; $pdf->merge('file', $filename); //echo "merged...\n"; } /// echo "$filename\n"; if (is_file($filename)) { // echo "loggobok $filename \n"; return $batchDir . "/logbook.pdf"; } else { return 0; } //foreach ($pdfFiles as $pdfFile) { // echo "joining $pdfFile<BR>"; //} // now join them }
function createsignedpdf($sourcepdfpath, $signedpdfpath, $outputpath) { $pdf = new PDFMerger(); $pdf->addPDF($sourcepdfpath, 'all')->addPDF($signedpdfpath, '1')->merge('file', $outputpath); if (file_exists($outputpath)) { return 1; } else { return 0; } }
function addPDF($file_path) { // Suppression de l'autoprint et travail sur copie temporaire (afin de ne pas altérer le document original) @mkdir("./tmp/pdfmerge"); $temp_file = tempnam("./tmp/pdfmerge", "pdfmerge"); $temp_files[] = $temp_file; $content = file_get_contents($file_path); $content = CWkHtmlToPDFConverter::removeAutoPrint($content); file_put_contents($temp_file, $content); self::$temp_files[] = $temp_file; parent::addPDF($temp_file); }
private function process_download_pdf($date = NULL, $part = FALSE) { require_once APPPATH . 'libraries/pdf/PDFMerger.php'; $pdf = new PDFMerger(); if (!$date) { $date = date('Y-m-d'); } $pdf_folder = "/var/www/html/mallerp/static/ems/{$date}/"; $input_user = get_current_user_id(); $priority = fetch_user_priority_by_system_code('shipping'); // director? then set input_user as FALSE, no need to filter it if ($priority > 1) { $input_user = FALSE; } $confirmed_list = $this->epacket_model->fetch_ems_confirmed_list($date, $input_user, $part); if (empty($confirmed_list) or !file_exists($pdf_folder)) { echo 'No pdf for ' . $date; return; } foreach ($confirmed_list as $order) { $track_number = $order->track_number; $pdf_url = $pdf_folder . $track_number . '.pdf'; $sku_pdf_url = $pdf_folder . 'sku_list_' . $track_number . '.pdf'; if (!file_exists($pdf_url)) { continue; } $pdf->addPDF($pdf_url, 'all'); $data = array('downloaded' => 1); $this->epacket_model->update_ems_confirmed_list($order->id, $data); if (!file_exists($sku_pdf_url)) { continue; } $pdf->addPDF($sku_pdf_url, 'all'); } $pdf->merge('download', "ems_eub_{$date}.pdf"); }
/** * Generate a PDF file * * @param PDF $pdf * @param string $outPath */ public function generate(PDF $pdf, $outPath) { $cacheDir = $this->config['cache_dir']; $files = array(); foreach ($pdf->getPages() as $url) { $path = $cacheDir . '/' . md5($url) . '.pdf'; $this->phantom->urlToPdf($url, $path); $files[] = $path; } // Page PDFs generated, stitch 'em together $composite = new \PDFMerger(); foreach ($files as $file) { $composite->addPDF($file); } // Output try { $composite->merge('file', $outPath); } catch (\Exception $E) { // Throws an exception for no good reason - ignore it } }
public function retrievePostPDF() { $validator = Validator::make(Input::all(), array('packinglist' => 'required')); if (!$validator->fails()) { include app_path() . '/includes/PDFMerger.php'; $notFoundPOs = array(); $nonGroundPOs = array(); $packingListPOsArray = array(); $packingListPathArray = array(); $packingListPOs = trim(Input::get('packinglist')); Session::flash('packinglist', $packingListPOs); $packingListPOsArray = explode(PHP_EOL, $packingListPOs); foreach ($packingListPOsArray as $packingListPO) { $tempPackingList = PackingList::where('po', '=', $packingListPO)->first(); if ($tempPackingList == null) { //do not have packing list yet array_push($notFoundPOs, $packingListPO); } else { array_push($packingListPathArray, $tempPackingList->pathToFile); // dd($tempPackingList->shipterms=='Ground'); if ($tempPackingList->shipterms != 'Ground') { array_push($nonGroundPOs, $packingListPO); } } } if (count($notFoundPOs) > 0) { $notFoundPOsReturnString = ''; foreach ($notFoundPOs as $notFoundPO) { $notFoundPOsReturnString .= $notFoundPO . '<br>'; } return View::make('parsepdfKohls-exportpdf-output')->with(array('response' => '<p style="color:red;">The below POs are missing:</p><br>' . $notFoundPOsReturnString)); } else { //return a download file..we have all Packing lists $pdf = new PDFMerger(); foreach ($packingListPathArray as $packingListPath) { $pdf->addPDF($packingListPath); } $tempoutputpath = 'output' . '-' . time() . '.pdf'; $outputpath = public_path() . '/Kohlspos/' . $tempoutputpath; $pdf->merge('file', $outputpath); $outputpath = 'Kohlspos/' . $tempoutputpath; $data['nonGroundPos'] = $nonGroundPOs; // dd($nonGroundPOs); $data['outputpath'] = $outputpath; return View::make('parsepdfKohls-exportpdf-output', $data); // REPLACE 'file' WITH 'browser', 'download', 'string', or 'file' for output options } } else { return View::make('parsepdfKohls-exportpdf-input')->with(array('response' => '<p style="color:red;">Please add a list of POs below.</p>')); } }
public function printManifest($id_manifest_ws) { if (is_array($id_manifest_ws)) { if (empty($id_manifest_ws)) { return false; } if (file_exists(_PS_MODULE_DIR_ . 'dpdpoland/manifest_duplicated.pdf') && !unlink(_PS_MODULE_DIR_ . 'dpdpoland/manifest_duplicated.pdf')) { $error_message = $this->l('Could not delete old PDF file. Please check module permissions'); $error = $this->module_instance->displayError($error_message); return $this->module_instance->outputHTML($error); } foreach ($id_manifest_ws as $id) { $manifest = new DpdPolandManifest(); $manifest->id_manifest_ws = $id; if ($pdf_file_contents = $manifest->generate()) { if (file_exists(_PS_MODULE_DIR_ . 'dpdpoland/manifest_' . (int) $id . '.pdf') && !unlink(_PS_MODULE_DIR_ . 'dpdpoland/manifest_' . (int) $id . '.pdf')) { $error_message = $this->l('Could not delete old PDF file. Please check module permissions'); $error = $this->module_instance->displayError($error_message); return $this->module_instance->outputHTML($error); } $fp = fopen(_PS_MODULE_DIR_ . 'dpdpoland/manifest_' . (int) $id . '.pdf', 'a'); if (!$fp) { $error_message = $this->l('Could not create PDF file. Please check module folder permissions'); $error = $this->module_instance->displayError($error_message); return $this->module_instance->outputHTML($error); } fwrite($fp, $pdf_file_contents); fclose($fp); } else { $error_message = $this->module_instance->displayError(reset(DpdPolandManifestWS::$errors)); return $this->module_instance->outputHTML($error_message); } } include_once _PS_MODULE_DIR_ . 'dpdpoland/libraries/PDFMerger/PDFMerger.php'; $pdf = new PDFMerger(); foreach ($id_manifest_ws as $id) { $manifest_pdf_path = _PS_MODULE_DIR_ . 'dpdpoland/manifest_' . (int) $id . '.pdf'; $pdf->addPDF($manifest_pdf_path, 'all')->addPDF($manifest_pdf_path, 'all'); } $pdf->merge('file', _PS_MODULE_DIR_ . 'dpdpoland/manifest_duplicated.pdf'); ob_end_clean(); header('Content-type: application/pdf'); header('Content-Disposition: attachment; filename="manifests_' . time() . '.pdf"'); readfile(_PS_MODULE_DIR_ . 'dpdpoland/manifest_duplicated.pdf'); $this->deletePDFFiles($id_manifest_ws); exit; } $manifest = new DpdPolandManifest(); $manifest->id_manifest_ws = $id_manifest_ws; if ($pdf_file_contents = $manifest->generate()) { if (file_exists(_PS_MODULE_DIR_ . 'dpdpoland/manifest.pdf') && !unlink(_PS_MODULE_DIR_ . 'dpdpoland/manifest.pdf')) { $error_message = $this->l('Could not delete old PDF file. Please check module permissions'); $error = $this->module_instance->displayError($error_message); return $this->module_instance->outputHTML($error); } if (file_exists(_PS_MODULE_DIR_ . 'dpdpoland/manifest_duplicated.pdf') && !unlink(_PS_MODULE_DIR_ . 'dpdpoland/manifest_duplicated.pdf')) { $error_message = $this->l('Could not delete old PDF file. Please check module permissions'); $error = $this->module_instance->displayError($error_message); return $this->module_instance->outputHTML($error); } $fp = fopen(_PS_MODULE_DIR_ . 'dpdpoland/manifest.pdf', 'a'); if (!$fp) { $error_message = $this->l('Could not create PDF file. Please check module folder permissions'); $error = $this->module_instance->displayError($error_message); return $this->module_instance->outputHTML($error); } fwrite($fp, $pdf_file_contents); fclose($fp); include_once _PS_MODULE_DIR_ . 'dpdpoland/libraries/PDFMerger/PDFMerger.php'; $pdf = new PDFMerger(); $pdf->addPDF(_PS_MODULE_DIR_ . 'dpdpoland/manifest.pdf', 'all'); $pdf->addPDF(_PS_MODULE_DIR_ . 'dpdpoland/manifest.pdf', 'all'); $pdf->merge('file', _PS_MODULE_DIR_ . 'dpdpoland/manifest_duplicated.pdf'); ob_end_clean(); header('Content-type: application/pdf'); header('Content-Disposition: attachment; filename="manifests_' . time() . '.pdf"'); readfile(_PS_MODULE_DIR_ . 'dpdpoland/manifest_duplicated.pdf'); $this->deletePDFFiles($id_manifest_ws); exit; } else { $this->module_instance->outputHTML($this->module_instance->displayError(reset(DpdPolandManifestWS::$errors))); } }
<?php include 'PDFMerger.php'; $pdf = new PDFMerger(); for ($i = 0; $i < 200; $i++) { $pdf->addPDF('samplepdfs/one.pdf', '1, 3, 4')->addPDF('samplepdfs/two.pdf', '1-2')->addPDF('samplepdfs/three.pdf', 'all')->addPDF('samplepdfs/test.pdf', 'all'); } $pdf->merge('download', 'samplepdfs/TEST2.pdf'); //REPLACE 'file' WITH 'browser', 'download', 'string', or 'file' for output options //You do not need to give a file path for browser, string, or download - just the name.
<?php include 'PDFMerger.php'; $pdf = new PDFMerger(); $pdf->addPDF('samplepdfs/one.pdf', '1, 3, 4')->addPDF('samplepdfs/two.pdf', '1-2')->addPDF('samplepdfs/three.pdf', 'all')->merge('file', 'samplepdfs/TEST2.pdf'); //REPLACE 'file' WITH 'browser', 'download', 'string', or 'file' for output options //You do not need to give a file path for browser, string, or download - just the name.
public function createMediaPDF($formid) { $data = $this->objFormModel->getPdfFormData($formid, $db); $postFields = 'mode=media&filename=m_' . $data['pdffile'] . '&formid=' . $formid . '&data=' . urlencode(serialize($data)); $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, SITE_URL . 'plugins/pdf/pdf.php'); curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE); curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_POSTFIELDS, $postFields); $sms_server = curl_exec($ch); curl_close($ch); include '../plugins/PDFMerger/PDFMerger.php'; $pdf = new PDFMerger(); try { $pdf->addPDF('../pdf/' . $data['pdffile'], 'all')->addPDF('../pdf/' . 'm_' . $data['pdffile'], 'all')->merge('file', '../pdf/' . $data['pdffile']); } catch (Exception $ex) { } try { $pdf->addPDF('../pdf/deidentified_' . $data['pdffile'], 'all')->addPDF('../pdf/' . 'm_' . $data['pdffile'], 'all')->merge('file', '../pdf/deidentified_' . $data['pdffile']); } catch (Exception $ex) { } @unlink('../pdf/' . 'm_' . $data['pdffile']); }
<?php include_once 'libraries/PDFMerger/PDFMerger.php'; $AdayBasvuru = $this->AdayBasvuru; $pdf = new PDFMerger(); foreach ($AdayBasvuru as $row) { $pdf->addPDF(EK_FOLDER . 'abhibe/odeme/' . $row['ISTEK_ID'] . '/' . $row['ODEME_DOSYASI'], 'all'); } // $pdf->addPDF(EK_FOLDER.'samplepdfs/one.pdf', '1, 3, 4'); // $pdf->addPDF(EK_FOLDER.'samplepdfs/two.pdf', '1-2'); //->addPDF('samplepdfs/three.pdf', 'all') //->merge('file', 'samplepdfs/TEST3.pdf'); // secilen yere kaydediliyor $pdf->merge('browser', 'AB_HIBE_' . $this->IstekId . '.pdf');
if (file_exists($pathToBarcode)) { unlink($pathToBarcode); } // save pdf to temp dir $output = $dompdf->output(); $pdfName = $code . '.pdf'; file_put_contents('temp/' . $pdfName, $output); // keep track of generated pdf's $pathToPdfs[] = 'temp/' . $pdfName; } // load pdfmerger include 'pdfmerger/PDFMerger.php'; $pdf = new PDFMerger(); // add each pdf to pdf merger foreach ($pathToPdfs as $pathToPdf) { $pdf->addPDF($pathToPdf, 'all'); } // save merged pdf $mergedname = 'hardcopy_barcodes.pdf'; $pdf->merge('download', $mergedname); // cleanup temp pdf's foreach ($pathToPdfs as $pathToPdf) { if (file_exists($pathToPdf)) { unlink($pathToPdf); } } function randomstring($length = 6) { $characters = '0123456789abcdefghijklmnopqrstuvwxyz'; $randomString = ''; for ($i = 0; $i < $length; $i++) {
public function track_numberdownload_part_pdf() { if (!$this->input->is_post()) { return; } $track_number = $this->input->post('track_number'); //echo $track_number; if (substr($track_number, 0, 2) == 'LN') { $pdf_folder = "/var/www/html/mallerp/static/ems/"; $confirmed_list = $this->epacket_model->get_specification_epacket_confirm_list_with_track_number($track_number); } else { $pdf_folder = "/var/www/html/mallerp/static/pdf/"; $confirmed_list = $this->epacket_model->get_epacket_confirm_list_with_track_number($track_number); } if (empty($confirmed_list)) { echo 'No order is ' . $track_number; return; } $date = substr($confirmed_list->input_date, 0, 10); $pdf_folder .= $date . '/'; if (substr($track_number, 0, 2) == 'LN') { //$track_number = $order->track_number; $pdf_url = $pdf_folder . $track_number . '.pdf'; $sku_pdf_url = $pdf_folder . 'sku_list_' . $track_number . '.pdf'; } else { $transaction_id = $order->transaction_id; //$track_number = $order->track_number; $pdf_url = $pdf_folder . $transaction_id . '.pdf'; $sku_pdf_url = $pdf_folder . 'sku_list_' . $track_number . '.pdf'; } if (!file_exists($pdf_folder)) { echo '1.No pdf for ' . $track_number; return; } if ($confirmed_list->print_label == 0) { echo '2.pdf not download for ' . $date; return; } //echo $pdf_folder."<pre>";var_dump($confirmed_list);echo "</pre>"; require_once APPPATH . 'libraries/pdf/PDFMerger.php'; $pdf = new PDFMerger(); if (!file_exists($pdf_url)) { echo '3.No pdf for ' . $track_number; return; } if ($confirmed_list->downloaded == 0) { $data = array('downloaded' => 1); if (substr($track_number, 0, 2) == 'LN') { $this->epacket_model->update_ems_confirmed_list($confirmed_list->id, $data); } else { $this->epacket_model->update_confirmed_list($confirmed_list->id, $data); } } $pdf->addPDF($pdf_url, 'all'); if (!file_exists($sku_pdf_url)) { continue; } $pdf->addPDF($sku_pdf_url, 'all'); $pdf->merge('download', "{$track_number}.pdf"); }
public function updateOrderStatus() { $session = JFactory::getSession(); $post = $session->get('updateOrderIdPost'); $merge_invoice_arr = $session->get('merge_invoice_arr'); $rand_invoice_name = JRequest::getVar('rand_invoice_name', ''); $order_functions = new order_functions(); $cnt = JRequest::getInt('cnt', 0); $order_id = $post['cid']; $responcemsg = ""; for ($i = $cnt, $j = 0; $j < 1; $j++) { if (!isset($order_id[$i])) { $pdf = new PDFMerger(); $merge_invoice_arr = $session->get('merge_invoice_arr'); for ($m = 0; $m < count($merge_invoice_arr); $m++) { if (file_exists(JPATH_SITE . '/components/com_redshop/assets/document' . '/invoice/shipped_' . $merge_invoice_arr[$m] . '.pdf')) { $pdf->addPDF(JPATH_SITE . '/components/com_redshop/assets/document' . '/invoice/shipped_' . $merge_invoice_arr[$m] . '.pdf', 'all'); } } $pdf->merge('file', JPATH_SITE . '/components/com_redshop/assets/document' . '/invoice/shipped_' . $rand_invoice_name . '.pdf'); for ($m = 0; $m < count($merge_invoice_arr); $m++) { if (file_exists(JPATH_SITE . '/components/com_redshop/assets/document' . '/invoice/shipped_' . $merge_invoice_arr[$m] . '.pdf')) { unlink(JPATH_ROOT . '/components/com_redshop/assets/document/invoice/shipped_' . $merge_invoice_arr[$m] . '.pdf'); } } $session->set('merge_invoice_arr', null); break; } $returnmsg = $order_functions->orderStatusUpdate($order_id[$i], $post); // For shipped pdf generation if ($post['order_status_all'] == "S" && $post['order_paymentstatus' . $order_id[$i]] == "Paid") { $pdfObj = new TCPDF(PDF_PAGE_ORIENTATION, PDF_UNIT, 'A5', true, 'UTF-8', false); $pdfObj->SetTitle('Shipped'); $pdfObj->SetAuthor('redSHOP'); $pdfObj->SetCreator('redSHOP'); $pdfObj->SetMargins(8, 8, 8); $font = 'times'; $pdfObj->setImageScale(PDF_IMAGE_SCALE_RATIO); $pdfObj->setHeaderFont(array($font, '', 8)); $pdfObj->SetFont($font, "", 6); $invoice = $order_functions->createShippedInvoicePdf($order_id[$i]); $session->set('merge_invoice_arr', $order_id[$i]); $pdfObj->AddPage(); $pdfObj->WriteHTML($invoice, true, false, true, false, ''); $invoice_pdfName = "shipped_" . $order_id[$i]; $merge_invoice_arr[] = $order_id[$i]; $session->set('merge_invoice_arr', $merge_invoice_arr); $pdfObj->Output(JPATH_SITE . '/components/com_redshop/assets/document' . '/invoice/' . $invoice_pdfName . ".pdf", "F"); } $responcemsg .= "<div>" . ($i + 1) . ": " . JText::_('COM_REDSHOP_ORDER_ID') . " " . $order_id[$i] . " -> "; $errmsg = ''; if ($returnmsg) { $responcemsg .= "<span style='color: #00ff00'>" . JText::_('COM_REDSHOP_ORDER_STATUS_SUCCESSFULLY_UPDATED') . $errmsg . "</span>"; } else { $responcemsg .= "<span style='color: #ff0000'>" . JText::_('COM_REDSHOP_ORDER_STATUS_UPDATE_FAIL') . $errmsg . "</span>"; } $responcemsg .= "</div>"; } $responcemsg = "<div id='sentresponse'>" . $responcemsg . "</div>"; echo $responcemsg; exit; }
<?php include '../PDFMerger/PDFMerger.php'; $pdf = new PDFMerger(); class PDF extends FPDF { public function Header() { } } $pdf->addPDF('pdf/transitiemonitor.pdf', '1')->addPDF('pdf/toelichting.pdf', 'all')->merge('download', 'transitiemonitor.pdf');
<?php include 'PDFMerger.php'; $pdf = new PDFMerger(); /*$pdf->addPDF('samplepdfs/one.pdf', '1, 3, 4') ->addPDF('samplepdfs/two.pdf', '1-2') ->addPDF('samplepdfs/three.pdf', 'all') ->merge('file', 'samplepdfs/TEST2.pdf');*/ $pdf->addPDF('samplepdfs/transitiemonitor.pdf', 'all')->addPDF('samplepdfs/transitiemonitor2.pdf', 'all')->merge('download', 'transitiemonitor_all.pdf'); //REPLACE 'file' WITH 'browser', 'download', 'string', or 'file' for output options //You do not need to give a file path for browser, string, or download - just the name.
static function open_pdfs() { add_submenu_page(null, 'Download', 'Download', 'manage_woocommerce', 'bring_labels', function () { if (!isset($_GET['order_ids']) || $_GET['order_ids'] == '') { return; } $current_user = wp_get_current_user(); // ID 0 is a not an user. if ($current_user->ID == 0) { exit; } // Admins and managers can download all orders. $can_download = in_array('manage_woocommerce', $current_user->roles) || in_array('administrator', $current_user->roles); if (!$can_download) { exit; } $order_ids = explode(',', $_GET['order_ids']); $files_to_merge = []; foreach ($order_ids as $order_id) { $order = new Bring_WC_Order_Adapter(new WC_Order($order_id)); if (!$order->has_booking_consignments()) { continue; } $consignments = $order->get_booking_consignments(); foreach ($consignments as $consignment) { $confirmation = $consignment->confirmation; $consignment_number = $confirmation->consignmentNumber; $file_path = Bring_Booking_Labels::get_file_path($order->order->id, $consignment_number); if (file_exists($file_path)) { $files_to_merge[] = Bring_Booking_Labels::get_file_path($order->order->id, $consignment_number); } } } include_once FRAKTGUIDEN_PLUGIN_PATH . '/vendor/myokyawhtun/pdfmerger/PDFMerger.php'; $merger = new PDFMerger(); foreach ($files_to_merge as $file) { $merger->addPDF($file); } $merge_result_file = Bring_Booking_Labels::get_local_dir() . '/labels-merged.pdf'; $merger->merge('file', $merge_result_file); header("Content-Length: " . filesize($merge_result_file)); header("Content-type: application/pdf"); header("Content-disposition: inline; filename=" . basename($merge_result_file)); header('Expires: 0'); header('Cache-Control: must-revalidate, post-check=0, pre-check=0'); // Workaround for Chrome's inline pdf viewer ob_clean(); flush(); readfile($merge_result_file); exit; }); }
public function MesclarCertificadosPalestraLote() { // Requer permissão de acesso $this->RequirePermission(Usuario::$P_ADMIN, 'SecureExample.LoginForm', 'Autentique-se para acessar esta página', 'Você não possui permissão para acessar essa página ou sua sessão expirou'); $idPalestra = $this->GetRouter()->GetUrlParam('idPalestra'); $participantes = $this->GetRouter()->GetUrlParam('participantes'); //Palestra $palestra = $this->Phreezer->Get('Palestra', $idPalestra); if ($this->GetRouter()->GetUrlParam('palestrantes')) { //PalestraParticipante require_once 'Model/PalestraPalestrante.php'; $criteria = new PalestraPalestranteCriteria(); $criteria->IdPalestra_Equals = $idPalestra; $palestrantes = $this->Phreezer->Query('PalestraPalestranteReporter', $criteria)->ToObjectArray(true, $this->SimpleObjectParams()); $pessoas = array(); foreach ($palestrantes as $palestrante) { $pessoas[] = $palestrante->idPalestrante; } if ($this->GetRouter()->GetUrlParam('idPalestrante')) { $pessoas = array($this->GetRouter()->GetUrlParam('idPalestrante')); } $ehPalestrante = true; print_r($pessoas); } else { $pessoas = json_decode($this->GetRouter()->GetUrlParam('participantes')); $ehPalestrante = false; } $caminho = '/certificados-gerados/' . AppBaseController::ParseUrl($palestra->Nome) . '-' . $palestra->IdPalestra . '/'; include './vendor/PDFMerger/PDFMerger.php'; $pdf = new PDFMerger(); foreach ($pessoas as $pessoa) { $arquivo = GlobalConfig::$APP_ROOT . $caminho . 'palestra' . $pessoa . '.pdf'; $pdf->addPDF($arquivo); } $fileMerged = $caminho . 'impressao.pdf'; $pdf->merge('file', GlobalConfig::$APP_ROOT . $fileMerged); if ($pdf) { echo GlobalConfig::$ROOT_URL . $fileMerged; } }
<?php include 'PDFMerger/PDFMerger.php'; $pdf = new PDFMerger(); $pdf->addPDF('PDFMerger/samplepdfs/1.pdf')->addPDF('PDFMerger/samplepdfs/4.pdf')->merge('file', 'PDFMerger/samplepdfs/ricardo.pdf'); if ($pdf) { echo 'GErou pdf'; } //REPLACE 'file' WITH 'browser', 'download', 'string', or 'file' for output options //You do not need to give a file path for browser, string, or download - just the name.
public static function printLabels($printout_format) { $module_instance = Module::getinstanceByName('dpdpoland'); if ($package_ids = Tools::getValue('PackagesBox')) { $package = new DpdPolandPackage(); $separated_packages = DpdPolandPackage::separatePackagesBySession($package_ids); $international_packages = $separated_packages['INTERNATIONAL']; $domestic_packages = $separated_packages['DOMESTIC']; if ($international_packages) { $result = self::createLabelPDFDocument($package, $module_instance, $international_packages, $printout_format, 'international_labels.pdf'); if ($result !== true) { return $module_instance->outputHTML($result); } } if ($domestic_packages) { $result = self::createLabelPDFDocument($package, $module_instance, $domestic_packages, $printout_format, 'domestic_labels.pdf'); if ($result !== true) { return $module_instance->outputHTML($result); } } include_once _PS_MODULE_DIR_ . 'dpdpoland/libraries/PDFMerger/PDFMerger.php'; $pdf = new PDFMerger(); if ($international_packages && $domestic_packages) { if (file_exists(_PS_MODULE_DIR_ . 'dpdpoland/labels_multisession.pdf') && !unlink(_PS_MODULE_DIR_ . 'dpdpoland/labels_multisession.pdf')) { $error_message = $module_instance->l('Could not delete old PDF file. Please check module folder permissions', self::FILENAME); $error = $module_instance->displayError($error_message); return $module_instance->outputHTML($error); } $international_pdf_path = _PS_MODULE_DIR_ . 'dpdpoland/international_labels.pdf'; $domestic_pdf_path = _PS_MODULE_DIR_ . 'dpdpoland/domestic_labels.pdf'; $multisession_pdf_path = _PS_MODULE_DIR_ . 'dpdpoland/labels_multisession.pdf'; $pdf->addPDF($international_pdf_path, 'all')->addPDF($domestic_pdf_path, 'all')->merge('file', $multisession_pdf_path); } ob_end_clean(); header('Content-type: application/pdf'); header('Content-Disposition: attachment; filename="labels_' . time() . '.pdf"'); if ($international_packages && $domestic_packages) { readfile(_PS_MODULE_DIR_ . 'dpdpoland/labels_multisession.pdf'); } elseif ($international_packages) { readfile(_PS_MODULE_DIR_ . 'dpdpoland/international_labels.pdf'); } elseif ($domestic_packages) { readfile(_PS_MODULE_DIR_ . 'dpdpoland/domestic_labels.pdf'); } else { $error_message = $module_instance->l('No labels were found', self::FILENAME); $error = $module_instance->displayError($error_message); return $module_instance->outputHTML($error); } self::deletePDFFiles(); } }
$iff = 1; foreach ($userId_arr1 as $attachIds1) { $collectionUpload = $db->nf_user_fileuploads; $files121 = $collectionUpload->findOne(array('_id' => new MongoId($attachIds1))); $filType1 = explode(".", $files121['file_name']); if ($filType1[1] == "pdf") { //echo $iff; // if($iff == 1) // { // $pdf->Output($_SERVER['DOCUMENT_ROOT'].'nf/upload_dir/files/'.$newsavedPdf.'.pdf', 'F'); // echo $ssw = "files"; // } // else // { // echo $ssw = "savedpdfs"; // } $pdf1->addPDF($_SERVER['DOCUMENT_ROOT'] . 'nf/upload_dir/savedpdfs/' . $newsavedPdf . '.pdf', 'all')->addPDF($_SERVER['DOCUMENT_ROOT'] . 'nf/upload_dir/files/' . $files121['file_name'], 'all')->merge('file', $_SERVER['DOCUMENT_ROOT'] . 'nf/upload_dir/savedpdfs/' . $newsavedPdf . '.pdf'); } else { } $iff++; } //foreach //unlink($_SERVER['DOCUMENT_ROOT'].'nf/upload_dir/files/'.$newsavedPdf.'.pdf'); } else { $pdf->Output($_SERVER['DOCUMENT_ROOT'] . 'nf/upload_dir/savedpdfs/' . $newsavedPdf . '.pdf', 'F'); } $prvUrl = basename($_SERVER['HTTP_REFERER']); header("location:../../" . $prvUrl . ""); //============================================================+ // END OF FILE //============================================================+
$fp = fopen($file, 'w'); $lt = @createLT($orderid, $totalnb, $return); if ($lt === null) { /* error, skip it */ $nb--; continue; } fwrite($fp, $lt); fclose($fp); if (file_exists('custom_pdf/config.json')) { /* personnalize */ include_once 'custom_pdf/CustomPDF.php'; $cust = new CustomPDF($file, $orderid); $cust->generate(); } @$pdf->addPDF($file, 'all'); $nb--; } } try { $pdf->merge('download', 'Chronopost-LT-' . date('Ymd-Hi') . '.pdf'); } catch (Exception $e) { echo '<p>Le fichier généré est invalide.</p>'; echo '<p>Vérifiez la configuration du module et que les commandes visées disposent d\'adresses de livraison valides.</p>'; } function createLT($orderid, $totalnb = 1, $isReturn = false) { $o = new Order($orderid); $a = new Address($o->id_address_delivery); $cust = new Customer($o->id_customer); // at least 2 skybills for orders >= 30kg
function mergeAndDownload($valid_files, $file_path) { $pdf = new PDFMerger(); foreach ($valid_files as $file) { $pdf->addPDF($file_path . $file); } $pdf->merge('file', realpath("../") . "/admin/assets/uploads/files/answer_script/temp/" . '/navin_' . time() . '.pdf'); die; }
$_SESSION['tmp']['pages_non_anonymes'] = implode(',',$tab_pages_non_anonymes); $_SESSION['tmp']['pages_nombre_par_bilan'] = implode(' ; ',$tab_pages_nombre_par_bilan); unset($_SESSION['tmp']['tab_pages_decoupe_pdf']); exit('ok'); } // //////////////////////////////////////////////////////////////////////////////////////////////////// // IMPRIMER ETAPE 4/4 - Le PDF complet est généré ; on n'en garde que les bilans non anonymes // //////////////////////////////////////////////////////////////////////////////////////////////////// if( ($ACTION=='imprimer') && ($etape==4) ) { $releve_pdf = new PDFMerger; if($_SESSION['tmp']['pages_non_anonymes']!='') // Potentiellement possible si on veut imprimer un ou plusieurs bulletins d'élèves sans aucune donnée, ce qui provoque l'erreur "FPDF error: Pagenumber is wrong!" { $pdf_string = $releve_pdf -> addPDF( CHEMIN_DOSSIER_EXPORT.$_SESSION['tmp']['fichier_nom'].'.pdf' , $_SESSION['tmp']['pages_non_anonymes'] ) -> merge( 'file' , CHEMIN_DOSSIER_EXPORT.$_SESSION['tmp']['fichier_nom'].'.pdf' ); } echo'<ul class="puce">'; echo'<li><a target="_blank" href="'.URL_DIR_EXPORT.$_SESSION['tmp']['fichier_nom'].'.pdf"><span class="file file_pdf">Récupérer, <span class="u">pour impression</span>, l\'ensemble des bilans officiels en un seul document <b>[x]</b>.</span></a></li>'; echo'<li><a target="_blank" href="'.URL_DIR_EXPORT.$_SESSION['tmp']['fichier_nom'].'.zip"><span class="file file_zip">Récupérer, <span class="u">pour archivage</span>, les bilans officiels dans des documents individuels.</span></a></li>'; echo'</ul>'; echo'<p class="astuce"><b>[x]</b> Nombre de pages par bilan (y prêter attention avant de lancer une impression recto-verso en série) :<br />'.$_SESSION['tmp']['pages_nombre_par_bilan'].'</p>'; unset( $_SESSION['tmp']['fichier_nom'] , $_SESSION['tmp']['pages_non_anonymes'] , $_SESSION['tmp']['pages_nombre_par_bilan'] ); exit(); } // //////////////////////////////////////////////////////////////////////////////////////////////////// // IMPRIMER ETAPE 1/4 - Génération de l'impression PDF (archive + responsables) // //////////////////////////////////////////////////////////////////////////////////////////////////// if( ($ACTION!='imprimer') || ($etape!=1) )
<?php include_once 'libraries/PDFMerger/PDFMerger.php'; $AdayBasvuru = $this->AdayBasvuru; $pdf = new PDFMerger(); foreach ($AdayBasvuru as $row) { $pdf->addPDF(EK_FOLDER . 'abhibe/basvuru/' . $row['SINAV_ID'] . '/' . $row['DOKUMAN'], 'all'); } // $pdf->addPDF(EK_FOLDER.'samplepdfs/one.pdf', '1, 3, 4'); // $pdf->addPDF(EK_FOLDER.'samplepdfs/two.pdf', '1-2'); //->addPDF('samplepdfs/three.pdf', 'all') //->merge('file', 'samplepdfs/TEST3.pdf'); // secilen yere kaydediliyor $pdf->merge('browser', 'AB_HIBE_' . $this->IstekId . '.pdf');