Example #1
2
 /**
  * Merge multiple documents.
  *
  * @return Dhl_Intraship_Helper_Pdf             $this
  * @throws Dhl_Intraship_Helper_Pdf_Exception
  */
 public function merge()
 {
     // Include required fpdi library.
     if (!class_exists('FPDF', false)) {
         require_once Mage::getBaseDir('base') . DS . 'lib' . DS . 'fpdf' . DS . 'fpdf.php';
     }
     if (!class_exists('FPDI', false)) {
         require_once Mage::getBaseDir('base') . DS . 'lib' . DS . 'fpdf' . DS . 'fpdi.php';
     }
     // Try to merge documents via FPDI.
     try {
         // Create new FPDI document
         $this->_document = new FPDI('P', 'mm', $this->getConfig()->getFormat());
         $this->_document->SetAutoPageBreak(false);
         $page = 1;
         foreach ($this->_collection as $document) {
             $pages = $this->_document->setSourceFile($document->getFilePath());
             for ($i = 1; $i <= $pages; $i++) {
                 $this->_document->addPage();
                 $this->_document->useTemplate($this->_document->importPage($i, '/MediaBox'));
                 $page++;
             }
         }
     } catch (Exception $e) {
         throw new Dhl_Intraship_Helper_Pdf_Exception('pdf merging failed. service temporary not available', $e->getCode());
     }
     return $this;
 }
Example #2
0
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     $id = $input->getArgument('id');
     $pdffile = $input->getArgument('pdf');
     $em = $this->getContainer()->get('doctrine');
     $tab = $this->csv($pdffile);
     $template = $em->getRepository('PrintBundle:Template')->find($id);
     $path = $this->getContainer()->get('kernel')->getRootDir() . '/../web/uploads/pdf/' . $template->getPdffile();
     $width = $template->getWidth();
     $height = $template->getHeight();
     $orientation = $height > $width ? 'P' : 'L';
     $custom_layout = array($width, $height);
     $i = 1;
     foreach ($tab as $key => $value) {
         $pdf = new \FPDI($orientation, 'mm', $custom_layout, true, 'UTF-8', false);
         $pdf->setPageOrientation($orientation);
         $pdf->SetMargins(PDF_MARGIN_LEFT, 40, PDF_MARGIN_RIGHT);
         $pdf->SetAutoPageBreak(true, 40);
         $pdf->setFontSubsetting(false);
         // add a page
         $pdf->AddPage($orientation);
         $pdf->setSourceFile($path);
         $_tplIdx = $pdf->importPage(1);
         $size = $pdf->useTemplate($_tplIdx, 0, 0, $width, true);
         foreach ($template->getChildactivity() as $opt) {
             $pdf->SetXY($opt->getX(), $opt->getY());
             $pdf->SetFont($opt->getFont(), '', $opt->getFontsize() * 2);
             // echo $opt->getFontsize()."\n";
             $pdf->Cell($opt->getWidth(), $opt->getHeight(), $value[$opt->getName()]);
         }
         //$pdf->Cell(0, $size['h'], 'TCPDF and FPDI');
         // echo $template->getId();
         $pdf->Output($this->getContainer()->get('kernel')->getRootDir() . '/../web/folder/pdf' . $template->getId() . "-{$i}.pdf", 'F');
         $i++;
     }
 }
Example #3
0
function emarking_import_pdf_into_pdf(FPDI $pdf, $pdftoimport)
{
    $originalpdfpages = $pdf->setSourceFile($pdftoimport);
    $pdf->SetAutoPageBreak(false);
    // Add all pages in the template, adding the header if it corresponds
    for ($pagenumber = 1; $pagenumber <= $originalpdfpages; $pagenumber++) {
        // Adding a page
        $pdf->AddPage();
        $template = $pdf->importPage($pagenumber);
        $pdf->useTemplate($template, 0, 0, 0, 0, true);
    }
}
 public function createScreeningPdf($hash)
 {
     $screening_entry_model = ScreeningEntry::findOne(['hash' => $hash]);
     $screening_form_model = ScreeningForm::findOne(['id' => $screening_entry_model->screening_form_id]);
     $subject_model = Subject::findOne(['id' => $screening_entry_model->subject_id]);
     $count = 1;
     //$permissions = \SetaPDF_Core_SecHandler::PERM_DIGITAL_PRINT ;
     $this->_font = 'Helvetica';
     //class_exists('TCPDF', true); // trigger Composers autoloader to load the TCPDF class
     $pdf = new \FPDI();
     $pdf->SetAutoPageBreak(true);
     // add a page
     $pdf->SetTopMargin(30);
     $pdf->AddPage();
     $pdf->setSourceFile(\yii::$app->basePath . "/../letterhead-mini-header.pdf");
     $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->SetFont($this->_font, '', 9);
     $pdf->SetXY(10, 6);
     $pdf->Cell(0, 3, 'Confidential - Participant screening form');
     $pdf->SetFont($this->_font, '', 12);
     $pdf->SetXY(10, 14);
     $pdf->MultiCell(150, 3, yii::$app->DateComponent->timestampToUkDate($screening_entry_model->created_at), 0, 'R');
     $pdf->MultiCell(100, 3, $screening_entry_model->screening_form_title, 0, '');
     $pdf->Ln();
     $pdf->SetFont($this->_font, '', 9);
     $pdf->Cell(100, 4, sprintf('Participant: %s %s (dob %s)', $screening_entry_model->subject->first_name, $screening_entry_model->subject->last_name, yii::$app->DateComponent->isoToUkDate($screening_entry_model->subject->dob)));
     $pdf->Cell(50, 4, sprintf('Identifier: %s', $screening_entry_model->subject->cubric_id), 0, '', 'R');
     $pdf->Ln();
     $pdf->Cell(100, 4, sprintf('Researcher: %s %s (project %s)', $screening_entry_model->researcher->first_name, $screening_entry_model->researcher->last_name, $screening_entry_model->project->code));
     $pdf->Cell(50, 4, sprintf('Resource: %s', $screening_entry_model->resource_title), 0, '', 'R');
     $pdf->SetXY(10, 38);
     $pdf->SetFont($this->_font, '', 12);
     $pdf->Cell(150, 4, sprintf('Responses'));
     $pdf->SetFont($this->_font, '', 9);
     $pdf->Ln();
     foreach (yii::$app->screeningresponse->getResponses($hash) as $response) {
         if (strlen($response['caption']) > 0) {
             $pdf->Ln();
             $pdf->MultiCell(180, 4, sprintf('%s ', $response['caption']), 0, 'U');
             $count = 1;
         }
         $pdf->MultiCell(180, 4, sprintf('%s. %s ', $count, $response['content']));
         $pdf->SetFont($this->_font, 'B', 9);
         if ($response['response'] === null) {
             $response['response'] = 'Not specified / Unknown.';
         }
         $pdf->MultiCell(180, 4, sprintf('%s ', $response['response']));
         $pdf->SetFont($this->_font, '', 9);
         $count++;
         $pdf->Ln();
     }
     $pdf->Ln();
     $pdf->SetFont($this->_font, '', 12);
     $pdf->Cell(180, 4, sprintf('Signatures'));
     $pdf->Ln();
     $pdf->Ln();
     $pdf->SetFont($this->_font, '', 9);
     $pdf->Cell(100, 4, 'Participant ');
     $pdf->Cell(100, 4, 'Researcher ');
     $pdf->Ln();
     $pdf->Ln();
     $currentX = $pdf->GetX();
     $currentY = $pdf->GetY();
     $pdf->Image(sprintf('/tmp/subject-%s.png', $hash), $currentX, $currentY);
     $currentX = $pdf->GetX();
     $pdf->Image(sprintf('/tmp/researcher-%s.png', $hash), $currentX + 100, $currentY);
     // now write some text above the imported page
     // NOW SET ScreeningEntry::progress_id = PUBLISHED so it cannot be edited again.
     // $pdfData = $pdf->Output('S');
     // create a writer
     // create a Http writer
     //$writer = new \SetaPDF_Core_Writer_Http("fpdf-sign-demo.pdf", true);
     // load document by filename
     //$document = new \SetaPDF_Core_Document::loadByString($pdfData, $writer);
     //$document = new \SetaPDF_Core_Reader_File($pdf->Output(), $writer);
     $writer = new \SetaPDF_Core_Writer_File("/Users/Spiro/tmp/myPDF.pdf");
     $document = \SetaPDF_Core_Document::loadByString($pdf->Output("S"), $writer);
     // let's prepare the temporary file writer:
     \SetaPDF_Core_Writer_TempFile::setTempDir("/tmp/");
     // create a signer instance for the document
     $signer = new \SetaPDF_Signer($document);
     // add a field with the name "Signature" to the top left of page 1
     $signer->addSignatureField(\SetaPDF_Signer_SignatureField::DEFAULT_FIELD_NAME, 1, \SetaPDF_Signer_SignatureField::POSITION_LEFT_BOTTOM, array('x' => 10, 'y' => 10), 180, 50);
     // set some signature properties
     $signer->setReason('Integrity');
     $signer->setLocation('CUBRIC');
     $signer->setContactInfo('+44 2920 703859');
     // ccreate an OpenSSL module instance
     $module = new \SetaPDF_Signer_Signature_Module_OpenSsl();
     // set the sign certificate
     $module->setCertificate(file_get_contents("/Users/spiro/Sites/projects/certs/certificate.pem"));
     // set the private key for the sign certificate
     $module->setPrivateKey(array(file_get_contents("/Users/spiro/Sites/projects/certs/key.pem"), ""));
     // create a Signature appearance
     $visibleAppearance = new \SetaPDF_Signer_Signature_Appearance_Dynamic($module);
     // choose a document to get the background from and convert the art box to an xObject
     $backgroundDocument = \SetaPDF_Core_Document::loadByFilename(Yii::getAlias('@frontend/web/img/cubric-logo.pdf'));
     $backgroundXObject = $backgroundDocument->getCatalog()->getPages()->getPage(1)->toXObject($document);
     // format the date
     $visibleAppearance->setShowFormat(\SetaPDF_Signer_Signature_Appearance_Dynamic::CONFIG_DATE, 'd-m-Y H:i:s');
     // disable the distinguished name
     $visibleAppearance->setShow(\SetaPDF_Signer_Signature_Appearance_Dynamic::CONFIG_DISTINGUISHED_NAME, false);
     // set the background with 50% opacity
     $visibleAppearance->setGraphic($backgroundXObject, 0.5);
     //$visibleAppearance->setBackgroundLogo($backgroundXObject, .5);
     // sign/certify the document
     // define the appearance
     $signer->setAppearance($visibleAppearance);
     $signer->sign($module);
     if (file_exists(sprintf('/tmp/subject-%s.png', $hash))) {
     }
     //   unlink(sprintf('/tmp/subject-%s.png' , $hash));
     if (file_exists(sprintf('/tmp/researcher-%s.png', $hash))) {
     }
     //     unlink(sprintf('/tmp/researcher-%s.png' , $hash));
     return true;
 }
Example #5
0
 public function executeBatchPrintBadge(sfWebRequest $request)
 {
     $ids = $request->getParameter('ids');
     // initiate FPDI
     $pdf = new FPDI('P', 'pt');
     // set the sourcefile
     $pdf->setSourceFile(sfConfig::get('sf_upload_dir') . '/badges/ID_new.pdf');
     foreach ($ids as $id) {
         $this->employee = EmployeePeer::retrieveByPk($id);
         // import page 1
         $tplIdx = $pdf->importPage(1);
         // add a new page based on size of the badge
         $s = $pdf->getTemplatesize($tplIdx);
         $pdf->AddPage('P', array($s['w'], $s['h']));
         $pdf->useTemplate($tplIdx);
         $pdf->setMargins(0, 0, 0, 0);
         $pdf->SetAutoPageBreak(false);
         if ($this->employee->getPicture()) {
             $pdf->Image(sfConfig::get('sf_upload_dir') . '/' . sfConfig::get('app_employee_images_dir') . '/' . $this->employee->getPicture(), 29.5, 25.5, 60.3, 74.3);
         } else {
             $pdf->Image(sfConfig::get('sf_upload_dir') . '/badges/picture_missing.jpg', 29.5, 25.5, 60.3, 74.3);
         }
         // now write some text above the imported page
         $pdf->SetFont('freesans', 'B', 12);
         $pdf->SetTextColor(82, 78, 134);
         $pdf->SetXY(22, 110);
         $pdf->Cell(0, 12, $this->employee->getFullName());
         $pdf->Ln();
         $pdf->SetX(22);
         $pdf->SetFont('freesans', 'BI', 10);
         $pdf->Cell(0, 14, $this->employee->getJob());
         $pdf->SetDisplayMode('real');
     }
     return $pdf->Output('newpdf.pdf', 'D');
 }
Example #6
0
 function schedule_retirement_pay($date_retired = '', $employee_id = '1')
 {
     $data = array();
     $data['msg'] = '';
     $this->load->library('fpdf');
     if (!defined('FPDF_FONTPATH')) {
         define('FPDF_FONTPATH', $this->config->item('fonts_path'));
     }
     $this->load->library('fpdi');
     // initiate FPDI
     $pdf = new FPDI('L', 'mm', 'Legal');
     $pdf->SetAutoPageBreak(FALSE);
     // add a page
     $pdf->AddPage();
     // set the sourcefile
     $pdf->setSourceFile('dtr/template/leave/schedule_retirement_pay.pdf');
     // select the first page
     $tplIdx = $pdf->importPage(1);
     // use the page we imported
     $pdf->useTemplate($tplIdx);
     $e = new Employee_m();
     $e->get_by_employee_id($employee_id);
     // set font, font style, font size.
     $pdf->SetFont('Times', '', 10);
     $pdf->SetTextColor(89, 89, 89);
     // set initial placement
     $pdf->SetXY(142, 20.5);
     $personal = new Personal_m();
     $personal->where('employee_id', $e->id);
     $personal->get(1);
     $this->load->helper('date');
     $o = new Office_m();
     $o->get_by_office_id($e->office_id);
     $period = 'January 1, 2012 May 10, 2012';
     $office_name = $o->office_name;
     $lgu_name = Setting::getField('lgu_name');
     //var_dump($date_retired);
     $date_retired_diff = $date_retired;
     $date_birth = convert_long_date($personal->birth_date, TRUE);
     $first_day_of_service = convert_long_date($e->first_day_of_service);
     $date_retired = convert_long_date($date_retired, TRUE);
     $salary = $this->Salary_grade->get_monthly_salary($e->salary_grade, $e->step);
     //$pdf->SetX(114);
     $pdf->Write(0, $period);
     $pdf->Ln(10);
     $pdf->SetX(63);
     $pdf->Write(0, $office_name);
     $pdf->Ln(5);
     $pdf->SetX(63);
     $pdf->Write(0, $lgu_name);
     $pdf->SetFont('Times', 'B', 10);
     $pdf->Ln(21.5);
     $pdf->SetX(14);
     $pdf->Write(0, $e->fname . ' ' . substr($e->mname, 0, 1) . '. ' . $e->lname);
     $pdf->SetFont('Times', '', 10);
     $pdf->SetX(65);
     $pdf->Write(0, $date_birth);
     $pdf->SetX(88);
     $pdf->Write(0, $date_retired);
     $date1 = new DateTime("1970-7-01");
     $date2 = new DateTime("2011-11-16");
     $date1 = new DateTime($e->first_day_of_service);
     $date2 = new DateTime($date_retired_diff);
     $interval = $date1->diff($date2);
     //echo "difference " . $interval->y . " years, " . $interval->m." months, ".$interval->d." days ";
     if ($interval->y != 0) {
         $pdf->SetX(114);
         $pdf->Write(0, $interval->y . " years");
     }
     if ($interval->m != 0) {
         $pdf->Ln(5);
         $pdf->SetX(114);
         $pdf->Write(0, $interval->m . " months");
     }
     if ($interval->d != 0) {
         $pdf->Ln(5);
         $pdf->SetX(114);
         $pdf->Write(0, $interval->d . " days");
     }
     // Salary
     $pdf->SetXY(145, 53);
     $pdf->Cell(20, 8, number_format($salary, 2), '', 0, 'C', FALSE);
     $total_leave = $this->Leave_card->get_total_leave_credits($employee_id);
     $vacation_leave = $total_leave['vacation'];
     $sick_leave = $total_leave['sick'];
     $total = $vacation_leave + $sick_leave;
     $terminal_leave = $salary * $total * 0.0478087;
     // vacation leave
     $pdf->SetXY(203, 58);
     $pdf->Cell(20, 8, number_format($vacation_leave, 3), '', 0, 'R', FALSE);
     // sick leave
     $pdf->SetXY(203, 63);
     $pdf->Cell(20, 8, number_format($sick_leave, 3), '', 0, 'R', FALSE);
     // total
     $pdf->SetXY(203, 68);
     $pdf->Cell(20, 8, number_format($total, 3), '', 0, 'R', FALSE);
     // terminal leave
     $pdf->SetX(274);
     $pdf->Cell(20, 8, number_format($terminal_leave, 2), '', 0, 'R', FALSE);
     $pdf->SetFont('Times', 'B', 10);
     // grand total leave
     $pdf->SetXY(203, 119);
     $pdf->Cell(20, 8, number_format($total, 3), '', 0, 'R', FALSE);
     // total terminal amount
     $pdf->SetX(274);
     $pdf->Cell(20, 8, number_format($terminal_leave, 2), '', 0, 'R', FALSE);
     // Signatories
     $pdf->Ln(35);
     $pdf->SetX(13);
     $pdf->Cell(50, 8, Setting::getField('retirement_signatory_prepared'), '', 0, 'C', FALSE);
     // date
     $pdf->SetFont('Times', '', 10);
     $pdf->SetX(76);
     $pdf->Cell(50, 8, date('F d, Y'), '', 0, 'C', FALSE);
     $pdf->SetFont('Times', 'B', 10);
     $pdf->SetX(147);
     $pdf->Cell(50, 8, Setting::getField('retirement_signatory_approved'), '', 0, 'C', FALSE);
     $pdf->SetFont('Times', '', 10);
     $pdf->Ln(5);
     $pdf->SetX(13);
     $pdf->Cell(50, 8, Setting::getField('retirement_signatory_prepared_position'), '', 0, 'C', FALSE);
     $pdf->SetX(146);
     $pdf->Cell(50, 8, Setting::getField('retirement_signatory_approved_position'), '', 0, 'C', FALSE);
     $pdf->SetFont('Times', 'B', 10);
     $pdf->Ln(25);
     $pdf->SetX(13);
     $pdf->Cell(50, 8, Setting::getField('retirement_signatory_certified'), '', 0, 'C', FALSE);
     $pdf->SetX(88);
     $pdf->Cell(50, 8, Setting::getField('retirement_signatory_attested'), '', 0, 'C', FALSE);
     $pdf->SetX(147);
     $pdf->Cell(50, 8, Setting::getField('retirement_signatory_availability'), '', 0, 'C', FALSE);
     $pdf->SetX(223);
     $pdf->Cell(50, 8, Setting::getField('retirement_signatory_noted'), '', 0, 'C', FALSE);
     $pdf->SetFont('Times', '', 10);
     $pdf->Ln(5);
     $pdf->SetX(13);
     $pdf->Cell(50, 8, Setting::getField('retirement_signatory_certified_position'), '', 0, 'C', FALSE);
     $pdf->SetX(88);
     $pdf->Cell(50, 8, Setting::getField('retirement_signatory_attested_position'), '', 0, 'C', FALSE);
     $pdf->SetX(147);
     $pdf->Cell(50, 8, Setting::getField('retirement_signatory_availability_position'), '', 0, 'C', FALSE);
     $pdf->SetX(223);
     $pdf->Cell(50, 8, Setting::getField('retirement_signatory_noted_position'), '', 0, 'C', FALSE);
     header('Cache-Control: maxage=3600');
     //Adjust maxage appropriately
     header('Pragma: public');
     $pdf->Output('dtr/reports/schedule_retirement_pay' . $employee_id . '.pdf', 'F');
     // index 'L' for landscape
     $this->pages['L'] = 'dtr/reports/schedule_retirement_pay' . $employee_id . '.pdf';
 }
Example #7
0
    header("location: index.php?app=print");
    die;
} else {
    $items = $_REQUEST['item'];
    $conf = $_REQUEST['conf'];
}
ini_set("memory_limit", "64M");
require_once 'class/data.php';
require_once 'class/build.php';
require_once 'tcpdf/tcpdf.php';
require_once 'tcpdf/tcpdf_addons.php';
require_once 'FPDI/fpdi.php';
$print_data = new print_data_class($_camp->id);
$print_build = new print_build_class($print_data);
$pdf = new FPDI('P', 'mm', 'A4', true, 'UTF-8', false);
$pdf->SetAutoPageBreak(true);
$pdf->SetAuthor('ecamp2.pfadiluzern.ch');
$pdf->SetSubject('J&S - Programm');
$pdf->SetTitle('J&S - Programm');
foreach ($items as $nr => $item) {
    if ($item == "title") {
        $print_build->cover->build($pdf);
    }
    if ($item == "picasso") {
        $print_build->picasso->set_orientation($conf[$nr]);
        $print_build->picasso->build($pdf);
    }
    if ($item == "allevents") {
        if ($conf[$nr] == "true") {
            $print_build->daylist->build($pdf);
        }
Example #8
0
            $return = "templates/18px_up-red.png";
        } else {
            $return = "";
        }
        return $return;
    }
}
// just require FPDI afterwards
require_once './FPDI-1.4.4/fpdi.php';
// Page in is in mm -- 215.9 wide, by 279.4 = 8.5 x 11 inches
// initiate PDF
$pdf = new FPDI("P", "mm", "letter");
// Shortcut so we don't have to write $this_border so much;
$b = $pdf->border;
// Set page break distance from bottom
$pdf->SetAutoPageBreak(false, 30);
// Load the dynamic content from the post
$content = json_decode(utf8_encode($_POST['content']));
$pdf->content = $content;
// Note - Don't add all the fonts.  They all get embedded in the PDF wether you use them or not.
// Add some Unicode font (uses UTF-8)
// Hairline
$pdf->AddFont('Lato-100', '', 'Lato-Hai.ttf', true);
// Regular
$pdf->AddFont('Lato', '', 'Lato-Lig.ttf', true);
// Bold
$pdf->AddFont('Lato', 'B', 'Lato-Reg.ttf', true);
// Really Bold
$pdf->AddFont('Lato-700', '', 'Lato-Bol.ttf', true);
//
$pdf->SetFont('Lato', '', 10);
Example #9
0
 /**
  * resizePdf 
  * 
  * @return void
  */
 public function resizePdf()
 {
     try {
         if (false === class_exists('FPDF', false)) {
             require_once Mage::getBaseDir('base') . DS . 'lib' . DS . 'fpdf' . DS . 'fpdf.php';
         }
         if (false === class_exists('FPDI', false)) {
             require_once Mage::getBaseDir('base') . DS . 'lib' . DS . 'fpdf' . DS . 'fpdi.php';
         }
         // Create new FPDI document
         $document = new FPDI('P', 'mm', $this->getConfig()->getFormat());
         $margins = $this->getConfig()->getMargins();
         $document->SetAutoPageBreak(false);
         $pages = $document->setSourceFile($this->getPathToPdf());
         for ($i = 1; $i <= $pages; $i++) {
             $document->addPage();
             $document->useTemplate($document->importPage($i, '/MediaBox'), $margins['left'], $margins['top']);
         }
         $document->Output($this->getPathToPdf(), 'F');
     } catch (Exception $e) {
         throw new Dhl_Intraship_Helper_Pdf_Exception('pdf resizing failed. service temporary not available. ' . $e->getMessage(), $e->getCode());
     }
 }
 function Output($type)
 {
     $type = strtolower($type);
     //Initialize PDF object so all subclasses can access it.
     //Loop through all objects and combine the output from each into a single document.
     if ($type == 'pdf') {
         if (!class_exists('tcpdf')) {
             require_once dirname(__FILE__) . DIRECTORY_SEPARATOR . $this->tcpdf_dir . DIRECTORY_SEPARATOR . 'tcpdf.php';
         }
         if (!class_exists('fpdi')) {
             require_once dirname(__FILE__) . DIRECTORY_SEPARATOR . $this->fpdi_dir . DIRECTORY_SEPARATOR . 'fpdi.php';
         }
         $pdf = new FPDI('P', 'pt');
         $pdf->setMargins(0, 0, 0, 0);
         $pdf->SetAutoPageBreak(FALSE);
         $pdf->setFontSubsetting(FALSE);
         foreach ($this->objs as $obj) {
             $obj->setPDFObject($pdf);
             $obj->Output($type);
         }
         return $pdf->Output('', 'S');
     } elseif ($type == 'efile') {
         foreach ($this->objs as $obj) {
             return $obj->Output($type);
         }
     } elseif ($type == 'xml') {
         //Since multiple XML sections may need to be joined together,
         //We must pass the XML object between each form and  build the entire XML object completely
         //then output it all at once at the end.
         $xml = NULL;
         $xml_schema = NULL;
         foreach ($this->objs as $obj) {
             if (is_object($xml)) {
                 $obj->setXMLObject($xml);
             }
             $obj->Output($type);
             if (isset($obj->xml_schema)) {
                 $xml_schema = $obj->getClassDirectory() . DIRECTORY_SEPARATOR . 'schema' . DIRECTORY_SEPARATOR . $obj->xml_schema;
             }
             if ($xml == NULL and is_object($obj->getXMLObject())) {
                 $xml = $obj->getXMLObject();
             }
         }
         if (is_object($xml)) {
             $output = $xml->asXML();
             $xml_validation_retval = $this->validateXML($output, $xml_schema);
             if ($xml_validation_retval !== TRUE) {
                 Debug::text('XML Schema is invalid! Malformed XML!', __FILE__, __LINE__, __METHOD__, 10);
                 //$output = FALSE;
                 $output = $xml_validation_retval;
             }
         } else {
             Debug::text('No XML object!', __FILE__, __LINE__, __METHOD__, 10);
             $output = FALSE;
         }
         return $output;
     }
 }
 function Output($type)
 {
     $type = strtolower($type);
     //Initialize PDF object so all subclasses can access it.
     //Loop through all objects and combine the output from each into a single document.
     if ($type == 'pdf') {
         if (!class_exists('tcpdf')) {
             require_once dirname(__FILE__) . DIRECTORY_SEPARATOR . $this->tcpdf_dir . DIRECTORY_SEPARATOR . 'tcpdf.php';
         }
         if (!class_exists('fpdi')) {
             require_once dirname(__FILE__) . DIRECTORY_SEPARATOR . $this->fpdi_dir . DIRECTORY_SEPARATOR . 'fpdi.php';
         }
         $pdf = new FPDI('P', 'pt');
         $pdf->setMargins(0, 0, 0, 0);
         $pdf->SetAutoPageBreak(FALSE);
         foreach ($this->objs as $obj) {
             $obj->setPDFObject($pdf);
             $obj->Output($type);
         }
         return $pdf->Output('', 'S');
     }
 }
Example #12
0
 public function generatepdfAction(command $commande)
 {
     $request = $this->get('request');
     $tools = $this->get('tools.utils');
     $session = $request->getSession();
     if ($session->has('tpl')) {
         $tpl = $commande->getToprint();
         $pdffile = "";
         foreach ($tpl as $key => $elemnt) {
             foreach ($elemnt as $val) {
                 $prod = $this->getDoctrine()->getRepository('MainFrontBundle:paramtpl')->find($val['id']);
                 $template = $prod->getTpl();
                 $tplpdf = str_replace("../", "", $template->getPdf());
                 $pdffile = $this->get('kernel')->getRootDir() . '/../web/' . $tplpdf;
             }
         }
         $custom_layout = array(85, 55);
         $orientation = 'L';
         $pdf = new \FPDI($orientation, 'mm', $custom_layout, true, 'UTF-8', false);
         $pdf->setPageOrientation($orientation);
         $pdf->SetMargins(0, 0, 0);
         $pdf->SetAutoPageBreak(true, 0);
         $pdf->setFontSubsetting(false);
         $pdf->AddPage($orientation);
         //   echo "<pre>";print_r($pdf->getMargins());exit;
         $pdf->setSourceFile($pdffile);
         $_tplIdx = $pdf->importPage(1);
         $size = $pdf->useTemplate($_tplIdx, 0, 0, 85, 55, true);
         $idd = "";
         $i = 0;
         $oldx = 0;
         $oldy = 0;
         foreach ($elemnt as $value) {
             //if($i==0)
             if ($idd != $value['id'] && $value['value'] != "") {
                 $pdf->SetPageMark();
                 if (substr($value['value'], 0, 4) != "/tmp") {
                     //$tools->dump($value);
                     $align = strtoupper(substr($value['align'], 0, 1));
                     $color = $this->hex2rgb($value['color']);
                     $pdf->SetTextColor($color[0], $color[1], $color[2]);
                     $param = $this->getDoctrine()->getRepository('MainFrontBundle:paramtpl')->find($value['id']);
                     $y2 = $param->getX1() / 5;
                     $x1 = $param->getY1() / 5;
                     //$x1 = 10;$y2 = 8;
                     $w = $param->getX2() / 5;
                     $h = $param->getY2() / 5;
                     $oldx = $x1;
                     $oldy = $y2;
                     $pdf->SetX($x1, false);
                     $pdf->SetY($y2, false);
                     //$pdf->SetXY($x1, $y2,true);
                     $pdf->SetFont(null, '', $param->getSize() * 0.6);
                     //$param->getPolice()
                     // echo $opt->getFontsize()."\n";
                     $pdf->Cell($w, $h, $value["value"], 0, 0, $align);
                 } else {
                     $param = $this->getDoctrine()->getRepository('MainFrontBundle:paramtpl')->find($value['id']);
                     $img = $this->getParameter('base_url') . $value['value'];
                     $pdf->Image($img, $param->getX1() / 4.5, $param->getY1() / 4.55, $param->getX2() / 4.55, $param->getY2() / 4.5, '', '', '', true);
                 }
             }
             $idd = $value['id'];
             $i++;
         }
         //$pdf->Cell(0, $size['h'], 'TCPDF and FPDI');
         // echo $template->getId();
         $pdf->Output($this->get('kernel')->getRootDir() . '/../web/pdf.pdf');
     }
     return new Response("");
 }
Example #13
0
 public function test()
 {
     //        $rgb_arr = sscanf('rgb(243, 243, 243)', "rgb(%d, %d, %d)");
     //        print_r($this->rgbToCmyk($rgb_arr[0], $rgb_arr[1], $rgb_arr[2]));
     //        exit();
     //
     $img = new Imagick('test.jpg');
     $img->resizeimage(1076, 720, Imagick::FILTER_LANCZOS, 1);
     $img->setresolution(300, 300);
     $img->setimageformat('pdf');
     $img->writeimage('test.pdf');
     include_once APPPATH . 'libraries/tcpdf/tcpdf.php';
     include_once APPPATH . 'libraries/tcpdf/fpdi.php';
     // создаём лист
     $pdf = new FPDI('L', 'mm', array(91, 61), true, 'UTF-8', false);
     $pdf->AddPage('L');
     // загрузим ранее сохранённый шаблон
     $pdf->setSourceFile('test.pdf');
     $pdf->SetMargins(0, 0, 0, true);
     $tplIdx = $pdf->importPage(1);
     $pdf->useTemplate($tplIdx, null, null, 0, 0, true);
     // установим опции для pdf
     $pdf->SetMargins(0, 0, 0, true);
     $pdf->setCellHeightRatio(1);
     $pdf->setCellPaddings(0, 0, 0, 0);
     $pdf->setCellMargins(1, 1, 1, 1);
     $pdf->SetAutoPageBreak(false);
     $pdf->SetPrintHeader(false);
     $pdf->SetPrintFooter(false);
     $pdf->Image('qwe.png', 30, 30, 20, '', '', '', '', false, 300);
     $pdf->SetTextColor(0, 0, 0, 100);
     $pdf->SetFont('helvetica', 'BI', 10, '', 'false');
     $pdf->Text(12, 9, 'Black CMYK');
     $pdf->Output($_SERVER['DOCUMENT_ROOT'] . '/uploads/fynal.pdf', 'F');
     $im = new Imagick();
     $im->setResolution(300, 300);
     $im->readimage('uploads/fynal.pdf[0]');
     $im->setImageFormat('jpeg');
     $im->resizeimage(538, 360, Imagick::FILTER_LANCZOS, 1);
     $im->writeImage('uploads/fynal.jpg');
     $im->clear();
     $im->destroy();
     //        include_once APPPATH . 'libraries/drawer.php';
     //
     //        $drawer = new Drawer();
     //        $drawer->init();
     //        $drawer->setLayout();
     //        $drawer->setBackground('test.jpg');
     //        $drawer->drawImage('test.jpg', 10, 10, 30);
     //        $drawer->drawText('Maxim', 10, 10, 'TimesNewRoman', 20, 'rgb(77, 77, 77)');
     //        $drawer->savePdf($_SERVER['DOCUMENT_ROOT'] . '/1.pdf');
     //        $drawer->makePreview($_SERVER['DOCUMENT_ROOT'] . '/1.pdf', $_SERVER['DOCUMENT_ROOT'] . '/1.jpg');
 }
Example #14
0
 public function save_design()
 {
     if ($this->input->post('mode') == 'edit') {
         $this->db->delete('designs', array('id' => $this->input->post('design_id')));
     }
     $faceMacket = str_replace('http://klever.media/', '', $this->input->post('faceMacket'));
     $backMacket = str_replace('http://klever.media/', '', $this->input->post('backMacket'));
     $face = $this->input->post('face');
     $back = $this->input->post('back');
     // get all fonts
     $query = $this->db->get('fonts');
     $fonts = array();
     foreach ($query->result() as $font) {
         $fonts[$font->family] = $font->source;
     }
     // generate pdf face template name and preview name
     $face_pdf = 'uploads/redactor/face_' . md5(microtime(true)) . '.pdf';
     $face_preview = 'uploads/redactor/face_' . md5(microtime(true)) . '.jpg';
     // convert face image to pdf
     $img = new Imagick($faceMacket);
     $img->setresolution(300, 300);
     $img->setcolorspace(Imagick::COLORSPACE_CMYK);
     $img->resizeimage(1076, 720, Imagick::FILTER_LANCZOS, 1);
     $img->setimageformat('pdf');
     $img->writeimage($face_pdf);
     // include TCPDF ana FPDI
     include_once APPPATH . 'libraries/tcpdf/tcpdf.php';
     include_once APPPATH . 'libraries/tcpdf/fpdi.php';
     include_once APPPATH . 'libraries/tcpdf/include/tcpdf_fonts.php';
     $fontMaker = new TCPDF_FONTS();
     // создаём лист
     $pdf = new FPDI('L', 'mm', array(91, 61), true, 'UTF-8', false);
     $pdf->SetMargins(0, 0, 0, true);
     $pdf->AddPage('L');
     // загрузим ранее сохранённый шаблон
     $pdf->setSourceFile($face_pdf);
     $pdf->SetMargins(0, 0, 0, true);
     $tplIdx = $pdf->importPage(1);
     $pdf->useTemplate($tplIdx, null, null, 0, 0, true);
     // установим опции для pdf
     $pdf->setCellHeightRatio(1);
     $pdf->setCellPaddings(0, 0, 0, 0);
     $pdf->setCellMargins(0, 0, 0, 0);
     $pdf->SetAutoPageBreak(false, 0);
     $pdf->SetPrintHeader(false);
     $pdf->SetPrintFooter(false);
     if (!empty($face)) {
         // отрисуем сначала изображения лица
         foreach ($face as $item) {
             if ($item['type'] == 'image') {
                 $pdf->Image($_SERVER['DOCUMENT_ROOT'] . '/' . str_replace('http://klever.media/', '', $item['content']), $this->px_to_mm($item['left']), $this->px_to_mm($item['top']), $this->px_to_mm($item['width']), '', '', '', '', false, 300);
             }
         }
         // потом текст на лице
         foreach ($face as $item) {
             if ($item['type'] == 'text') {
                 $cmyk = $this->rgbToCmyk($item['color']);
                 $pdf->SetTextColor($cmyk['c'] * 100, $cmyk['m'] * 100, $cmyk['y'] * 100, $cmyk['k'] * 100);
                 // set font
                 $tcpdfFont = $fontMaker->addTTFfont(realpath('fonts/redactor/' . $fonts[$item['font']]));
                 $pdf->SetFont($tcpdfFont, '', $item['size'] / 2, '', 'false');
                 $pdf->Text($this->px_to_mm($item['left']), $this->px_to_mm($item['top']), $item['content'], false, false, true, 0, 0, 'L', false, '', 0, false, 'T', 'L', false);
             }
         }
     }
     // сохраним пдф лица
     $pdf->Output($_SERVER['DOCUMENT_ROOT'] . '/' . $face_pdf, 'F');
     // сделаем превью для пользователя
     $im = new Imagick();
     $im->setResolution(300, 300);
     $im->readimage($face_pdf . '[0]');
     $im->flattenimages();
     $im->setImageFormat('jpg');
     $im->resizeimage(1076, 720, Imagick::FILTER_LANCZOS, 1);
     $im->writeImage($face_preview);
     $im->clear();
     $im->destroy();
     //exec('$ convert ' . $_SERVER['DOCUMENT_ROOT'] . '/' . $face_pdf . ' ' . $_SERVER['DOCUMENT_ROOT'] . '/' . $face_preview);
     // есть ли оборот
     if (!empty($backMacket)) {
         // generate pdf back template name and preview name
         $back_pdf = 'uploads/redactor/back_' . md5(microtime(true)) . '.pdf';
         $back_preview = 'uploads/redactor/back_' . md5(microtime(true)) . '.jpg';
         // convert back image to pdf
         $img = new Imagick($backMacket);
         $img->setresolution(300, 300);
         $img->setcolorspace(Imagick::COLORSPACE_CMYK);
         $img->resizeimage(1076, 720, Imagick::FILTER_LANCZOS, 1);
         $img->setimageformat('pdf');
         $img->writeimage($back_pdf);
         // создаём лист
         $pdf = new FPDI('L', 'mm', array(91, 61), true, 'UTF-8', false);
         $pdf->AddPage('L');
         // загрузим ранее сохранённый шаблон
         $pdf->setSourceFile($_SERVER['DOCUMENT_ROOT'] . '/' . $back_pdf);
         $pdf->SetMargins(0, 0, 0, true);
         $tplIdx = $pdf->importPage(1);
         $pdf->useTemplate($tplIdx, null, null, 0, 0, true);
         // установим опции для pdf
         $pdf->SetMargins(0, 0, 0, true);
         $pdf->setCellHeightRatio(1);
         $pdf->setCellPaddings(0, 0, 0, 0);
         $pdf->setCellMargins(1, 1, 1, 1);
         $pdf->SetAutoPageBreak(false);
         $pdf->SetPrintHeader(false);
         $pdf->SetPrintFooter(false);
         if (!empty($back)) {
             // отрисуем сначала изображения оборота
             foreach ($back as $item) {
                 if ($item['type'] == 'image') {
                     $pdf->Image($_SERVER['DOCUMENT_ROOT'] . '/' . str_replace('http://klever.media/', '', $item['content']), $this->px_to_mm($item['left']), $this->px_to_mm($item['top']), $this->px_to_mm($item['width']), '', '', '', '', false, 300);
                 }
             }
             // потом текст на обороте
             foreach ($back as $item) {
                 if ($item['type'] == 'text') {
                     $cmyk = $this->rgbToCmyk($item['color']);
                     $pdf->SetTextColor($cmyk['c'] * 100, $cmyk['m'] * 100, $cmyk['y'] * 100, $cmyk['k'] * 100);
                     // set font
                     $tcpdfFont = $fontMaker->addTTFfont($_SERVER['DOCUMENT_ROOT'] . '/fonts/redactor/' . $fonts[$item['font']]);
                     $pdf->SetFont($tcpdfFont, '', $item['size'] / 2, '', 'false');
                     $pdf->Text($this->px_to_mm($item['left']), $this->px_to_mm($item['top']), $item['content'], false, false, true, 0, 0, 'L', false, '', 0, false, 'T', 'L', false);
                 }
             }
         }
         // сохраним пдф оборота
         $pdf->Output($_SERVER['DOCUMENT_ROOT'] . '/' . $back_pdf, 'F');
         // сделаем превью для пользователя
         $im = new Imagick();
         $im->setResolution(300, 300);
         $im->readimage($back_pdf . '[0]');
         $im->setImageFormat('jpg');
         $im->flattenimages();
         $im->resizeimage(1076, 720, Imagick::FILTER_LANCZOS, 1);
         $im->writeImage($back_preview);
         $im->clear();
         $im->destroy();
     }
     $this->db->insert('products', array('name' => 'cards_pvc', 'tiraj' => 100, 'weight' => 0.5, 'price' => 0.49, 'cost' => 49, 'macket' => 'my_macket'));
     $product_id = $this->db->insert_id();
     $this->db->insert('designs', array('product_id' => $product_id, 'theme_id' => $this->input->post('theme'), 'face_background' => $faceMacket, 'back_background' => empty($backMacket) ? NULL : $backMacket, 'face' => $face_preview, 'back' => empty($back_preview) ? '' : $back_preview, 'type' => 'system'));
     $design_id = $this->db->insert_id();
     $options = array();
     if (!empty($face)) {
         foreach ($face as $item) {
             if ($item['type'] == 'text') {
                 $options[] = array('design_id' => $design_id, 'type' => 'text', 'front' => 'face', 'top' => $item['top'], 'left' => $item['left'], 'width' => NULL, 'height' => NULL, 'content' => $item['content'], 'font' => $item['font'], 'color' => $item['color'], 'size' => $item['size']);
             } else {
                 $options[] = array('design_id' => $design_id, 'type' => 'image', 'front' => 'face', 'top' => $item['top'], 'left' => $item['left'], 'width' => $item['width'], 'height' => $item['height'], 'content' => $item['content'], 'font' => NULL, 'color' => NULL, 'size' => NULL);
             }
         }
     }
     if (!empty($back)) {
         foreach ($back as $item) {
             if ($item['type'] == 'text') {
                 $options[] = array('design_id' => $design_id, 'type' => 'text', 'front' => 'back', 'top' => $item['top'], 'left' => $item['left'], 'width' => NULL, 'height' => NULL, 'content' => $item['content'], 'font' => $item['font'], 'color' => $item['color'], 'size' => $item['size']);
             } else {
                 $options[] = array('design_id' => $design_id, 'type' => 'image', 'front' => 'back', 'top' => $item['top'], 'left' => $item['left'], 'width' => $item['width'], 'height' => $item['height'], 'content' => $item['content'], 'font' => NULL, 'color' => NULL, 'size' => NULL);
             }
         }
     }
     if (count($options) > 0) {
         $this->db->insert_batch('design_options', $options);
     }
     echo 'OK';
 }
Example #15
0
 public function generatepdfAction($id)
 {
     $width = 320;
     $height = 450;
     $pdfmerge = $this->getDoctrine()->getRepository('PrintBundle:Pdfmerge')->find($id);
     $elementwidth = $pdfmerge->getWidth();
     $elementheight = $pdfmerge->getHeight();
     $marge = $pdfmerge->getMarge();
     $singlewidth = $elementwidth + $marge;
     $singleheight = $elementheight + $marge;
     // test occupation
     $test1 = (int) ($height / $singleheight) * (int) ($width / $singlewidth);
     $test2 = (int) ($width / $singleheight) * (int) ($height / $singlewidth);
     if ($test1 >= $test2) {
         $width = 320;
         $height = 450;
         $orientation = "P";
     } else {
         $width = 450;
         $height = 320;
         $orientation = "L";
     }
     // calculate margin
     $nbrX = (int) ($width / $singlewidth);
     $nbrY = (int) ($height / $singleheight);
     $marginleft = ($width - $nbrX * $singlewidth) / 2;
     $margintop = ($height - $nbrY * $singleheight) / 2;
     //print_r(array($orientation, $marginleft, $margintop));
     $custom_layout = array($width, $height);
     $pdf = new \FPDI($orientation, 'mm', 'SRA3', true, 'UTF-8', false);
     $pdf->setPageOrientation($orientation);
     $pdf->setPrintHeader(false);
     $pdf->setPrintFooter(false);
     $pdf->SetMargins($marginleft, 40, $marginleft);
     $pdf->SetAutoPageBreak(true, 40);
     $pdf->setFontSubsetting(false);
     // add a page
     $pdf->AddPage($orientation);
     $i = 0;
     $path = $this->get('kernel')->getRootDir() . '/../web/';
     $toaddheight = $margintop;
     $face = array();
     $j = 0;
     foreach ($pdfmerge->getPdflist() as $list) {
         for ($k = 0; $k < $list->getRepeat(); $k++) {
             if ($i == $nbrX) {
                 $i = 0;
                 $j++;
                 $toaddheight += $singleheight;
             }
             $toaddwidth = $i * $singlewidth + $marginleft;
             $face[$toaddheight][$toaddwidth] = $list->getFile();
             $i++;
         }
     }
     $reverse = array();
     foreach ($face as $y => $value) {
         foreach ($value as $x => $fichier) {
             $file = $path . $fichier;
             $pdf->setSourceFile($file);
             $_tplIdx = $pdf->importPage(1);
             $size = $pdf->useTemplate($_tplIdx, $x, $y, 85);
             $reverse[$y][$x] = $fichier;
         }
     }
     //echo "<pre>";print_r($face);exit;
     $this->repert($pdf, $face, $marginleft, $margintop, $singlewidth, $singleheight, $height, $width);
     if ($pdfmerge->getNbpage() == 2) {
         $pdf->AddPage($orientation);
         foreach ($reverse as $y => $value) {
             foreach ($value as $x => $fichier) {
                 $file = $path . $fichier;
                 $pdf->setSourceFile($file);
                 $_tplIdx = $pdf->importPage(2);
                 $size = $pdf->useTemplate($_tplIdx, $x, $y, 85);
                 $reverse[$y][$x] = $fichier;
             }
         }
         $this->repert($pdf, $face, $marginleft, $margintop, $singlewidth, $singleheight, $height, $width);
     }
     $pdf->Output("aaa.pdf", 'I');
 }
Example #16
0
         //add file to array
         $tif_files[] = $dir_fax_temp . '/' . $fax_name . '.tif';
     }
     //if
 }
 //foreach
 // unique id for this fax
 $fax_instance_uuid = uuid();
 //generate cover page, merge with pdf
 if ($fax_subject != '' || $fax_message != '') {
     //load pdf libraries
     require_once "resources/tcpdf/tcpdf.php";
     require_once "resources/fpdi/fpdi.php";
     // initialize pdf
     $pdf = new FPDI('P', 'in');
     $pdf->SetAutoPageBreak(false);
     $pdf->setPrintHeader(false);
     $pdf->setPrintFooter(false);
     $pdf->SetMargins(0, 0, 0, true);
     if (strlen($fax_cover_font) > 0) {
         if (substr($fax_cover_font, -4) == '.ttf') {
             $pdf_font = TCPDF_FONTS::addTTFfont($fax_cover_font);
         } else {
             $pdf_font = $fax_cover_font;
         }
     }
     if (!$pdf_font) {
         $pdf_font = 'times';
     }
     //add blank page
     $pdf->AddPage('P', array($page_width, $page_height));
Example #17
0
/**
 * Creates a personalized exam file.
 *
 * @param unknown $examid        	
 * @return NULL
 */
function emarking_download_exam($examid, $multiplepdfs = false, $groupid = null, $pbar = null, $sendprintorder = false, $printername = null)
{
    global $DB, $CFG, $USER, $OUTPUT;
    // Se obtiene el examen
    if (!($downloadexam = $DB->get_record('emarking_exams', array('id' => $examid)))) {
        return null;
    }
    // Contexto del curso para verificar permisos
    $context = context_course::instance($downloadexam->course);
    if (!has_capability('mod/emarking:downloadexam', $context)) {
        return null;
    }
    // Verify that remote printing is enable, otherwise disable a printing order
    if ($sendprintorder && (!$CFG->emarking_enableprinting || $printername == null)) {
        return null;
    }
    $course = $DB->get_record('course', array('id' => $downloadexam->course));
    $coursecat = $DB->get_record('course_categories', array('id' => $course->category));
    if ($downloadexam->printrandom == 1) {
        $enrolincludes = 'manual,self,meta';
    } else {
        $enrolincludes = 'manual,self';
    }
    if ($CFG->emarking_enrolincludes && strlen($CFG->emarking_enrolincludes) > 1) {
        $enrolincludes = $CFG->emarking_enrolincludes;
    }
    if (isset($downloadexam->enrolments) && strlen($downloadexam->enrolments) > 1) {
        $enrolincludes = $downloadexam->enrolments;
    }
    $enrolincludes = explode(",", $enrolincludes);
    // Get all the files uploaded as forms for this exam
    $fs = get_file_storage();
    $files = $fs->get_area_files($context->id, 'mod_emarking', 'exams', $examid);
    // We filter only the PDFs
    $pdffileshash = array();
    foreach ($files as $filepdf) {
        if ($filepdf->get_mimetype() === 'application/pdf') {
            $pdffileshash[] = array('hash' => $filepdf->get_pathnamehash(), 'filename' => $filepdf->get_filename());
        }
    }
    // Verify that at least we have a PDF
    if (count($pdffileshash) < 1) {
        return null;
    }
    if ($downloadexam->headerqr == 1) {
        if ($groupid != null) {
            $filedir = $CFG->dataroot . "/temp/emarking/{$context->id}" . "/group_" . $groupid;
        } else {
            $filedir = $CFG->dataroot . "/temp/emarking/{$context->id}";
        }
        $fileimg = $CFG->dataroot . "/temp/emarking/{$context->id}/qr";
        $userimgdir = $CFG->dataroot . "/temp/emarking/{$context->id}/u";
        emarking_initialize_directory($filedir, true);
        emarking_initialize_directory($fileimg, true);
        emarking_initialize_directory($userimgdir, true);
        if ($groupid != null) {
            // Se toman los resultados del query dentro de una variable.
            $students = emarking_get_students_of_groups($downloadexam->course, $groupid);
        } else {
            // Se toman los resultados del query dentro de una variable.
            $students = emarking_get_students_for_printing($downloadexam->course);
        }
        $nombre = array();
        $current = 0;
        // Los resultados del query se recorren mediante un foreach loop.
        foreach ($students as $student) {
            if (array_search($student->enrol, $enrolincludes) === false) {
                continue;
            }
            $nombre[] = substr("{$student->lastname}, {$student->firstname}", 0, 65);
            $rut[] = $student->idnumber;
            $moodleid[] = $student->id;
            // Get the image file for student
            $imgfound = false;
            if ($CFG->emarking_pathuserpicture && is_dir($CFG->emarking_pathuserpicture)) {
                $idstring = "" . $student->idnumber;
                $revid = strrev($idstring);
                $idpath = $CFG->emarking_pathuserpicture;
                $idpath .= "/" . substr($revid, 0, 1);
                $idpath .= "/" . substr($revid, 1, 1);
                if (file_exists($idpath . "/user{$idstring}.png")) {
                    $userimg[] = $idpath . "/user{$idstring}.png";
                    $imgfound = true;
                }
            }
            if (!$imgfound) {
                $usercontext = context_user::instance($student->id);
                $imgfile = $DB->get_record('files', array('contextid' => $usercontext->id, 'component' => 'user', 'filearea' => 'icon', 'filename' => 'f1.png'));
                if ($imgfile) {
                    $userimg[] = emarking_get_path_from_hash($userimgdir, $imgfile->pathnamehash, "u" . $student->id, true);
                } else {
                    $userimg[] = $CFG->dirroot . "/pix/u/f1.png";
                }
            }
        }
        $numberstudents = count($nombre);
        for ($i = $numberstudents; $i < $numberstudents + $downloadexam->extraexams; $i++) {
            $nombre[$i] = '..............................................................................';
            $rut[$i] = '0';
            $moodleid[$i] = '0';
            $userimg[$i] = $CFG->dirroot . "/pix/u/f1.png";
        }
        $newfile = emarking_get_path_from_hash($filedir, $pdffileshash[$current]['hash']);
        $path = $filedir . "/" . str_replace(' ', '-', $pdffileshash[$current]['filename']);
        $hash = hash_file('md5', $path);
        $logoisconfigured = false;
        if ($logofile = emarking_get_logo_file()) {
            $logofilepath = emarking_get_path_from_hash($filedir, $logofile->get_pathnamehash());
            $logoisconfigured = true;
        }
        $file1 = $filedir . "/" . emarking_clean_filename($course->shortname, true) . "_" . emarking_clean_filename($downloadexam->name, true) . ".pdf";
        $pdf = new FPDI();
        $cp = $pdf->setSourceFile($path);
        if ($cp > 99) {
            print_error(get_string('page', 'mod_emarking'));
        }
        if ($multiplepdfs || $groupid != null) {
            $zip = new ZipArchive();
            if ($groupid != null) {
                $file1 = $filedir . "/" . emarking_clean_filename($course->shortname, true) . "_" . "GRUPO_" . $groupid . "_" . emarking_clean_filename($downloadexam->name, true) . ".zip";
            } else {
                $file1 = $filedir . "/" . emarking_clean_filename($course->shortname, true) . "_" . emarking_clean_filename($downloadexam->name, true) . ".zip";
            }
            if ($zip->open($file1, ZipArchive::CREATE) !== true) {
                return null;
            }
        }
        if ($sendprintorder) {
            if ($pbar != null) {
                $pbar->update(0, count($nombre), '');
            }
        }
        $jobs[] = array();
        if ($downloadexam->printlist == 1) {
            $flag = 0;
            // lista de alumnos
            if ($flag == 0) {
                $pdf->SetAutoPageBreak(false);
                $pdf->AddPage();
                $left = 85;
                $top = 8;
                $pdf->SetFont('Helvetica', 'B', 12);
                $pdf->SetXY($left, $top);
                $pdf->Write(1, core_text::strtoupper("LISTA DE ALUMNOS"));
                $left = 15;
                $top = 16;
                $pdf->SetFont('Helvetica', '', 8);
                $pdf->SetXY($left, $top);
                $pdf->Write(1, core_text::strtoupper("Asignatura: " . $course->fullname));
                $left = 15;
                $top = 22;
                $pdf->SetFont('Helvetica', '', 8);
                $pdf->SetXY($left, $top);
                $pdf->Write(1, core_text::strtoupper("N° Inscritos: " . count($nombre)));
                // $year = date("Y");
                // $month= date("F");
                // $day= date("m");
                setlocale(LC_ALL, "es_ES");
                $left = 15;
                $top = 28;
                $pdf->SetFont('Helvetica', '', 8);
                $pdf->SetXY($left, $top);
                $pdf->Write(1, core_text::strtoupper("Fecha: " . strftime("%A %d de %B del %Y")));
                $left = 15;
                $top = 36;
                $pdf->SetXY($left, $top);
                $pdf->Cell(10, 10, "N°", 1, 0, 'L');
                $pdf->Cell(120, 10, "Nombres", 1, 0, 'L');
                $pdf->Cell(50, 10, "Firmas", 1, 0, 'L');
                $t = 0;
                $t2 = 46;
                for ($a = 0; $a <= count($nombre) - 1; $a++) {
                    if ($n == 24 || $n == 48 || $n == 72 || $n == 96 || $n == 120) {
                        $pdf->AddPage();
                        $t = 0;
                        $t2 = 8;
                    }
                    $top = $t2 + $t;
                    $n = $a + 1;
                    $pdf->SetFont('Helvetica', '', 8);
                    $pdf->SetXY($left, $top);
                    $pdf->Cell(10, 10, $n . ")", 1, 0, 'L');
                    $pdf->Cell(120, 10, core_text::strtoupper($nombre[$a]), 1, 0, 'L');
                    $pdf->Cell(50, 10, "", 1, 0, 'L');
                    // $pdf->Write ( 1, core_text::strtoupper ( $nombre [$a] ) );
                    $t = $t + 10;
                }
                $flag = 1;
                if ($multiplepdfs || $groupid != null) {
                    if ($groupid != null) {
                        $pdffile = $filedir . "/Lista_de_alumnos_" . "GRUPO_" . $groupid . ".pdf";
                        $pdf->Output($pdffile, "F");
                        // se genera el nuevo pdf
                        $zip->addFile($pdffile, "GRUPO_" . $groupid . ".pdf");
                    } else {
                        $pdffile = $filedir . "/Lista_de_alumnos_" . emarking_clean_filename($course->shortname, true) . ".pdf";
                        $pdf->Output($pdffile, "F");
                        // se genera el nuevo pdf
                        $zip->addFile($pdffile, "Lista_de_alumnos_" . emarking_clean_filename($course->shortname, true) . ".pdf");
                    }
                }
                $printername = explode(',', $CFG->emarking_printername);
                if ($sendprintorder) {
                    if ($printername[$_POST["printername"]] != "Edificio-C-mesonSecretaria") {
                        $command = "lp -d " . $printername[$_POST["printername"]] . " -o StapleLocation=UpperLeft -o fit-to-page -o media=Letter " . $pdffile;
                    } else {
                        $command = "lp -d " . $printername[$_POST["printername"]] . " -o StapleLocation=SinglePortrait -o PageSize=Letter -o Duplex=none " . $pdffile;
                    }
                    $printresult = exec($command);
                    if ($CFG->debug) {
                        echo "{$command} <br>";
                        echo "{$printresult} <hr>";
                    }
                }
            }
        }
        // Here we produce a PDF file for each student
        for ($k = 0; $k <= count($nombre) - 1; $k++) {
            // If there are multiplepdfs we have to produce one per student
            if ($multiplepdfs || $sendprintorder || $groupid != null) {
                $pdf = new FPDI();
            }
            if ($multiplepdfs || $sendprintorder || $groupid != null || count($pdffileshash) > 1) {
                $current++;
                if ($current > count($pdffileshash) - 1) {
                    $current = 0;
                }
                $newfile = emarking_get_path_from_hash($filedir, $pdffileshash[$current]['hash']);
                $path = $filedir . "/" . str_replace(' ', '-', $pdffileshash[$current]['filename']);
                $cp = $pdf->setSourceFile($path);
            }
            $pdf->SetAutoPageBreak(false);
            for ($i = 1; $i <= $cp + $downloadexam->extrasheets; $i = $i + 1) {
                $h = rand(1, 999999);
                $img = $fileimg . "/qr" . $h . "_" . $rut[$k] . "_" . $i . "_" . $hash . ".png";
                $imgrotated = $fileimg . "/qr" . $h . "_" . $rut[$k] . "_" . $i . "_" . $hash . "r.png";
                // Se genera QR con id, curso y número de página
                $qrstring = "{$moodleid[$k]} - {$downloadexam->course} - {$i}";
                QRcode::png($qrstring, $img);
                // se inserta QR
                QRcode::png($qrstring . " - R", $imgrotated);
                // se inserta QR
                $gdimg = imagecreatefrompng($imgrotated);
                $rotated = imagerotate($gdimg, 180, 0);
                imagepng($rotated, $imgrotated);
                $pdf->AddPage();
                // Agrega una nueva página
                if ($i <= $cp) {
                    $tplIdx = $pdf->importPage($i);
                    // Se importan las páginas del documento pdf.
                    $pdf->useTemplate($tplIdx, 0, 0, 0, 0, $adjustPageSize = true);
                    // se inserta como template el archivo pdf subido
                }
                /*
                 * Ahora se escribe texto sobre las páginas ya importadas. Se fija la fuente, el tipo y el tamaño de la letra. Se señala el título. Se da el nombre, apellido y rut del alumno al cual pertenece la prueba. Se indica el curso correspondiente a la evaluación. Se introduce una imagen. Esta corresponde al QR que se genera con los datos
                 */
                if ($CFG->emarking_includelogo && $logoisconfigured) {
                    $pdf->Image($logofilepath, 2, 8, 30);
                }
                $left = 58;
                $top = 8;
                $pdf->SetFont('Helvetica', '', 12);
                $pdf->SetXY($left, $top);
                $pdf->Write(1, core_text::strtoupper($downloadexam->name));
                $pdf->SetFont('Helvetica', '', 9);
                $top += 5;
                $pdf->SetXY($left, $top);
                $pdf->Write(1, core_text::strtoupper(get_string('name') . ": " . $nombre[$k]));
                $top += 4;
                if ($rut[$k] && strlen($rut[$k]) > 0) {
                    $pdf->SetXY($left, $top);
                    $pdf->Write(1, get_string('idnumber', 'mod_emarking') . ": " . $rut[$k]);
                    $top += 4;
                }
                $pdf->SetXY($left, $top);
                $pdf->Write(1, core_text::strtoupper(get_string('course') . ": " . $course->fullname));
                $top += 4;
                if (file_exists($userimg[$k])) {
                    $pdf->Image($userimg[$k], 35, 8, 15, 15, "PNG", null, "T", true);
                }
                $totals = new stdClass();
                $totals->identified = $i;
                $totals->total = $cp + $downloadexam->extrasheets;
                $pdf->SetXY($left, $top);
                $pdf->Write(1, core_text::strtoupper(get_string('page') . ": " . get_string('aofb', 'mod_emarking', $totals)));
                $pdf->Image($img, 176, 3, 34);
                // y antes era -2
                $pdf->Image($imgrotated, 0, $pdf->getPageHeight() - 35, 34);
                unlink($img);
                unlink($imgrotated);
            }
            if ($multiplepdfs || $sendprintorder || $groupid != null) {
                $pdffile = $filedir . "/" . emarking_clean_filename($qrstring) . ".pdf";
                if (file_exists($pdffile)) {
                    $pdffile = $filedir . "/" . emarking_clean_filename($qrstring) . "_" . $k . ".pdf";
                    $pdf->Output($pdffile, "F");
                    // se genera el nuevo pdf
                    $zip->addFile($pdffile, emarking_clean_filename($qrstring) . "_" . $k . ".pdf");
                } else {
                    $pdffile = $filedir . "/" . emarking_clean_filename($qrstring) . ".pdf";
                    $pdf->Output($pdffile, "F");
                    // se genera el nuevo pdf
                    $zip->addFile($pdffile, emarking_clean_filename($qrstring) . ".pdf");
                }
                $jobs[$k]["param_1_pbar"] = $k + 1;
                $jobs[$k]["param_2_pbar"] = count($nombre);
                $jobs[$k]["param_3_pbar"] = 'Imprimiendo pruebas de ' . core_text::strtoupper($nombre[$k]);
                $jobs[$k]["name_job"] = $pdffile;
            }
        }
        $printername = explode(',', $CFG->emarking_printername);
        if ($sendprintorder) {
            foreach ($jobs as &$valor) {
                if (!empty($valor)) {
                    if ($pbar != null) {
                        $pbar->update($valor["param_1_pbar"], $valor["param_2_pbar"], $valor["param_3_pbar"]);
                    }
                    if ($printername[$_POST["printername"]] != "Edificio-C-mesonSecretaria") {
                        $command = "lp -d " . $printername[$_POST["printername"]] . " -o StapleLocation=UpperLeft -o fit-to-page -o media=Letter " . $valor["name_job"];
                    } else {
                        $command = "lp -d " . $printername[$_POST["printername"]] . " -o StapleLocation=SinglePortrait -o PageSize=Letter -o Duplex=none " . $valor["name_job"];
                    }
                    $printresult = exec($command);
                    if ($CFG->debug) {
                        echo "{$command} <br>";
                        echo "{$printresult} <hr>";
                    }
                }
            }
        }
        if ($multiplepdfs || $groupid != null) {
            // Generate Bat File
            $printerarray = array();
            foreach (explode(',', $CFG->emarking_printername) as $printer) {
                $printerarray[] = $printer;
            }
            $contenido = "@echo off\r\n";
            $contenido .= "TITLE Sistema de impresion\r\n";
            $contenido .= "color ff\r\n";
            $contenido .= "cls\r\n";
            $contenido .= ":MENUPPL\r\n";
            $contenido .= "cls\r\n";
            $contenido .= "echo #######################################################################\r\n";
            $contenido .= "echo #                     Sistema de impresion                            #\r\n";
            $contenido .= "echo #                                                                     #\r\n";
            $contenido .= "echo # @copyright 2014 Eduardo Miranda                                     #\r\n";
            $contenido .= "echo # Fecha Modificacion 23-04-2014                                       #\r\n";
            $contenido .= "echo #                                                                     #\r\n";
            $contenido .= "echo #   Para realizar la impresion debe seleccionar una de las impresoras #\r\n";
            $contenido .= "echo #   configuradas.                                                     #\r\n";
            $contenido .= "echo #                                                                     #\r\n";
            $contenido .= "echo #                                                                     #\r\n";
            $contenido .= "echo #######################################################################\r\n";
            $contenido .= "echo #   Seleccione una impresora:                                         #\r\n";
            $i = 0;
            while ($i < count($printerarray)) {
                $contenido .= "echo #   " . $i . " - " . $printerarray[$i] . "                                                   #\r\n";
                $i++;
            }
            $contenido .= "echo #   " . $i++ . " - Cancelar                                                      #\r\n";
            $contenido .= "echo #                                                                     #\r\n";
            $contenido .= "echo #######################################################################\r\n";
            $contenido .= "set /p preg01= Que desea hacer? [";
            $i = 0;
            while ($i <= count($printerarray)) {
                if ($i == count($printerarray)) {
                    $contenido .= $i;
                } else {
                    $contenido .= $i . ",";
                }
                $i++;
            }
            $contenido .= "]\r\n";
            $i = 0;
            while ($i < count($printerarray)) {
                $contenido .= "if %preg01%==" . $i . " goto MENU" . $i . "\r\n";
                $i++;
            }
            $contenido .= "if %preg01%==" . $i++ . " goto SALIR\r\n";
            $contenido .= "goto MENU\r\n";
            $contenido .= "pause\r\n";
            $i = 0;
            while ($i < count($printerarray)) {
                $contenido .= ":MENU" . $i . "\r\n";
                $contenido .= "cls\r\n";
                $contenido .= "set N=%Random%%random%\r\n";
                $contenido .= "plink central.apuntes mkdir -m 0777 ~/pruebas/%N%\r\n";
                $contenido .= "pscp *.pdf central.apuntes:pruebas/%N%\r\n";
                $contenido .= "plink central.apuntes cp ~/pruebas/script_pruebas.sh ~/pruebas/%N%\r\n";
                $contenido .= "plink central.apuntes cd pruebas/%N%;./script_pruebas.sh " . $printerarray[$i] . "\r\n";
                $contenido .= "plink central.apuntes rm -dfr ~/pruebas/%N%\r\n";
                $contenido .= "EXIT\r\n";
                $i++;
            }
            $contenido .= ":SALIR\r\n";
            $contenido .= "CLS\r\n";
            $contenido .= "ECHO Cancelando...\r\n";
            $contenido .= "EXIT\r\n";
            $random = rand();
            mkdir($CFG->dataroot . '/temp/emarking/' . $random . '_bat/', 0777);
            // chmod($random."_bat/", 0777);
            $fp = fopen($CFG->dataroot . "/temp/emarking/" . $random . "_bat/imprimir.bat", "x");
            fwrite($fp, $contenido);
            fclose($fp);
            // Generate zip file
            $zip->addFile($CFG->dataroot . "/temp/emarking/" . $random . "_bat/imprimir.bat", "imprimir.bat");
            $zip->close();
            unlink($CFG->dataroot . "/temp/emarking/" . $random . "_bat/imprimir.bat");
            rmdir($CFG->dataroot . "/temp/emarking/" . $random . "_bat");
        } else {
            if (!$sendprintorder) {
                $pdf->Output($file1, "F");
                // se genera el nuevo pdf
            }
        }
        $downloadexam->status = EMARKING_EXAM_SENT_TO_PRINT;
        $downloadexam->printdate = time();
        $DB->update_record('emarking_exams', $downloadexam);
        if ($sendprintorder) {
            $pbar->update_full(100, 'Impresión completada exitosamente');
            return $filedir;
        }
        if ($groupid != null) {
            unlink($file1);
            return $filedir;
        } else {
            ob_start();
            // modificación: ingreso de esta linea, ya que anterior revisión mostraba error en el archivo
            header('Content-Description: File Transfer');
            header('Content-Type: application/x-download');
            header('Content-Disposition: attachment; filename=' . basename($file1));
            header('Content-Transfer-Encoding: binary');
            header('Expires: 0');
            header('Cache-Control: must-revalidate');
            header('Pragma: public');
            ob_clean();
            flush();
            readfile($file1);
            unlink($file1);
            // borra archivo temporal en moodledata
            exit;
        }
        return false;
    } else {
        $students = emarking_get_students_for_printing($downloadexam->course);
        $filedir = $CFG->dataroot . "/temp/emarking/{$context->id}";
        emarking_initialize_directory($filedir, true);
        $printername = explode(',', $CFG->emarking_printername);
        $totalAlumn = 0;
        $pdffiles = array();
        for ($current = 0; $current < count($pdffileshash); $current++) {
            $newfile = emarking_get_path_from_hash($filedir, $pdffileshash[$current]['hash']);
            $path = $filedir . "/" . str_replace(' ', '-', $pdffileshash[$current]['filename']);
            $pdf = new FPDI();
            $cp = $pdf->setSourceFile($path);
            if ($cp > 99) {
                print_error(get_string('page', 'mod_emarking'));
            }
            $pdf->SetAutoPageBreak(false);
            $s = 1;
            while ($s <= $cp + $downloadexam->extrasheets) {
                $pdf->AddPage();
                if ($s <= $cp) {
                    $tplIdx = $pdf->importPage($s);
                    // Se importan las páginas del documento pdf.
                    $pdf->useTemplate($tplIdx, 0, 0, 0, 0, $adjustPageSize = true);
                    // se inserta como template el archivo pdf subido
                }
                $s++;
            }
            $pdffile = $filedir . "/" . $current . emarking_clean_filename($file->filename);
            $pdf->Output($pdffile, "F");
            $pdffiles[] = $pdffile;
        }
        $totalAlumn = count($students);
        if ($pbar != null) {
            $pbar->update(0, $totalAlumn, '');
        }
        for ($k = 0; $k <= $totalAlumn + $downloadexam->extraexams - 1; $k++) {
            $pdffile = $pdffiles[$k % count($pdffileshash)];
            if ($printername[$_POST["printername"]] != "Edificio-C-mesonSecretaria") {
                $command = "lp -d " . $printername[$_POST["printername"]] . " -o StapleLocation=UpperLeft -o fit-to-page -o media=Letter " . $pdffile;
            } else {
                $command = "lp -d " . $printername[$_POST["printername"]] . " -o StapleLocation=SinglePortrait -o PageSize=Letter -o Duplex=none " . $pdffile;
            }
            // $printresult = exec ( $command );
            if ($CFG->debug) {
                echo "{$command} <br>";
                echo "{$printresult} <hr>";
            }
            if ($pbar != null) {
                $pbar->update($k, $totalAlumn, '');
            }
        }
        $pbar->update_full(100, 'Impresión completada exitosamente');
        return true;
        /*
         * $downloadexam->status = EMARKING_EXAM_SENT_TO_PRINT; $downloadexam->printdate = time (); $DB->update_record ( 'emarking_exams', $downloadexam ); $downloadURL = $CFG->wwwroot . '/pluginfile.php/' . $file->contextid . '/mod_emarking/' . $file->filearea . '/' . $file->itemid . '/' . $file->filename; $startdownload = true; echo '<meta http-equiv="refresh" content="2;url=' . $downloadURL . '">'; return true;
         */
    }
}