Beispiel #1
1
function upload_file_to_client_pdf($file_to_send)
{
    //Function reads a text file and converts to pdf.
    global $STMT_TEMP_FILE_PDF;
    $pdf = new Cezpdf('LETTER');
    //pdf creation starts
    $pdf->ezSetMargins(36, 0, 36, 0);
    $pdf->selectFont($GLOBALS['fileroot'] . "/library/fonts/Courier.afm");
    $pdf->ezSetY($pdf->ez['pageHeight'] - $pdf->ez['topMargin']);
    $countline = 1;
    $file = fopen($file_to_send, "r");
    //this file contains the text to be converted to pdf.
    while (!feof($file)) {
        $OneLine = fgets($file);
        //one line is read
        if (stristr($OneLine, "\f") == true && !feof($file)) {
            $pdf->ezNewPage();
            $pdf->ezSetY($pdf->ez['pageHeight'] - $pdf->ez['topMargin']);
            str_replace("\f", "", $OneLine);
        }
        if (stristr($OneLine, 'REMIT TO') == true || stristr($OneLine, 'Visit Date') == true) {
            //lines are made bold when 'REMIT TO' or 'Visit Date' is there.
            $pdf->ezText('<b>' . $OneLine . '</b>', 12, array('justification' => 'left', 'leading' => 6));
        } else {
            $pdf->ezText($OneLine, 12, array('justification' => 'left', 'leading' => 6));
        }
        $countline++;
    }
    $fh = @fopen($STMT_TEMP_FILE_PDF, 'w');
    //stored to a pdf file
    if ($fh) {
        fwrite($fh, $pdf->ezOutput());
        fclose($fh);
    }
    header("Pragma: public");
    //this section outputs the pdf file to browser
    header("Expires: 0");
    header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
    header("Content-Type: application/force-download");
    header("Content-Length: " . filesize($STMT_TEMP_FILE_PDF));
    header("Content-Disposition: attachment; filename=" . basename($STMT_TEMP_FILE_PDF));
    header("Content-Description: File Transfer");
    readfile($STMT_TEMP_FILE_PDF);
    // flush the content to the browser. If you don't do this, the text from the subsequent
    // output from this script will be in the file instead of sent to the browser.
    flush();
    exit;
    //added to exit from process properly in order to stop bad html code -ehrlive
    // sleep one second to ensure there's no follow-on.
    sleep(1);
}
Beispiel #2
0
 public function ezSetMargins($top, $bottom, $left, $right)
 {
     parent::ezSetMargins($top, $bottom, $left, $right);
     $this->top = $this->pageHeight - $this->ez['topMargin'];
     $this->bottom = $this->ez['bottomMargin'];
     $this->left = $this->ez['leftMargin'];
     $this->right = $this->pageWidth - $this->ez['rightMargin'];
     $this->width = $this->right - $this->left;
 }
Beispiel #3
0
function printPDF($res, $res2, $data)
{
    $pdf = new Cezpdf("LETTER");
    $pdf->ezSetMargins(72, 30, 50, 30);
    $pdf->selectFont('Helvetica');
    $opts = array('justification' => "center");
    $pdf->ezText($res['facility_address'], "", $opts);
    $pdf->ezText("\n" . $res2['patient_name'] . "\n" . xl('Date of Birth') . ": " . $res2['patient_DOB'] . "\n" . $res2['patient_address']);
    $pdf->ezText("\n");
    $opts = array('maxWidth' => 550, 'fontSize' => 8);
    $pdf->ezTable($data, "", $title, $opts);
    $pdf->ezText("\n\n\n\n" . xl('Signature') . ":________________________________", "", array('justification' => 'right'));
    $pdf->ezStream();
}
Beispiel #4
0
function printPDF($res, $res2, $data)
{
    require_once $GLOBALS['fileroot'] . "/library/classes/class.ezpdf.php";
    $pdf = new Cezpdf("LETTER");
    $pdf->ezSetMargins(72, 30, 50, 30);
    $pdf->selectFont($GLOBALS['fileroot'] . "/library/fonts/Helvetica.afm");
    $opts = array('justification' => "center");
    $pdf->ezText($res['facility_address'], "", $opts);
    $pdf->ezText("\n" . $res2['patient_name'] . "\n" . xl('Date of Birth') . ": " . $res2['patient_DOB'] . "\n" . $res2['patient_address']);
    $pdf->ezText("\n");
    $opts = array('maxWidth' => 550, 'fontSize' => 8);
    $pdf->ezTable($data, "", $title, $opts);
    $pdf->ezText("\n\n\n\n" . xl('Signature') . ":________________________________", "", array('justification' => 'right'));
    $pdf->ezStream();
}
Beispiel #5
0
 /**
  * Creates a PDF document and sends this pricelist to the client
  *
  * Unfortunately, ezpdf does not return anything after printing the
  * document, so there's no way to tell whether it has succeeded.
  * Thus, you should not rely on the return value, except when it is
  * false -- in that case, loading of some data failed.
  * @return  boolean           False on failure, true on supposed success
  */
 function send_as_pdf()
 {
     global $objInit, $_ARRAYLANG;
     if (!$this->load()) {
         return \Message::error($_ARRAYLANG['TXT_SHOP_PRICELIST_ERROR_LOADING']);
     }
     $objPdf = new \Cezpdf('A4');
     $objPdf->setEncryption('', '', array('print'));
     $objPdf->selectFont(\Cx\Core\Core\Controller\Cx::instanciate()->getCodeBaseLibraryPath() . '/ezpdf/fonts/' . $this->font);
     $objPdf->ezSetMargins(0, 0, 0, 0);
     // Reset margins
     $objPdf->setLineStyle(0.5);
     $marginTop = 30;
     $biggerCountTop = $biggerCountBottom = 0;
     $arrHeaderLeft = $arrHeaderRight = $arrFooterLeft = $arrFooterRight = array();
     if ($this->header) {
         // header should be shown
         $arrHeaderLeft = explode("\n", $this->header_left);
         $arrHeaderRight = explode("\n", $this->header_right);
         $countLeft = count($arrHeaderLeft);
         $countRight = count($arrHeaderRight);
         $biggerCountTop = $countLeft > $countRight ? $countLeft : $countRight;
         $marginTop = $biggerCountTop * 14 + 36;
     }
     // Bottom margin
     $marginBottom = 20;
     $arrFooterRight = array();
     if ($this->footer) {
         // footer should be shown
         // Old, obsolete:
         $this->footer_left = str_replace('<--DATE-->', date(ASCMS_DATE_FORMAT_DATE, time()), $this->footer_left);
         $this->footer_right = str_replace('<--DATE-->', date(ASCMS_DATE_FORMAT_DATE, time()), $this->footer_right);
         // New:
         $this->footer_left = str_replace('[DATE]', date(ASCMS_DATE_FORMAT_DATE, time()), $this->footer_left);
         $this->footer_right = str_replace('[DATE]', date(ASCMS_DATE_FORMAT_DATE, time()), $this->footer_right);
         $arrFooterLeft = explode("\n", $this->footer_left);
         $arrFooterRight = explode("\n", $this->footer_right);
         $countLeft = count($arrFooterLeft);
         $countRight = count($arrFooterRight);
         $biggerCountBottom = $countLeft > $countRight ? $countLeft : $countRight;
         $marginBottom = $biggerCountBottom * 20 + 20;
     }
     // Borders
     if ($this->border) {
         $linesForAllPages = $objPdf->openObject();
         $objPdf->saveState();
         $objPdf->setStrokeColor(0, 0, 0, 1);
         $objPdf->rectangle(10, 10, 575.28, 821.89);
         $objPdf->restoreState();
         $objPdf->closeObject();
         $objPdf->addObject($linesForAllPages, 'all');
     }
     // Header
     $headerArray = array();
     $startpointY = 0;
     if ($this->header) {
         $objPdf->ezSetY(830);
         $headerForAllPages = $objPdf->openObject();
         $objPdf->saveState();
         for ($i = 0; $i < $biggerCountTop; ++$i) {
             $headerArray[$i] = array('left' => isset($arrHeaderLeft[$i]) ? $arrHeaderLeft[$i] : '', 'right' => isset($arrHeaderRight[$i]) ? $arrHeaderRight[$i] : '');
         }
         $tempY = $objPdf->ezTable($headerArray, '', '', array('showHeadings' => 0, 'fontSize' => $this->font_size_header, 'shaded' => 0, 'width' => 540, 'showLines' => 0, 'xPos' => 'center', 'xOrientation' => 'center', 'cols' => array('right' => array('justification' => 'right'))));
         $tempY -= 5;
         if ($this->border) {
             $objPdf->setStrokeColor(0, 0, 0);
             $objPdf->line(10, $tempY, 585.28, $tempY);
         }
         $startpointY = $tempY - 5;
         $objPdf->restoreState();
         $objPdf->closeObject();
         $objPdf->addObject($headerForAllPages, 'all');
     }
     // Footer
     $pageNumbersX = $pageNumbersY = $pageNumbersFont = 0;
     if ($this->footer) {
         $footerForAllPages = $objPdf->openObject();
         $objPdf->saveState();
         $tempY = $marginBottom - 5;
         if ($this->border) {
             $objPdf->setStrokeColor(0, 0, 0);
             $objPdf->line(10, $tempY, 585.28, $tempY);
         }
         // length of the longest word
         $longestWord = 0;
         foreach ($arrFooterRight as $line) {
             if ($longestWord < strlen($line)) {
                 $longestWord = strlen($line);
             }
         }
         for ($i = $biggerCountBottom - 1; $i >= 0; --$i) {
             if (empty($arrFooterLeft[$i])) {
                 $arrFooterLeft[$i] = '';
             }
             if (empty($arrFooterRight[$i])) {
                 $arrFooterRight[$i] = '';
             }
             if ($arrFooterLeft[$i] == '<--PAGENUMBER-->' || $arrFooterLeft[$i] == '[PAGENUMBER]') {
                 $pageNumbersX = 65;
                 $pageNumbersY = $tempY - 18 - $i * $this->font_size_footer;
                 $pageNumbersFont = $this->font_size_list;
             } else {
                 $objPdf->addText(25, $tempY - 18 - $i * $this->font_size_footer, $this->font_size_footer, $arrFooterLeft[$i]);
             }
             if ($arrFooterRight[$i] == '<--PAGENUMBER-->' || $arrFooterRight[$i] == '[PAGENUMBER]') {
                 $pageNumbersX = 595.28 - 25;
                 $pageNumbersY = $tempY - 18 - $i * $this->font_size_footer;
                 $pageNumbersFont = $this->font_size_list;
             } else {
                 // Properly align right
                 $width = $objPdf->getTextWidth($this->font_size_footer, $arrFooterRight[$i]);
                 $objPdf->addText(595.28 - $width - 25, $tempY - 18 - $i * $this->font_size_footer, $this->font_size_footer, $arrFooterRight[$i]);
             }
         }
         $objPdf->restoreState();
         $objPdf->closeObject();
         $objPdf->addObject($footerForAllPages, 'all');
     }
     // Page numbers
     if (isset($pageNumbersX)) {
         $objPdf->ezStartPageNumbers($pageNumbersX, $pageNumbersY, $pageNumbersFont, '', $_ARRAYLANG['TXT_SHOP_PRICELIST_FORMAT_PAGENUMBER'], 1);
     }
     // Margins
     $objPdf->ezSetMargins($marginTop, $marginBottom, 30, 30);
     // Product table
     if (isset($startpointY)) {
         $objPdf->ezSetY($startpointY);
     }
     $objInit->backendLangId = $this->lang_id;
     $_ARRAYLANG = $objInit->loadLanguageData('Shop');
     Currency::setActiveCurrencyId($this->currency_id);
     $currency_symbol = Currency::getActiveCurrencySymbol();
     $category_ids = $this->category_ids();
     if ($category_ids == '*') {
         $category_ids = null;
     }
     $count = 1000;
     // Be sensible!
     // Pattern is "%" because all-empty parameters will result in an
     // empty array!
     $arrProduct = Products::getByShopParams($count, 0, null, $category_ids, null, '%', null, null, '`category_id` ASC, `name` ASC');
     $arrCategoryName = ShopCategories::getNameArray();
     $arrOutput = array();
     foreach ($arrProduct as $product_id => $objProduct) {
         $categoryIds = explode(',', $objProduct->category_id());
         $arrCategoryNames = array();
         foreach ($categoryIds as $categoryId) {
             $arrCategoryNames[] = $arrCategoryName[$categoryId];
         }
         //$objProduct = new Product();
         $arrOutput[$product_id] = array('product_name' => self::decode($objProduct->name()), 'category_name' => self::decode(implode(', ', $arrCategoryNames)), 'product_code' => self::decode($objProduct->code()), 'product_id' => self::decode($objProduct->id()), 'price' => ($objProduct->discount_active() ? "S " . Currency::formatPrice($objProduct->discountprice()) : Currency::formatPrice($objProduct->price())) . ' ' . $currency_symbol);
     }
     $objPdf->ezTable($arrOutput, array('product_name' => '<b>' . self::decode($_ARRAYLANG['TXT_SHOP_PRODUCT_NAME']) . '</b>', 'category_name' => '<b>' . self::decode($_ARRAYLANG['TXT_SHOP_CATEGORY_NAME']) . '</b>', 'product_code' => '<b>' . self::decode($_ARRAYLANG['TXT_SHOP_PRODUCT_CODE']) . '</b>', 'product_id' => '<b>' . self::decode($_ARRAYLANG['TXT_ID']) . '</b>', 'price' => '<b>' . self::decode($_ARRAYLANG['TXT_SHOP_PRICE']) . '</b>'), '', array('showHeadings' => 1, 'fontSize' => $this->font_size_list, 'width' => 530, 'innerLineThickness' => 0.5, 'outerLineThickness' => 0.5, 'shaded' => 2, 'shadeCol' => array(hexdec(substr($this->row_color_1, 0, 2)) / 255, hexdec(substr($this->row_color_1, 2, 2)) / 255, hexdec(substr($this->row_color_1, 4, 2)) / 255), 'shadeCol2' => array(hexdec(substr($this->row_color_2, 0, 2)) / 255, hexdec(substr($this->row_color_2, 2, 2)) / 255, hexdec(substr($this->row_color_2, 4, 2)) / 255), 'cols' => array('product_name' => array('width' => 255), 'category_name' => array('width' => 130), 'product_code' => array('width' => 50), 'product_id' => array('width' => 40, 'justification' => 'right'), 'price' => array('width' => 55, 'justification' => 'right'))));
     $objPdf->ezStream();
     // Never reached
     return true;
 }
            $assinatura1 = $res['assinatura1'];
            $assinatura2 = $res['assinatura2'];
            $texto = $res['texto'];
            $n_empresa = $res['n_empresa'];
            if ($n_empresa == '') {
                $n_empresa = $res['n_nome'];
            }
            $n_cpf = $res['n_cpf'];
            $n_rg = $res['n_rg'];
            $n_endereco = $res['n_endereco'];
            $n_complemento = $res['n_complemento'];
            $n_numero = $res['n_numero'];
            $n_bairro = $res['n_bairro'];
            $n_cidade = $res['n_cidade'];
            $n_estado = $res['n_estado'];
            $pdf->ezSetMargins(10, 10, 25, 20);
            $pdf->ezText('Notificação', 16, array('justification' => 'center'));
            $pdf->ezText('
' . $data_atual, 12, array('justification' => 'left'));
            $pdf->ezText('
' . $n_empresa, 14);
            $pdf->ezText('Documento: ' . $n_cpf . '
' . $n_endereco . ', ' . $n_numero . ' ' . $n_complemento . '
' . $n_bairro . ' - ' . $n_cidade . ' - ' . $n_estado . '

' . $texto . '



', 12);
            $pdf->ezImage('../assinaturas/' . $assinatura1, 0, 100, '', 'center');
$GLOBALS["table_body_height"] = 10;
$GLOBALS["footer_height"] = 8;
$GLOBALS["table_layout_vertical"] = array('xPos' => 45, 'width' => $pdf->ez['pageWidth'] - 80, 'xOrientation' => 'right', 'showHeadings' => 0, 'shaded' => 2, 'shadeCol' => array(1, 1, 1), 'shadeCol2' => array(0.9, 0.9, 0.9), 'showLines' => 0, 'fontSize' => $GLOBALS["table_body_height"], 'leading' => "20", 'cols' => array('0' => array('width' => 150)));
$GLOBALS["table_layout_horizontal"] = array('xPos' => 45, 'width' => $pdf->ez['pageWidth'] - 80, 'xOrientation' => 'right', 'showHeadings' => 1, 'shaded' => 2, 'shadeCol' => array(1, 1, 1), 'shadeCol2' => array(0.9, 0.9, 0.9), 'showLines' => 0, 'fontSize' => $GLOBALS["table_body_height"], 'leading' => "20");
function header_footer($pdf)
{
    $pdf->addText(30, 25, $GLOBALS["footer_height"], date('l, dS \\of F Y, h:i:s A'));
    $pdf->addText(470, 25, $GLOBALS["footer_height"], 'http://www.open-audit.org');
    $im = imagecreatefrompng("./images/logo.png");
    $pdf->addImage($im, 380, $pdf->ez['pageHeight'] - 58, 200);
    $pdf->addLink("http://www.open-audit.org", 375, $pdf->ez['pageHeight'] - 60, 575, $pdf->ez['pageHeight'] - 20);
    return $pdf;
}
//Start PDF
/////////////////////////////////////////////////////////////////////////////////
$pdf->ezSetMargins('30', '40', '30', '30');
$pdf->selectFont(FPDF_FONTPATH . 'Helvetica.afm');
$pdf->ezStartPageNumbers(300, 25, $GLOBALS["footer_height"], '', '', 1);
//Footer
$pdf = header_footer($pdf);
//Get the pc's to display
//actually only one
if (isset($_REQUEST["pc"]) and $_REQUEST["pc"] != "") {
    $pc = $_REQUEST["pc"];
    $_GET["pc"] = $_REQUEST["pc"];
    $sql = "SELECT system_uuid, system_timestamp, system_name FROM system WHERE system_uuid = '{$pc}' OR system_name = '{$pc}' ";
    $result = mysql_query($sql, $db);
    $i = 0;
    if ($myrow = mysql_fetch_array($result)) {
        do {
            $systems_array[$i] = array("pc" => $myrow["system_uuid"], "system_timestamp" => $myrow["system_timestamp"]);
//  // Find out how many times this prescription has been filled/refilled.
//  $refills_row = sqlQuery("SELECT count(*) AS count FROM drug_sales " .
//   "WHERE prescription_id = '" . $row['prescription_id'] .
//   "' AND quantity > 0");
//  $label_text .= ($refills_row['count'] - 1) . ' of ' . $row['refills'] . ' refills';
// }
// We originally went for PDF output on the theory that output formatting
// would be more controlled.  However the clumisness of invoking a PDF
// viewer from the browser becomes intolerable in a POS environment, and
// printing HTML is much faster and easier if the browser's page setup is
// configured properly.
//
if (false) {
    // if PDF output is desired
    $pdf = new Cezpdf($dconfig['paper_size']);
    $pdf->ezSetMargins($dconfig['top'], $dconfig['bottom'], $dconfig['left'], $dconfig['right']);
    $pdf->selectFont('Helvetica');
    $pdf->ezSetDy(20);
    // dunno why we have to do this...
    $pdf->ezText($header_text, 7, array('justification' => 'center'));
    if (!empty($dconfig['logo'])) {
        $pdf->ezSetDy(-5);
        // add space (move down) before the image
        $pdf->ezImage($dconfig['logo'], 0, 180, '', 'left');
        $pdf->ezSetDy(8);
        // reduce space (move up) after the image
    }
    $pdf->ezText($label_text, 9, array('justification' => 'center'));
    $pdf->ezStream();
} else {
    // HTML output
Beispiel #9
0
    /**
     * gera um pdf dos laudos
	 *
	 * @param array $r
     */
	function pdfLaudos($rs){
	
		//error_reporting(E_ALL);
		set_time_limit(1800);
		include 'lib/php/classes/class.ezpdf.php';
		
		$pdf = new Cezpdf('a4','portrait');
		$pdf -> ezSetMargins(50,70,50,50);
		$all = $pdf->openObject();
		$pdf->saveState();
		$pdf->setStrokeColor(0,0,0,1);
		$pdf->restoreState();
		$pdf->closeObject();
		$pdf->addObject($all,'all');
		$mainFont = './fonts/Courier.afm';
		$codeFont = './fonts/Courier.afm';
		$pdf->selectFont($mainFont);
		$n_rows = sizeof($rs);

		$c = 0;
		$t=945;
		$fator = 25;
		foreach($rs as $id => $r){
			$o = new Interpretacao($r["int_id"]);
			
			$hos = new Hospital($o->get("hos_id"));
			$hos_nome = $hos->get("hos_nome");
			
			$con = new Convenio($o->get("con_id"));
			$con_nome = $con->get("con_nome");
			
			$exa = new Exame($o->get("exa_id"));
			$exa_nome = $exa->get("exa_nome");
			
			$pdf->ezText($hos_nome,18,array('justification'=>'center')); 
			$pdf->ezText(" ",20,array('justification'=>'left'));
			$pdf->ezText("PACIENTE      : ".$r["int_paciente_prontuario"]."   ".$r["int_paciente_nome"],10,array('justification'=>'left'));

			if ($r["int_paciente_nascimento"] == "0000-00-00")
				$pdf->ezText("NASCIMENTO    :                                   SEXO: ".$r["int_paciente_sexo"],10,array('justification'=>'left'));
			else
				$pdf->ezText("NASCIMENTO    : ".Formatacao::formatBrData($r["int_paciente_nascimento"])."                        SEXO: ".$r["int_paciente_sexo"],10,array('justification'=>'left'));
		
			$pdf->ezText("CONVÊNIO      : ".$con_nome,10,array('justification'=>'left'));
			$pdf->ezText("EXAME         : ".$exa_nome,10,array('justification'=>'left'));

			$pdf->ezText(" ",20,array('justification'=>'left'));

			$pdf->ezText("                                                  DATA: ".Formatacao::formatBrDataHoraminSeg($r["int_data_interpretacao"]),10,array('justification'=>'left'));
			$pdf->ezText("N DO EXAME               : ".$r["int_opcional"],10,array('justification'=>'left'));
			$pdf->ezText("MÉDICO REQUISITANTE      : ".$r["int_requisitante"],10,array('justification'=>'left'));
			$pdf->ezText("EXAME INTERPRETADO POR   : 9679 Ernesto Sousa Nunes",10,array('justification'=>'left'));
			$pdf->ezText("TÉCNICO RX               : ".$r["int_tecnico_rx"],10,array('justification'=>'left'));
			
			$pdf->ezText(" ",20,array('justification'=>'left'));
			
			$pdf->ezText("I N T E R P R E T A Ç Ã O",18,array('justification'=>'center')); 
			
			$pdf->ezText(" ",20,array('justification'=>'left'));
			
			$vet_txt = split("\n",$r["int_texto"]);
			
			$pdf->ezText("============================================================================",10,array('justification'=>'left'));
			
			$pdf->ezText(" ",8,array('justification'=>'left'));
			
			foreach($vet_txt as $linha){
				$pdf->ezText("      ".$linha,10,array('justification'=>'left'));
			}
			$pdf->ezText(" ",8,array('justification'=>'left'));
			
			$pdf->ezText("============================================================================",10,array('justification'=>'left'));
			
			$pdf->ezText("              Exame interpretado por: 9676 - Dr. Ernesto Sousa Nunes",10,array('justification'=>'left'));
			$pdf->addJpegFromFile('ass.jpg',250, 0);
			$pdf->openHere('Fit');
			if ($c+1 < $n_rows)
				$pdf->ezNewPage();
			$c++;
			
			$o->informaImpressao();
			//$sql = "update laudo set LAU_DATA_EXPORTACAO = now() where LAU_ID = ".$r["LAU_ID"]." LIMIT 1";
			//$up = mysql_query($sql, $db) or die(mysql_error());
		 }
		
		$pdfcode = $pdf->Output();
		//$pdfcode = str_replace("\n","\n<br>",htmlspecialchars($pdfcode));
		//$cont = trim($pdfcode);
		$fh = fopen("laudos_prontos.pdf", 'w+');
		fwrite($fh, $pdfcode);
		fclose($fh);
		?><script language="javascript">document.location.href="laudos_prontos.pdf";</script><?

	}
function CREATEPDF($p)
{
    $sGeo = explode("|", $p);
    $tokens = explode(",", $sGeo[0]);
    $sMin = explode(" ", $tokens[0]);
    $sMax = explode(" ", $tokens[2]);
    $sMinX = $sMin[0];
    $sMinY = $sMin[1];
    $oPDF = new Cezpdf('a4', 'portrait') or die("Kan PDFLib niet gebruiken");
    $oPDF->ezSetMargins(20, 20, 20, 20);
    $oPDF->openHere('Fit');
    $ext1 = $sMax[1] - $sMin[0];
    $ext2 = $sMax[2] - $sMin[1];
    $oPDF->setLineStyle(2);
    $oPDF->rectangle(20, 20, 595.28 - 40, 841.89 - 40);
    for ($iRecord = 1; $iRecord < count($sGeo) - 1; $iRecord++) {
        $oPDF->setLineStyle(0.1);
        $oPDF->setColor(1, 0, 0);
        $oPDF->setStrokeColor(0.5, 0.5, 0.5);
        $tokens = explode(",", $sGeo[$iRecord]);
        $point = array();
        $waarde = 0;
        //$waardex = (297.64);
        //$waardey = (420.945);
        //$waardex = 0;
        //$waardey = 0;
        for ($gRecord = 0; $gRecord < count($tokens); $gRecord++) {
            $sPunt = explode(" ", $tokens[$gRecord]);
            if ($gRecord == 0) {
                $sX = $sPunt[0] - $sMinX;
                $sY = $sPunt[1] - $sMinY;
                $point[$waarde] = $sX * 1000 / 0.3528 / 350000;
                $point[$waarde + 1] = $sY * 1000 / 0.3528 / 350000;
            } elseif ($gRecord == count($tokens) - 1) {
                $sX = $sPunt[1] - $sMinX;
                $sY = $sPunt[2] - $sMinY;
                $point[$waarde] = $sX * 1000 / 0.3528 / 350000;
                $point[$waarde + 1] = $sY * 1000 / 0.3528 / 350000;
            } else {
                $sX = $sPunt[1] - $sMinX;
                $sY = $sPunt[2] - $sMinY;
                $point[$waarde] = $sX * 1000 / 0.3528 / 350000;
                $point[$waarde + 1] = $sY * 1000 / 0.3528 / 350000;
            }
            $waarde = $waarde + 2;
        }
        $oPDF->polygon($point, $waarde / 2, 1);
        $oPDF->polygon($point, $waarde / 2);
        unset($point);
    }
    $oPDF->ezStream();
}
Beispiel #11
0
 $cpstring = str_replace('{' . $FIELD_TAG['PT_LNAME'] . '}', $patdata['lname'], $cpstring);
 $cpstring = str_replace('{' . $FIELD_TAG['PT_MNAME'] . '}', $patdata['mname'], $cpstring);
 $cpstring = str_replace('{' . $FIELD_TAG['PT_STREET'] . '}', $patdata['street'], $cpstring);
 $cpstring = str_replace('{' . $FIELD_TAG['PT_CITY'] . '}', $patdata['city'], $cpstring);
 $cpstring = str_replace('{' . $FIELD_TAG['PT_STATE'] . '}', $patdata['state'], $cpstring);
 $cpstring = str_replace('{' . $FIELD_TAG['PT_POSTAL'] . '}', $patdata['postal_code'], $cpstring);
 $cpstring = str_replace('{' . $FIELD_TAG['PT_PHONE_HOME'] . '}', $patdata['phone_home'], $cpstring);
 $cpstring = str_replace('{' . $FIELD_TAG['PT_PHONE_CELL'] . '}', $patdata['phone_cell'], $cpstring);
 $cpstring = str_replace('{' . $FIELD_TAG['PT_SSN'] . '}', $patdata['ss'], $cpstring);
 $cpstring = str_replace('{' . $FIELD_TAG['PT_EMAIL'] . '}', $patdata['email'], $cpstring);
 $cpstring = str_replace('{' . $FIELD_TAG['PT_DOB'] . '}', $patdata['DOB'], $cpstring);
 if ($form_format == "pdf") {
     // documentation for ezpdf is here --> http://www.ros.co.nz/pdf/
     require_once $GLOBALS['fileroot'] . "/library/classes/class.ezpdf.php";
     $pdf = new Cezpdf($GLOBALS['rx_paper_size']);
     $pdf->ezSetMargins($GLOBALS['rx_top_margin'], $GLOBALS['rx_bottom_margin'], $GLOBALS['rx_left_margin'], $GLOBALS['rx_right_margin']);
     if (file_exists("{$template_dir}/custom_pdf.php")) {
         include "{$template_dir}/custom_pdf.php";
     } else {
         $pdf->selectFont($GLOBALS['fileroot'] . "/library/fonts/Helvetica.afm");
         $pdf->ezText($cpstring, 12);
     }
     $pdf->ezStream();
     exit;
 } else {
     // $form_format = html
     $cpstring = text($cpstring);
     //escape to prevent stored cross script attack
     $cpstring = str_replace("\n", "<br>", $cpstring);
     $cpstring = str_replace("\t", "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;", $cpstring);
     ?>
function BuildPDFReport($userid)
{
    $GLOBALS["SartON"] = time();
    $q = new mysql();
    $sql = "SELECT * FROM quarantine_report_users WHERE userid='{$userid}' and `type`=1 and `enabled`=1";
    $ligne = mysql_fetch_array($q->QUERY_SQL($sql, "artica_backup"));
    if ($ligne["enabled"] == 0) {
        return;
    }
    $params = unserialize(base64_decode($ligne["parameters"]));
    $days = $params["days"];
    $subject = $params["subject"];
    $subject = str_replace("{", "", $subject);
    $subject = str_replace("}", "", $subject);
    $session = md5($user->password);
    if ($days < 1) {
        $days = 2;
    }
    $user = new user($userid);
    while (list($num, $ligne) = each($user->HASH_ALL_MAILS)) {
        $recipient_sql[] = "mailto='{$ligne}'";
    }
    $date = date('Y-m-d');
    $recipients = implode(" OR ", $recipient_sql);
    $sql = "SELECT mailfrom,zDate,MessageID,DATE_FORMAT(zdate,'%W %D %H:%i') as tdate,subject FROM quarantine\n\tWHERE (zDate>DATE_ADD('{$date}', INTERVAL -{$days} DAY)) AND ({$recipients})  ORDER BY zDate DESC;";
    if ($GLOBALS["VERBOSE"]) {
        echo "{$sql}\n";
    }
    $datepdf = date('Y-m-d');
    $results = $q->QUERY_SQL($sql, "artica_backup");
    $num_rows = mysql_num_rows($results);
    if (!$q->ok) {
        send_email_events("Build SMTP quarantine report failed for {$uid}", "{$sql}\n{$q->mysql_error}", "postfix");
        return null;
    }
    if ($num_rows == 0) {
        return;
    }
    $pdf = new Cezpdf('a4', 'portrait');
    $pdf->ezSetMargins(50, 70, 50, 50);
    $all = $pdf->openObject();
    $pdf->saveState();
    //$pdf->setStrokeColor(0,0,0,1);
    $pdf->line(20, 40, 578, 40);
    $pdf->line(20, 822, 578, 822);
    $pdf->addText(50, 34, 6, $date);
    $pdf->restoreState();
    $pdf->closeObject();
    $pdf->addObject($all, 'all');
    $mainFont = dirname(__FILE__) . "/ressources/fonts/Helvetica.afm";
    $codeFont = dirname(__FILE__) . "/ressources/fonts/Courier.afm";
    $pdf->selectFont($mainFont);
    $pdf->ezText("{$user->DisplayName}\n", 30, array('justification' => 'centre'));
    $pdf->ezText("{$subject}\n", 20, array('justification' => 'centre'));
    $pdf->ezText("{$date} ({$num_rows} message(s))", 18, array('justification' => 'centre'));
    $pdf->ezStartPageNumbers(100, 30, 12, "left", "Page {PAGENUM}/{TOTALPAGENUM}");
    $pdf->ezNewPage();
    $options = array('showLines' => 2, 'showHeadings' => 0, 'shaded' => 2, 'shadeCol' => array(1, 1, 1), 'shadeCol2' => array(0.8, 0.8, 0.8), 'fontSize' => 11, 'textCol' => array(0, 0, 0), 'textCol2' => array(1, 1, 1), 'titleFontSize' => 16, 'titleGap' => 8, 'rowGap' => 5, 'colGap' => 10, 'lineCol' => array(1, 1, 1), 'xPos' => 'left', 'xOrientation' => 'right', 'width' => 500, 'maxWidth' => 500);
    while ($ligne = @mysql_fetch_array($results, MYSQL_ASSOC)) {
        $mail_subject = $ligne["subject"];
        $from = trim($ligne["mailfrom"]);
        $zDate = $ligne["tdate"];
        $MessageID = $ligne["MessageID"];
        if ($from == null) {
            $from = "unknown";
        }
        $domain = "unknown";
        if (preg_match("#(.+?)@(.+)#", $from, $re)) {
            $domain = $re[2];
        }
        $mail_subject = str_replace("{", "", $mail_subject);
        $mail_subject = str_replace("}", "", $mail_subject);
        $uri = "<c:alink:{{$params["URI"]}/user.quarantine.query.php?uid={$user->uid}&session={$session}&mail={$MessageID}>{$mail_subject}</c:alink>";
        $data[] = array($zDate, $from, $uri);
    }
    $pdf->ezTable($data, $cols, $subject, $options);
    $pdfcode = $pdf->output();
    $fname = "/tmp/" . date('Ymdhi') . "-{$user->mail}-quarantines.pdf";
    if ($GLOBALS["VERBOSE"]) {
        echo "{$pdf->messages}\nbuilding {$fname}\n";
    }
    @unlink($fname);
    if ($GLOBALS["VERBOSE"]) {
        echo "Building {$fname}\n";
    }
    $fp = fopen($fname, 'w');
    fwrite($fp, $pdfcode);
    fclose($fp);
    if (preg_match("#(.+?)@(.+)#", $user->mail, $re)) {
        $domain = $re[2];
    }
    $PostmasterAdress = "no-reply-quarantine@{$domain}";
    $ini = new Bs_IniHandler("/etc/artica-postfix/smtpnotif.conf");
    if ($ini->_params["SMTP"]["smtp_sender"] != null) {
        $PostmasterAdress = $ini->_params["SMTP"]["smtp_sender"];
    }
    if (file_exists('/etc/artica-postfix/settings/Daemons/PostfixPostmaster')) {
        $PostmasterAdress = trim(@file_get_contents('/etc/artica-postfix/settings/Daemons/PostfixPostmaster'));
    }
    $unix = new unix();
    $sendmail = $unix->find_program("sendmail");
    $mail = new PHPMailer(true);
    $mail->IsSendmail();
    $mail->AddAddress($user->mail, $user->DisplayName);
    $mail->AddReplyTo($PostmasterAdress, $PostmasterAdress);
    $mail->From = $PostmasterAdress;
    $mail->Subject = $subject;
    $mail->Body = "{$subject}\nSee attached file...\n";
    $mail->AddAttachment($fname, basename($fname));
    $content = $mail->Send(true);
    $tmpfile = "/tmp/" . md5(date('Y-m-d H:is') . "-{$user->uid}-msmtp");
    file_put_contents($tmpfile, $content);
    $cmd = "{$sendmail} -bm -t -f {$PostmasterAdress} <{$tmpfile}";
    system($cmd);
    @unlink($tmpfile);
    @unlink($fname);
    $SartOff = time();
    $time_duration = distanceOfTimeInWords($GLOBALS["SartON"], $SartOff);
    send_email_events("SMTP quarantine report for {$user->mail} (success) {$num_rows} message(s)", "duration:{$time_duration}\nnothing to say more...", "postfix");
}
Beispiel #13
0
 function get_printable_timeSheet_file($timeSheetID, $timeSheetPrintMode, $printDesc, $format)
 {
     global $TPL;
     $TPL["timeSheetID"] = $timeSheetID;
     $TPL["timeSheetPrintMode"] = $timeSheetPrintMode;
     $TPL["printDesc"] = $printDesc;
     $TPL["format"] = $format;
     $db = new db_alloc();
     if ($timeSheetID) {
         $timeSheet = new timeSheet();
         $timeSheet->set_id($timeSheetID);
         $timeSheet->select();
         $timeSheet->set_tpl_values();
         $person = $timeSheet->get_foreign_object("person");
         $TPL["timeSheet_personName"] = $person->get_name();
         $timeSheet->set_tpl_values("timeSheet_");
         // Display the project name.
         $project = new project();
         $project->set_id($timeSheet->get_value("projectID"));
         $project->select();
         $TPL["timeSheet_projectName"] = $project->get_value("projectName", DST_HTML_DISPLAY);
         // Get client name
         $client = $project->get_foreign_object("client");
         $client->set_tpl_values();
         $TPL["clientName"] = $client->get_value("clientName", DST_HTML_DISPLAY);
         $TPL["companyName"] = config::get_config_item("companyName");
         $TPL["companyNos1"] = config::get_config_item("companyACN");
         $TPL["companyNos2"] = config::get_config_item("companyABN");
         unset($br);
         $phone = config::get_config_item("companyContactPhone");
         $fax = config::get_config_item("companyContactFax");
         $phone and $TPL["phone"] = "Ph: " . $phone;
         $fax and $TPL["fax"] = "Fax: " . $fax;
         $timeSheet->load_pay_info();
         $db->query(prepare("SELECT max(dateTimeSheetItem) AS maxDate\n                                ,min(dateTimeSheetItem) AS minDate\n                                ,count(timeSheetItemID) as count\n                            FROM timeSheetItem \n                           WHERE timeSheetID=%d ", $timeSheetID));
         $db->next_record();
         $timeSheet->set_id($timeSheetID);
         $timeSheet->select() || alloc_error("Unable to select time sheet, trying to use id: " . $timeSheetID);
         $TPL["period"] = format_date(DATE_FORMAT, $db->f("minDate")) . " to " . format_date(DATE_FORMAT, $db->f("maxDate"));
         $TPL["img"] = config::get_config_item("companyImage");
         $TPL["companyContactAddress"] = config::get_config_item("companyContactAddress");
         $TPL["companyContactAddress2"] = config::get_config_item("companyContactAddress2");
         $TPL["companyContactAddress3"] = config::get_config_item("companyContactAddress3");
         $email = config::get_config_item("companyContactEmail");
         $email and $TPL["companyContactEmail"] = "Email: " . $email;
         $web = config::get_config_item("companyContactHomePage");
         $web and $TPL["companyContactHomePage"] = "Web: " . $web;
         $TPL["footer"] = config::get_config_item("timeSheetPrintFooter");
         $TPL["taxName"] = config::get_config_item("taxName");
         $default_header = "Time Sheet";
         $default_id_label = "Time Sheet ID";
         $default_contractor_label = "Contractor";
         $default_total_label = "TOTAL AMOUNT PAYABLE";
         if ($timeSheetPrintMode == "money") {
             $default_header = "Tax Invoice";
             $default_id_label = "Invoice Number";
         }
         if ($timeSheetPrintMode == "estimate") {
             $default_header = "Estimate";
             $default_id_label = "Estimate Number";
             $default_contractor_label = "Issued By";
             $default_total_label = "TOTAL AMOUNT ESTIMATED";
         }
         if ($format != "html") {
             // Build PDF document
             $font1 = ALLOC_MOD_DIR . "util/fonts/Helvetica.afm";
             $font2 = ALLOC_MOD_DIR . "util/fonts/Helvetica-Oblique.afm";
             $pdf_table_options = array("showLines" => 0, "shaded" => 0, "showHeadings" => 0, "xPos" => "left", "xOrientation" => "right", "fontSize" => 10, "rowGap" => 0, "fontSize" => 10);
             $cols = array("one" => "", "two" => "", "three" => "", "four" => "");
             $cols3 = array("one" => "", "two" => "");
             $cols_settings["one"] = array("justification" => "right");
             $cols_settings["three"] = array("justification" => "right");
             $pdf_table_options2 = array("showLines" => 0, "shaded" => 0, "showHeadings" => 0, "width" => 400, "fontSize" => 10, "xPos" => "center", "xOrientation" => "center", "cols" => $cols_settings);
             $cols_settings2["gst"] = array("justification" => "right");
             $cols_settings2["money"] = array("justification" => "right");
             $pdf_table_options3 = array("showLines" => 2, "shaded" => 0, "width" => 400, "xPos" => "center", "fontSize" => 10, "cols" => $cols_settings2, "lineCol" => array(0.8, 0.8, 0.8), "splitRows" => 1, "protectRows" => 0);
             $cols_settings["two"] = array("justification" => "right", "width" => 80);
             $pdf_table_options4 = array("showLines" => 2, "shaded" => 0, "width" => 400, "showHeadings" => 0, "fontSize" => 10, "xPos" => "center", "cols" => $cols_settings, "lineCol" => array(0.8, 0.8, 0.8));
             $pdf = new Cezpdf();
             $pdf->ezSetMargins(90, 90, 90, 90);
             $pdf->selectFont($font1);
             $pdf->ezStartPageNumbers(436, 80, 10, 'right', 'Page {PAGENUM} of {TOTALPAGENUM}');
             $pdf->ezStartPageNumbers(200, 80, 10, 'left', '<b>' . $default_id_label . ': </b>' . $TPL["timeSheetID"]);
             $pdf->ezSetY(775);
             $TPL["companyName"] and $contact_info[] = array($TPL["companyName"]);
             $TPL["companyContactAddress"] and $contact_info[] = array($TPL["companyContactAddress"]);
             $TPL["companyContactAddress2"] and $contact_info[] = array($TPL["companyContactAddress2"]);
             $TPL["companyContactAddress3"] and $contact_info[] = array($TPL["companyContactAddress3"]);
             $TPL["companyContactEmail"] and $contact_info[] = array($TPL["companyContactEmail"]);
             $TPL["companyContactHomePage"] and $contact_info[] = array($TPL["companyContactHomePage"]);
             $TPL["phone"] and $contact_info[] = array($TPL["phone"]);
             $TPL["fax"] and $contact_info[] = array($TPL["fax"]);
             $pdf->selectFont($font2);
             $y = $pdf->ezTable($contact_info, false, "", $pdf_table_options);
             $pdf->selectFont($font1);
             $line_y = $y - 10;
             $pdf->setLineStyle(1, "round");
             $pdf->line(90, $line_y, 510, $line_y);
             $pdf->ezSetY(782);
             $image_jpg = ALLOC_LOGO;
             if (file_exists($image_jpg)) {
                 $pdf->ezImage($image_jpg, 0, sprintf("%d", config::get_config_item("logoScaleX")), 'none');
                 $y = 700;
             } else {
                 $y = $pdf->ezText($TPL["companyName"], 27, array("justification" => "right"));
             }
             $nos_y = $line_y + 22;
             $TPL["companyNos2"] and $nos_y = $line_y + 34;
             $pdf->ezSetY($nos_y);
             $TPL["companyNos1"] and $y = $pdf->ezText($TPL["companyNos1"], 10, array("justification" => "right"));
             $TPL["companyNos2"] and $y = $pdf->ezText($TPL["companyNos2"], 10, array("justification" => "right"));
             $pdf->ezSetY($line_y - 20);
             $y = $pdf->ezText($default_header, 20, array("justification" => "center"));
             $pdf->ezSetY($y - 20);
             $ts_info[] = array("one" => "<b>" . $default_id_label . ":</b>", "two" => $TPL["timeSheetID"], "three" => "<b>Date Issued:</b>", "four" => date("d/m/Y"));
             $ts_info[] = array("one" => "<b>Client:</b>", "two" => $TPL["clientName"], "three" => "<b>Project:</b>", "four" => $TPL["timeSheet_projectName"]);
             $ts_info[] = array("one" => "<b>" . $default_contractor_label . ":</b>", "two" => $TPL["timeSheet_personName"], "three" => "<b>Billing Period:</b>", "four" => $TPL["period"]);
             if ($timeSheetPrintMode == "estimate") {
                 // This line needs to be glued to the above line
                 $temp = array_pop($ts_info);
                 $temp["three"] = "";
                 // Nuke Billing Period for the Estimate version of the pdf.
                 $temp["four"] = "";
                 // Nuke Billing Period for the Estimate version of the pdf.
                 $ts_info[] = $temp;
             }
             $y = $pdf->ezTable($ts_info, $cols, "", $pdf_table_options2);
             $pdf->ezSetY($y - 20);
             if ($timeSheetPrintMode == "money" || $timeSheetPrintMode == "estimate") {
                 list($rows, $info) = $this->get_timeSheetItem_list_money($TPL["timeSheetID"]);
                 $cols2 = array("desc" => "Description", "units" => "Units", "money" => "Charges", "gst" => $TPL["taxName"]);
                 $taxPercent = config::get_config_item("taxPercent");
                 if ($taxPercent === '') {
                     unset($cols2["gst"]);
                 }
                 $rows[] = array("desc" => "<b>TOTAL</b>", "units" => $info["total_units"], "money" => $info["total"], "gst" => $info["total_gst"]);
                 $y = $pdf->ezTable($rows, $cols2, "", $pdf_table_options3);
                 $pdf->ezSetY($y - 20);
                 if ($taxPercent !== '') {
                     $totals[] = array("one" => "TOTAL " . $TPL["taxName"], "two" => $info["total_gst"]);
                 }
                 $totals[] = array("one" => "TOTAL CHARGES", "two" => $info["total"]);
                 $totals[] = array("one" => "<b>" . $default_total_label . "</b>", "two" => "<b>" . $info["total_inc_gst"] . "</b>");
                 $y = $pdf->ezTable($totals, $cols3, "", $pdf_table_options4);
             } else {
                 if ($timeSheetPrintMode == "units") {
                     list($rows, $info) = $this->get_timeSheetItem_list_units($TPL["timeSheetID"]);
                     $cols2 = array("desc" => "Description", "units" => "Units");
                     $rows[] = array("desc" => "<b>TOTAL</b>", "units" => "<b>" . $info["total"] . "</b>");
                     $y = $pdf->ezTable($rows, $cols2, "", $pdf_table_options3);
                 } else {
                     if ($timeSheetPrintMode == "items") {
                         list($rows, $info) = $this->get_timeSheetItem_list_items($TPL["timeSheetID"]);
                         $cols2 = array("date" => "Date", "units" => "Units", "multiplier_string" => "Multiplier", "desc" => "Description");
                         $rows[] = array("date" => "<b>TOTAL</b>", "units" => "<b>" . $info["total"] . "</b>");
                         $y = $pdf->ezTable($rows, $cols2, "", $pdf_table_options3);
                     }
                 }
             }
             $pdf->ezSetY($y - 20);
             $pdf->ezText(str_replace(array("<br>", "<br/>", "<br />"), "\n", $TPL["footer"]), 10);
             $pdf->ezStream(array("Content-Disposition" => "timeSheet_" . $timeSheetID . ".pdf"));
             // Else HTML format
         } else {
             if (file_exists(ALLOC_LOGO)) {
                 $TPL["companyName"] = '<img alt="Company logo" src="' . $TPL["url_alloc_logo"] . '" />';
             }
             $TPL["this_tsp"] = $this;
             $TPL["main_alloc_title"] = "Time Sheet - " . APPLICATION_NAME;
             include_template(dirname(__FILE__) . "/../templates/timeSheetPrintM.tpl");
         }
     }
 }
function creaPDF($ids, $tmpName, $path, $PATHQR, $tmp = "")
{
    require dirname(dirname(dirname(__FILE__))) . '/f4/configuracion/utils.php';
    require dirname(dirname(dirname(__FILE__))) . '/f4/configuracion/importeco.php';
    require dirname(dirname(dirname(__FILE__))) . "/gui/QRCode/qr_imgV2.php";
    $data = "";
    $facturaController = new FacturaController($path);
    $selloController = new SelloController($path);
    $empresaController = new EmpresaController($path);
    $sucursalController = new SucursalController($path);
    $FWK_PDFFONTS = 'pdf/fonts/';
    $FWK_PDFDEFAULTFONT = 'pdf/fonts/Helvetica.afm';
    $FWK_PDFCOURIERFONT = 'pdf/fonts/Courier.afm';
    // Obtener factura y sus anexos
    $TIPOSCOMPROBANTEMXP = array(1 => "Factura", 3 => "Nota de Cr.", 2 => "NOTA DE DEBITO");
    $idconsulta = "";
    $idconsulta = explode(",", trim($ids));
    foreach ($idconsulta as $valor) {
        if (is_null($valor) || $valor == "") {
            array_pop($idconsulta);
        }
    }
    $contadorTotalPaginas = count($idconsulta);
    $contadorPagina = 1;
    // Crea el documento pdf
    $pdf = new Cezpdf('LETTER', 'portrait');
    foreach ($idconsulta as $idfactura) {
        $data['idfactura'] = $idfactura;
        $factura = $facturaController->execute('facturaParaPdf', $data);
        $row_factura = $factura['respuesta'];
        $info_xtra = json_decode($row_factura["info_xtra"]);
        $data['idfacefactura'] = $factura['respuesta']['idface_factura'];
        $data['idempresa'] = $factura['respuesta']['idempresa'];
        $data['idsello'] = $factura['respuesta']['idsello'];
        $version = $factura['respuesta']['version'];
        $addenda = $facturaController->execute('datosAddenda', $data);
        $row_addenda = $addenda['respuesta'];
        $empresa = $empresaController->execute('allId', $data);
        $row_empresa = $empresa['respuesta'];
        $sello = $selloController->execute('obtenerPorIdsello', $data);
        $row_sello = $sello['respuesta'];
        $data['sucursal'] = $sello['respuesta']['sucursal'];
        $sucursal = $sucursalController->execute('nombreSucIdempresa', $data);
        $row_sucursal = $sucursal['respuesta'];
        $xmlArray = xml2array(base64_decode($row_factura['factura']));
        $attr = "_attr";
        if ($version === "3.2") {
            $NSP = "cfdi:";
        } else {
            $NSP = "";
        }
        $comprobante = $NSP . "Comprobante";
        $emisor = $NSP . "Emisor";
        $emisorDomFiscal = $NSP . "DomicilioFiscal";
        $emisorExpedidoEn = $NSP . "ExpedidoEn";
        $receptor = $NSP . "Receptor";
        $domicilio = $NSP . "Domicilio";
        $concepto = $NSP . "Conceptos";
        $conceptoTag = $NSP . "Concepto";
        $impuestos = $NSP . "Impuestos";
        $traslado = $NSP . "Traslados";
        $trasladoTag = $NSP . "Traslado";
        $retencion = $NSP . "Retenciones";
        $retencionTag = $NSP . "Retencion";
        //INICIALIZACIONES
        $comprobanteNode = null;
        $emisorNode = null;
        $emisordomicilioNode = null;
        $expedidoNode = null;
        $receptorNode = null;
        $receptordomicilioNode = null;
        $conceptoNode = null;
        $impuestosNode = null;
        $trasladoNode = null;
        $retencionNode = null;
        // -------------------------------------------------chs --------------------------------------------------------------
        $comprobanteNode = $xmlArray[$comprobante . $attr];
        $emisorNode = $xmlArray[$comprobante][$emisor . $attr];
        $emisordomicilioNode = $xmlArray[$comprobante][$emisor][$emisorDomFiscal . $attr];
        $expedidoNode = isset($xmlArray[$comprobante][$emisor][$emisorExpedidoEn . $attr]) ? $xmlArray[$comprobante][$emisor][$emisorExpedidoEn . $attr] : "";
        $receptorNode = $xmlArray[$comprobante][$receptor . $attr];
        $receptordomicilioNode = $xmlArray[$comprobante][$receptor][$domicilio . $attr];
        $conceptos = $xmlArray[$comprobante][$concepto];
        $impuestosNode = $xmlArray[$comprobante][$impuestos . $attr];
        $traslados = $xmlArray[$comprobante][$impuestos][$traslado];
        $retenciones = isset($xmlArray[$comprobante][$impuestos][$retencion][$retencionTag . $attr]) ? $xmlArray[$comprobante][$impuestos][$retencion][$retencionTag . $attr] : "";
        $regimenFiscal = $xmlArray[$comprobante][$emisor]["cfdi:RegimenFiscal_attr"]["Regimen"];
        // ---------------------------------------------------------------------------------------------------------------
        //descuentos
        $desc1 = 0.0;
        $desc2 = 0.0;
        //==================================================================================================================
        $pdf->ezSetMargins(100, 30, 30, 30);
        $pdf->selectFont($FWK_PDFDEFAULTFONT);
        $pdf->setLineStyle(0.7, '', '', '', 0);
        $pdf->openHere('Fit');
        if ($row_factura['tipocfd'] == 3) {
            $pdf->setStrokeColor(255, 0, 0);
        }
        if ($row_factura['tipocfd'] == 2) {
            $pdf->setStrokeColor(0, 255, 0);
        }
        // Inicia numeracin de paginas.
        $pagina = 1;
        $pdf->ezStartPageNumbers(500, 15, 10, '', '{PAGENUM} de {TOTALPAGENUM}', 1);
        $primeraPagina = $pdf->currentPage;
        // i. Agrega el logo de la empresa
        $pathToLogo = $path == "../" ? "../f4/extensiones/" : "";
        $logofile = "logos/f.jpg";
        //TENDRA QUE VENIR DE UN PARAMETRO EN LA BD.
        /*if(isset($row_empresa['rfc']) && !empty($row_empresa['rfc']))
        		$logofile="logos/".$row_empresa['rfc'].".jpg";*/
        if (isset($sucursal["respuesta"]["sucursal"]) && !empty($sucursal["respuesta"]["sucursal"])) {
            $logofile = "logos/" . strtolower($sucursal["respuesta"]["sucursal"]) . ".jpg";
        }
        error_log($logofile);
        if ($comprobanteNode['serie'] == "X") {
            $logofile = "logos/wingu-xpress.jpg";
        }
        $pdf->addJpegFromFile($pathToLogo . $logofile, 30, 705, 140);
        // i. Agrega la leyenda "cancelada"
        if ($row_factura['estatus'] == 0) {
            $pdf->setColor(0.9, 0.9, 0.9);
            $pdf->addText(180, 200, 65, "<b>CANCELADA</b>", -45);
            $pdf->setColor(0, 0, 0);
        }
        // ------------------------------------------ENCABEZADO ------------------------------------------
        //ENCABEZADO DE LA FACTURA
        $tipoDocto = $row_factura['tipodocumento'];
        $tipoDocto1 = $row_factura['tipodocumento'] == "FACTURA" ? "FACTURA" : "";
        $tipoDocto2 = $row_factura['tipodocumento'] == "NOTA CARGO" ? "FACTURA" : "";
        $tipoDocto3 = $row_factura['tipodocumento'] == "NOTA CREDITO" ? "NOTA DE CREDITO" : "";
        $emisor = utf8_decode($emisorNode['nombre'] . "\n" . $emisorNode['rfc']) . "\n";
        $noInterior = isset($emisordomicilioNode['noInterior']) ? $emisordomicilioNode['noInterior'] : "";
        $noExterior = isset($emisordomicilioNode['noExterior']) ? $emisordomicilioNode['noExterior'] : "";
        $emisor .= utf8_decode($emisordomicilioNode['calle'] . " {$noExterior}");
        $emisor .= utf8_decode($emisordomicilioNode['colonia']);
        if (isset($emisordomicilioNode['localidad'])) {
            $emisor .= "\n" . utf8_decode($emisordomicilioNode['localidad']);
        }
        if ($emisordomicilioNode['municipio'] != "" && isset($emisordomicilioNode['municipio'])) {
            $emisor .= "\n" . utf8_decode($emisordomicilioNode['municipio']);
        }
        if ($emisordomicilioNode['estado'] != "" && isset($emisordomicilioNode['estado'])) {
            $emisor .= ", " . utf8_decode($emisordomicilioNode['estado']);
        }
        if ($emisordomicilioNode['codigoPostal'] != "" && isset($emisordomicilioNode['codigoPostal'])) {
            $emisor .= "\nCP " . utf8_decode($emisordomicilioNode['codigoPostal']);
        }
        $emisor .= " " . utf8_decode($emisordomicilioNode['pais']);
        $telefono = isset($row_empresa['telefono']) ? $row_empresa['telefono'] : "";
        $emisor .= "\nTel: " . $telefono . "\n";
        $mail = isset($row_empresa['mail']) ? $row_empresa['mail'] : "";
        $emisor .= "\n" . $mail;
        $emisor1 = utf8_decode($emisorNode['nombre']);
        $sucursal = "";
        if ($expedidoNode != "") {
            if (utf8_decode($row_sucursal['sucursal']) == "Q") {
                $tipoSucursal = utf8_decode('Querétaro');
            } else {
                if (utf8_decode($row_sucursal['sucursal']) == "F") {
                    $tipoSucursal = utf8_decode('5/6');
                } else {
                    if (utf8_decode($row_sucursal['sucursal']) == "S") {
                        $tipoSucursal = utf8_decode('Santa Fe');
                    }
                }
            }
            $sucursal = "Sucursal " . $tipoSucursal . "\n";
            if (utf8_decode($row_sucursal['sucursal']) != "S") {
                $noInteriorExpedido = isset($expedidoNode['noInterior']) ? $expedidoNode['noInterior'] : "";
                $sucursal .= utf8_decode($expedidoNode['calle'] . " " . $expedidoNode['noExterior'] . " ") . "\n";
                $sucursal .= utf8_decode($expedidoNode['colonia']) . "\n";
                $sucursal .= utf8_decode($expedidoNode['municipio']) . ", " . utf8_decode($expedidoNode['estado']) . "\n";
                $sucursal .= "CP " . utf8_decode($expedidoNode['codigoPostal']) . " " . utf8_decode($expedidoNode['pais']);
            }
        }
        ////////// i. Nombre del emisor
        $colNames = array();
        $tableData = array(array("dato" => $emisor1));
        $colOptions = array("dato" => array('justification' => 'left', 'width' => 200));
        $options = array('showLines' => 0, 'showHeadings' => 0, 'shaded' => 0, 'shadeCol' => array(1, 1, 1), 'fontSize' => 9, 'textCol' => array(0, 0, 0), 'rowGap' => 0, 'colGap' => 0, 'xPos' => 200, 'xOrientation' => 'right', 'width' => 200, 'cols' => $colOptions, 'innerLineThickness' => 0.3, 'outerLineThickness' => 0.3);
        // Dibuja la tabla nombre del emisor
        $pdf->ezSetY(765);
        $pdf->ezTable($tableData, $colNames, "", $options);
        ////////// i. Datos del emisor y de la sucursal
        $tableData = array(array("emisor" => $emisor, "espacio" => "", "sucursal" => $sucursal));
        $colOptions = array("emisor" => array('justification' => 'left', 'width' => 150), "espacio" => array('justification' => 'left', 'width' => 3), "sucursal" => array('justification' => 'left', 'width' => 100));
        $options = array('showLines' => 0, 'showHeadings' => 0, 'shaded' => 0, 'shadeCol' => array(1, 1, 1), 'fontSize' => 7, 'textCol' => array(0, 0, 0), 'rowGap' => 0, 'colGap' => 0, 'xPos' => 190, 'xOrientation' => 'right', 'width' => 335, 'cols' => $colOptions, 'innerLineThickness' => 0.3, 'outerLineThickness' => 0.3);
        // Dibuja la tabla
        $pdf->ezTable($tableData, "", "", $options);
        ////////// i. Datos del documento
        $foliodocto = rellena("0", 6, $comprobanteNode['folio']);
        $seriedocto = $comprobanteNode['serie'];
        if (!empty($seriedocto)) {
            $foliodocto = $seriedocto . "-" . rellena("0", 6, $comprobanteNode['folio']);
        }
        $fechastr = $comprobanteNode['fecha'];
        $fechatok = explode("T", $fechastr);
        $toksf = explode("-", $fechatok[0]);
        $fechastr = $toksf[2] . "-" . $toksf[1] . "-" . $toksf[0] . " " . $fechatok[1];
        $fechastrcfdi = $row_factura['FechaTimbrado'];
        $ncert = $comprobanteNode['noCertificado'];
        $aprob = $row_factura['noCertificadoSAT'];
        //chs
        $tableData = array(array("dato" => "<b>" . $tipoDocto1 . $tipoDocto2 . $tipoDocto3 . "</b>"), array("dato" => "<b>" . $foliodocto . "</b>"), array("dato" => "FECHA DE EMISION"), array("dato" => $fechastr), array("dato" => "LUGAR DE EXPEDICION"), array("dato" => utf8_decode($info_xtra->LugarExpedicion)), array("dato" => "FECHA DE CERTIFICACION"), array("dato" => $fechastrcfdi), array("dato" => "No. de Serie del Certificado del Emisor"), array("dato" => $ncert), array("dato" => "No. de Serie del Certificado del SAT"), array("dato" => $aprob), array("dato" => "Folio Fiscal"), array("dato" => $row_factura['uuid']));
        $colOptions = array("dato" => array('justification' => 'left', 'width' => 120));
        /*JASR*/
        $options = array('showLines' => 1, 'showHeadings' => 0, 'shaded' => 2, 'shadeCol' => array(1, 1, 1), 'shadeCol2' => array(0.9, 0.9, 0.9), 'fontSize' => 7, 'textCol' => array(1, 1, 1), 'rowGap' => 2, 'colGap' => 5, 'xPos' => 455, 'xOrientation' => 'right', 'width' => 120, 'cols' => $colOptions, 'innerLineThickness' => 0.3, 'outerLineThickness' => 0.3);
        // Dibuja la tabla datos del documento
        $pdf->ezSetDy(70);
        $pdf->ezTable($tableData, "", "", $options);
        ////////// i. Datos del cliente
        $noInterior = isset($receptordomicilioNode['noInterior']) ? utf8_decode($receptordomicilioNode['noInterior']) : "";
        $municipio = isset($receptordomicilioNode['municipio']) ? $receptordomicilioNode['municipio'] : "";
        $localidadCliente = isset($receptordomicilioNode['localidad']) ? utf8_decode($receptordomicilioNode['localidad']) : "";
        $tableData1 = array(array("cliente" => "<b>Cliente</b>"), array("cliente" => utf8_decode($receptorNode['nombre'])), array("cliente" => "RFC: " . utf8_decode($receptorNode['rfc'])), array("cliente" => utf8_decode($receptordomicilioNode['calle']) . " " . utf8_decode($receptordomicilioNode['noExterior']) . " {$noInterior} "), array("cliente" => utf8_decode($receptordomicilioNode['colonia']) . " " . $localidadCliente), array("cliente" => utf8_decode($municipio) . ", " . utf8_decode($receptordomicilioNode['estado']) . "  " . utf8_decode($receptordomicilioNode['codigoPostal']) . " \n" . utf8_decode($receptordomicilioNode['pais'])), array("cliente" => utf8_decode("Atención: " . $info_xtra->Receptor->contacto . "         Cliente: " . $info_xtra->Receptor->noCliente)), array("cliente" => utf8_decode("Tel: " . $info_xtra->Receptor->telefono)));
        $formaDePago = isset($comprobanteNode['formaDePago']) ? $comprobanteNode['formaDePago'] : "PAGO EN UNA SOLA EXHIBICION";
        $metodoPago = isset($comprobanteNode['metodoDePago']) ? $comprobanteNode['metodoDePago'] : "No Identificado";
        $numeroCuentaPago = isset($comprobanteNode['NumCtaPago']) ? $comprobanteNode['NumCtaPago'] : "No Identificado";
        $tableData2 = array(array("expedido" => "Expedido en: " . utf8_decode($info_xtra->LugarExpedicion)), array("expedido" => "Forma de Pago: " . utf8_decode($formaDePago)), array("expedido" => "Metodo de Pago: " . utf8_decode($metodoPago)), array("expedido" => "No. de Cuenta: " . utf8_decode($numeroCuentaPago)), array("expedido" => "Condiciones de Pago: " . utf8_decode($comprobanteNode['condicionesDePago'])), array("expedido" => "Regimen Fiscal: " . utf8_decode(preg_replace("/Ii/", "II", ucwords(strtolower($regimenFiscal))))), array("expedido" => "Tipo de Cambio: " . $comprobanteNode['TipoCambio'] . "  Moneda: " . $comprobanteNode['Moneda']), array("expedido" => "Elaboro: " . utf8_decode($info_xtra->Vendedor)), array("expedido" => utf8_decode("Póliza: " . $info_xtra->NumeroPoliza . "          SAP No: " . $info_xtra->NumeroPedido)));
        $tableData = array();
        $aux = count($tableData1) >= count($tableData2) ? $tableData1 : $tableData2;
        $cont = 0;
        foreach ($aux as $arr) {
            array_push($tableData, array("cliente" => $tableData1[$cont]["cliente"], "expedido" => $tableData2[$cont]["expedido"]));
            $cont++;
        }
        $colNames = array("cliente" => "", "expedido" => "");
        $colOptions = array("cliente" => array('justification' => 'left', 'width' => 205), "expedido" => array('justification' => 'left', 'width' => 205));
        $options = array('showLines' => 1, 'showHeadings' => 0, 'shaded' => 1, 'shadeCol' => array(0.9, 0.9, 0.9), 'fontSize' => 7, 'textCol' => array(0, 0, 0), 'rowGap' => 2, 'colGap' => 5, 'xPos' => 35, 'xOrientation' => 'right', 'width' => 410, 'cols' => $colOptions, 'innerLineThickness' => 0.3, 'outerLineThickness' => 0.3);
        $pdf->ezSetDy(125);
        $pdf->ezTable($tableData, $colNames, "", $options);
        //encabezado
        //error_log(print_r($info_xtra,true));
        $tableData = array(array("dato" => utf8_decode($info_xtra->Consumo->NotaEncabezado)));
        $colOptions = array("dato" => array('justification' => 'left', 'width' => 540));
        $options = array('showLines' => 1, 'showHeadings' => 0, 'shaded' => 0, 'shadeCol' => array(0.9, 0.9, 0.9), 'fontSize' => 7, 'textCol' => array(0, 0, 0), 'rowGap' => 5, 'colGap' => 5, 'xPos' => 35, 'xOrientation' => 'right', 'width' => 120, 'cols' => $colOptions, 'innerLineThickness' => 0.3, 'outerLineThickness' => 0.3);
        $pdf->ezSetDy(-10);
        $pdf->ezTable($tableData, "", "", $options);
        $actualY = $pdf->y;
        $pdf->setColor(0, 0, 0);
        $pdf->filledRectangle(30, $actualY - 30, 540, 18);
        $pdf->ezSetY($actualY - 15);
        $pdf->setColor(1, 1, 1);
        $pdf->ezText("<b>Codigo</b>", 7, array('left' => 25, 'justification' => 'left'));
        $pdf->ezSetY($actualY - 15);
        $pdf->ezText("<b>Descripcion</b>", 7, array('left' => 180, 'justification' => 'left'));
        $pdf->ezSetY($actualY - 15);
        $pdf->ezText("<b>Cant</b>", 7, array('left' => 361, 'justification' => 'left'));
        $pdf->ezSetY($actualY - 15);
        $pdf->ezText("<b>Unidad</b>", 7, array('left' => 398, 'justification' => 'left'));
        $pdf->ezSetY($actualY - 15);
        $pdf->ezText("<b>Unitario</b>", 7, array('left' => 445, 'justification' => 'left'));
        $pdf->ezSetY($actualY - 15);
        $pdf->ezText("<b>Importe</b>", 7, array('left' => 497, 'justification' => 'left'));
        ////////// i. Partidas
        $tableData = array();
        $renglones = 0;
        $rowData = array("codigo" => "", "cantidad" => "", "unidad" => "", "descripcion" => "", "unitario" => "", "importe" => "");
        $partidaCnt = 0;
        $cantidadArrayConceptos = count($conceptos);
        foreach ($conceptos as $key => $conceptoNode) {
            if (stristr($key, $attr) && $cantidadArrayConceptos == 2) {
                $partidaCnt++;
                $renglones += 2;
                $currentObj = array();
                $descripcion = $conceptoNode['descripcion'];
                $totalPalabras = strlen($descripcion);
                $totalCaracteres = 4800;
                if ($totalPalabras >= $totalCaracteres) {
                    $pagDesc = ceil($totalPalabras / $totalCaracteres);
                    $aux = 1;
                    $array = array();
                    for ($i = 1; $i <= $pagDesc; $i++) {
                        if ($i == $pagDesc) {
                            $array[] = $totalPalabras;
                        } else {
                            $val = $aux += $totalCaracteres;
                            $array[] = $val;
                        }
                    }
                    $desc = array();
                    $o = 0;
                    foreach ($array as $valor) {
                        $desc[] = substr($descripcion, $o, $valor);
                        $o += $valor - $o;
                    }
                    $cont = 1;
                    foreach ($desc as $descripcionexp) {
                        $currentObj["codigo"] = $info_xtra->Consumo->partidas[$partidaCnt - 1]->codigo;
                        $currentObj["cantidad"] = number_format(abs(doubleval($conceptoNode['cantidad'])), 2);
                        //$currentObj["unidad"]= (isset($conceptoNode['unidad'])) ? $conceptoNode['unidad'] :  "No Aplica";
                        $currentObj["unidad"] = $conceptoNode['unidad'];
                        //)) ? $conceptoNode['unidad'] :  "No Aplica";
                        $currentObj["descripcion"] = str_replace("__", "\n", utf8_decode($descripcionexp) . "\n" . utf8_decode($info_xtra->Consumo->partidas[$partidaCnt - 1]->nota));
                        if ($info_xtra->TipoImpresion == "KI2") {
                            $contPartidas = count($info_xtra->Consumo->partidas);
                            for ($i = 1; $i < $contPartidas; $i++) {
                                $currentObj["descripcion"] .= $info_xtra->Consumo->partidas[$i]->codigo . " " . $info_xtra->Consumo->partidas[$i]->cantidad . " " . $info_xtra->Consumo->partidas[$i]->unidad . " " . $info_xtra->Consumo->partidas[$i]->descripcion . " \$" . $info_xtra->Consumo->partidas[$i]->valorUnitario . " \n";
                            }
                        }
                        $currentObj["unitario"] = number_format($conceptoNode['valorUnitario'], 2);
                        $currentObj["importe"] = number_format(doubleval($conceptoNode['importe']), 2);
                        $for = $cont++;
                        log_action("for:::" . $for);
                        if ($for > 1) {
                            $currentObj["codigo"] = "";
                            $currentObj["cantidad"] = "";
                            $currentObj["unidad"] = "";
                            $currentObj["unitario"] = "";
                            $currentObj["importe"] = "";
                        }
                        array_push($tableData, $currentObj);
                    }
                } else {
                    $currentObj["codigo"] = $info_xtra->Consumo->partidas[$partidaCnt - 1]->codigo;
                    $currentObj["cantidad"] = number_format(abs(doubleval($conceptoNode['cantidad'])), 2);
                    //$currentObj["unidad"]= (isset($conceptoNode['unidad'])) ? $conceptoNode['unidad'] :  "No Aplica";
                    $currentObj["unidad"] = $conceptoNode['unidad'];
                    //)) ? $conceptoNode['unidad'] :  "No Aplica";
                    $currentObj["descripcion"] = str_replace("__", "\n", utf8_decode($descripcion) . "\n" . utf8_decode($info_xtra->Consumo->partidas[$partidaCnt - 1]->nota));
                    if ($info_xtra->TipoImpresion == "KI2") {
                        $contPartidas = count($info_xtra->Consumo->partidas);
                        for ($i = 1; $i < $contPartidas; $i++) {
                            $currentObj["descripcion"] .= utf8_decode($info_xtra->Consumo->partidas[$i]->codigo . " " . $info_xtra->Consumo->partidas[$i]->cantidad . " " . $info_xtra->Consumo->partidas[$i]->unidad . " " . $info_xtra->Consumo->partidas[$i]->descripcion . " " . $info_xtra->Consumo->partidas[$i]->valorUnitario) . " \n";
                        }
                    }
                    $currentObj["unitario"] = number_format($conceptoNode['valorUnitario'], 2);
                    $currentObj["importe"] = number_format(doubleval($conceptoNode['importe']), 2);
                    array_push($tableData, $currentObj);
                }
            } else {
                foreach ($conceptoNode as $key1 => $conceptoNode1) {
                    log_action(print_r($key1, TRUE));
                    if (stristr($key1, $attr)) {
                        $partidaCnt++;
                        $renglones += 2;
                        $currentObj = array();
                        $currentObj["codigo"] = $info_xtra->Consumo->partidas[$partidaCnt - 1]->codigo;
                        $currentObj["cantidad"] = number_format(abs(doubleval($conceptoNode1['cantidad'])), 2);
                        //$currentObj["unidad"]= (isset($conceptoNode['unidad'])) ? $conceptoNode['unidad'] :  "No Aplica";
                        $currentObj["unidad"] = $conceptoNode1['unidad'];
                        //)) ? $conceptoNode['unidad'] :  "No Aplica";
                        $currentObj["descripcion"] = str_replace("__", "\n", utf8_decode($conceptoNode1['descripcion'] . "\n" . $info_xtra->Consumo->partidas[$partidaCnt - 1]->nota));
                        if ($info_xtra->TipoImpresion == "KI2") {
                            $contPartidas = count($info_xtra->Consumo->partidas);
                            for ($i = 1; $i < $contPartidas; $i++) {
                                $currentObj["descripcion"] .= $info_xtra->Consumo->partidas[$i]->codigo . " " . $info_xtra->Consumo->partidas[$i]->cantidad . " " . $info_xtra->Consumo->partidas[$i]->unidad . " " . $info_xtra->Consumo->partidas[$i]->descripcion . " \$" . $info_xtra->Consumo->partidas[$i]->valorUnitario . " \n";
                            }
                        }
                        $currentObj["unitario"] = number_format($conceptoNode1['valorUnitario'], 2);
                        $currentObj["importe"] = number_format(doubleval($conceptoNode1['importe']), 2);
                        array_push($tableData, $currentObj);
                    }
                }
                //fin foreach 2  chs 20130705
            }
        }
        $currentObj = array();
        $currentObj["codigo"] = "";
        $currentObj["cantidad"] = "";
        $currentObj["unidad"] = "";
        $currentObj["descripcion"] = str_replace("__", "\n", utf8_decode($row_factura["fnotas"]));
        $currentObj["unitario"] = "";
        $currentObj["importe"] = "";
        array_push($tableData, $currentObj);
        if (isset($row_addenda['cl_fld1'])) {
            $currentObj = array();
            $currentObj["cantidad"] = "";
            $currentObj["descripcion"] = $row_addenda['cl_fld1'];
            if (!empty($row_addenda['cl_fld2'])) {
                $currentObj["descripcion"] .= "\n" . $row_addenda['cl_fld2'];
            }
            if (!empty($row_addenda['cl_fld3'])) {
                $currentObj["descripcion"] .= "\n" . $row_addenda['cl_fld3'];
            }
            if (!empty($row_addenda['cl_fld4'])) {
                $currentObj["descripcion"] .= "\n" . $row_addenda['cl_fld4'];
            }
            if (!empty($row_addenda['cl_fld5'])) {
                $currentObj["descripcion"] .= "\n" . $row_addenda['cl_fld5'];
            }
            if (!empty($row_addenda['cl_fld6'])) {
                $currentObj["descripcion"] .= "\n" . $row_addenda['cl_fld6'];
            }
            if (!empty($row_addenda['cl_fld7'])) {
                $currentObj["descripcion"] .= "\n" . $row_addenda['cl_fld7'];
            }
            if (!empty($row_addenda['cl_fld8'])) {
                $currentObj["descripcion"] .= "\n" . $row_addenda['cl_fld8'];
            }
            if (!empty($row_addenda['cl_fld9'])) {
                $currentObj["descripcion"] .= "\n" . $row_addenda['cl_fld9'];
            }
            if (!empty($row_addenda['cl_fld10'])) {
                $currentObj["descripcion"] .= "\n" . $row_addenda['cl_fld10'];
            }
            if (!empty($row_addenda['cl_fld11'])) {
                $currentObj["descripcion"] .= "\n" . $row_addenda['cl_fld11'];
            }
            if (!empty($row_addenda['cl_fld12'])) {
                $currentObj["descripcion"] .= "\n" . $row_addenda['cl_fld12'];
            }
            $currentObj["unitario"] = "";
            $currentObj["importe"] = "";
            array_push($tableData, $currentObj);
        }
        $currentObj = array();
        $currentObj["codigo"] = "";
        $currentObj["cantidad"] = "";
        $currentObj["unidad"] = "";
        $currentObj["descripcion"] = "";
        $currentObj["unitario"] = "";
        $currentObj["importe"] = "";
        if ($info_xtra->TipoImpresion == "KI2") {
            for ($renglones; $renglones < 10 - count($info_xtra->Consumo->partidas) * 0.95; $renglones++) {
                array_push($tableData, $currentObj);
            }
        } else {
            if ($renglones < 10) {
                for ($renglones; $renglones < 10; $renglones++) {
                    array_push($tableData, $currentObj);
                }
            }
        }
        $colNames = array("codigo" => "", "descripcion" => "", "cantidad" => "", "unidad" => "", "unitario" => "", "importe" => "");
        $colOptions = array("codigo" => array('justification' => 'center', 'width' => 70), "descripcion" => array('justification' => 'left', 'width' => 280), "cantidad" => array('justification' => 'center', 'width' => 40), "unidad" => array('justification' => 'left', 'width' => 40), "unitario" => array('justification' => 'right', 'width' => 55), "importe" => array('justification' => 'right', 'width' => 55));
        $options = array('showLines' => 1, 'showHeadings' => 1, 'shaded' => 1, 'shadeCol' => array(0.9, 0.9, 0.9), 'fontSize' => 7, 'textCol' => array(0, 0, 0), 'rowGap' => 4, 'colGap' => 5, 'xPos' => 35, 'xOrientation' => 'right', 'width' => 410, 'cols' => $colOptions, 'innerLineThickness' => 0.3, 'outerLineThickness' => 0.3);
        // Dibuja la tabla partidas
        $pdf->ezSetDy(11);
        $pdf->ezTable($tableData, $colNames, "", $options);
        ////////// i. Cantidad con letra
        $cadena = covertirNumLetras(number_format($comprobanteNode['total'], 2, ".", ''));
        if ($comprobanteNode['Moneda'] == "USD") {
            $cadena = str_replace("M.N.", "USD", $cadena);
            $cadena = str_replace("PESOS", "DOLARES", $cadena);
            $cadena = str_replace("PESO", "DOLAR", $cadena);
        }
        $tableData = array(array("dato" => "<b>Nota:</b>\n" . utf8_decode($info_xtra->Consumo->notaAlPie)), array("dato" => "<b>Total con letra</b>\n" . trim($cadena)));
        $colNames = array("dato" => "<b>Cant</b>");
        $colOptions = array("dato" => array('justification' => 'left', 'width' => 390));
        $options = array('showLines' => 1, 'showHeadings' => 0, 'shaded' => 1, 'shadeCol' => array(0.9, 0.9, 0.9), 'fontSize' => 7, 'textCol' => array(0, 0, 0), 'rowGap' => 2.5, 'colGap' => 5, 'xPos' => 35, 'xOrientation' => 'right', 'width' => 120, 'cols' => $colOptions, 'innerLineThickness' => 0.3, 'outerLineThickness' => 0.3);
        // Dibuja la tabla cantidad con letra
        $pdf->ezSetDy(0);
        $pdf->ezTable($tableData, "", "", $options);
        ////////// i. Totales
        $f_importe = "\$" . number_format($comprobanteNode['subTotal'], 2);
        //$f_iva_T=$conceptoNode['totalImpuestosTrasladados'];
        $f_total = "\$" . number_format($comprobanteNode['total'], 2);
        $tableData = array();
        $rowData = array("leyenda" => "", "cantidad" => "");
        $subtotal = array("dato" => "Subtotal", "valor" => $f_importe);
        array_push($tableData, $subtotal);
        foreach ($traslados as $key => $trasladoNode) {
            if ($key === $trasladoTag . $attr) {
                $tasaImpuesto = array();
                $tasaImpuesto_t = number_format($trasladoNode['tasa'], 0);
                $tasaImpuesto["dato"] = $trasladoNode['impuesto'] . " " . $tasaImpuesto_t . "%";
                $tasaImpuesto["valor"] = "\$" . number_format($trasladoNode['importe'], 2);
                //array_push($tableData,$tasaImpuesto);
            }
        }
        if (!empty($retenciones)) {
            foreach ($retenciones as $key => $retencionNode) {
                if ($key === $retencionTag . $attr) {
                    $tasaImpuesto = array();
                    $tasaImpuesto_t = number_format($retencionNode['tasa'], 2);
                    $tasaImpuesto["dato"] = "Ret. " . $retencionNode['impuesto'];
                    $tasaImpuesto["valor"] = "\$" . number_format($retencionNode['importe'], 2);
                    //array_push($tableData,$tasaImpuesto);
                }
            }
        }
        //fin if empty
        $iva = array("dato" => "<b>IVA</b>", "valor" => "<b>\$ " . number_format($info_xtra->TotalImpuestosTrasladados, 2) . "</b>");
        array_push($tableData, $iva);
        $total = array("dato" => "<b>Total</b>", "valor" => "<b>" . $f_total . "</b>");
        array_push($tableData, $total);
        $colNames = array("dato" => "<b>Cant</b>", "valor" => "Importe");
        $colOptions = array("dato" => array('justification' => 'right', 'width' => 55), "valor" => array('justification' => 'right', 'width' => 95));
        $options = array('showLines' => 1, 'showHeadings' => 0, 'shaded' => 2, 'shadeCol' => array(1, 1, 1), 'shadeCol2' => array(91, 21, 0), 'fontSize' => 7, 'textCol' => array(0, 0, 0), 'rowGap' => 3, 'colGap' => 5, 'xPos' => 425, 'xOrientation' => 'right', 'width' => 120, 'cols' => $colOptions, 'innerLineThickness' => 0.3, 'outerLineThickness' => 0.3);
        // Dibuja la tabla totales
        $pdf->ezSetDy(42.5);
        $pdf->ezTable($tableData, $colNames, "", $options);
        $rfce = $row_empresa['rfc'];
        $rfcr = $receptorNode['rfc'];
        $total = $comprobanteNode['total'];
        $uuidsat = $row_factura['uuid'];
        $cadenaQRCode = sprintf("?re=%s&rr=%s&tt=%s&id=%s", $rfce, $rfcr, $total, $uuidsat);
        /*QR Code: Para usar qr_imgV2():  qr_imgV2(d,e,s,v,t);
          d= datos        Cadena o datos a ser codificados.
          e= ECC level    Puede ser L,M,Q,H  (default M)
          s= module size  Para imagen JPEG:8; para PNG:4
          v= version      1-40   8 recomendado.
          t= image type   "J":imagen jpeg, "P" o culaquier otra cosa: imagen PNG */
        $img_filename = qr_imgV2($cadenaQRCode, "M", 8, 8, "J", $PATHQR);
        //v:7-13 8 parece adecuado.
        //$pdf->addJpegFromFile($img_filename,495,$pdf->y,90); //100
        //$pdf->addJpegFromFile($img_filename,32,170,130); //100
        $pdf->addJpegFromFile($img_filename, 32, $pdf->y - 140, 130);
        //100
        unlink($img_filename);
        ////////// i. Sello
        if ($version === "3.2") {
            $tableData = array(array("dato" => "<b>Sello Digital del Emisor</b>\n" . $row_factura['sello']), array("dato" => "<b>Sello Digital del SAT</b>\n" . $row_factura['selloSAT']));
        } else {
            $tableData = array(array("dato" => "<b>Sello Digital</b>\n" . $row_factura['sello']));
        }
        $colNames = array("dato" => "<b>Cant</b>");
        $colOptions = array("dato" => array('justification' => 'left', 'width' => 400));
        $options = array('showLines' => 1, 'showHeadings' => 0, 'shaded' => 0, 'shadeCol' => array(0.8, 0.8, 0.8), 'fontSize' => 7, 'textCol' => array(0, 0, 0), 'rowGap' => 5, 'colGap' => 5, 'xPos' => 175, 'xOrientation' => 'right', 'width' => 120, 'cols' => $colOptions, 'innerLineThickness' => 0.3, 'outerLineThickness' => 0.3);
        // Dibuja la tabla sello
        $pdf->ezSetDy(-10);
        $pdf->ezTable($tableData, $colNames, "", $options);
        /*$pdf->setColor(91,21,0);
        		$pdf->filledRectangle(30,167,134,151);
        		$pdf->setColor(1,1,1);	
        		$pdf->filledRectangle(31,167.5,132.3,149.5);*/
        ////////// i. Cadena original
        $columnaCadena = "";
        if ($version === "3.2") {
            $columnaCadena = sprintf("||1.0|%s|%s|%s|%s||", $row_factura['uuid'], $row_factura['FechaTimbrado'], $row_factura['selloCFD'], $row_factura['noCertificadoSAT']);
        } else {
            $columnaCadena = sprintf("%s", $row_factura['cadena']);
        }
        $tableData = array(array("dato" => "<b>Cadena original del complemento de certificacion digital del SAT</b>\n" . $columnaCadena), array("dato" => "<b>Folio Fiscal</b>\n" . $row_factura['uuid']));
        $colNames = array("dato" => "<b>Cant</b>");
        $colOptions = array("dato" => array('justification' => 'left', 'width' => 400));
        $options = array('showLines' => 1, 'showHeadings' => 0, 'shaded' => 0, 'shadeCol' => array(0.8, 0.8, 0.8), 'fontSize' => 7, 'textCol' => array(0, 0, 0), 'rowGap' => 5, 'colGap' => 5, 'xPos' => 175, 'xOrientation' => 'right', 'width' => 120, 'cols' => $colOptions, 'innerLineThickness' => 0.3, 'outerLineThickness' => 0.3);
        // Dibuja la tabla cadena original
        $pdf->ezSetDy(-5);
        $pdf->ezTable($tableData, $colNames, "", $options);
        // Leyendas
        $pdf->ezSetDy(-12);
        $leyendas = "ESTE DOCUMENTO ES UNA REPRESENTACION IMPRESA DE UN CFDI.\n";
        $pdf->setColor(0.5, 0.5, 0.5);
        $pdf->ezText($leyendas, 5, array('left' => 50, 'justification' => 'center'));
        $pdf->setColor(0, 0, 0);
        $pdf->ezStream(array("filename" => $row_factura['folio'] . "_" . str_replace(" ", "-", $receptorNode['nombre'])));
        //Necesario para que funcione ezStartPageNumbers
        //REGRESA PARA PONER ENCABEZADO EN PAGINAS 2 ->
        if ($contadorPagina != $contadorTotalPaginas) {
            $pdf->ezNewPage();
            $pdf->ezSetDy(-12);
        }
        $contadorPagina++;
    }
    //fin del foreach para la creacion del objeto pdf
    //ESCRIBE REPORTE AL ARCHIVO.
    //================================================================================
    $pdfcode = $pdf->output();
    error_log($tmpName);
    if ($tmpName === 2 || !$tmpName) {
        $tmpName = !$tmpName ? $tmpName : true;
    } else {
        exit($pdfcode);
    }
    //save the file
    if ($tmpName) {
        $nombrePDF = tempnam($tmp . "tmp/", 'face5') . ".pdf";
        $nombreToks = explode("/", $nombrePDF);
        if (count($nombreToks) < 2) {
            $nombreToks = explode("\\", $nombrePDF);
        }
        $lastTok = count($nombreToks) - 1;
        $nombrePDF = $nombreToks[$lastTok];
        $archivoPDF = $tmp . "tmp/" . $nombrePDF;
        $archivos = array($nombrePDF, $archivoPDF);
        error_log(print_R($archivos, true));
    } else {
        $nombrePDF = $tipoDocto . "_" . $row_factura['serie'] . $row_factura['folio'] . ".pdf";
        //$archivoPDF ="tmp/".$nombrePDF;//chs 20130705
        $archivoPDF = $tmp . "tmp/" . $nombrePDF;
        $archivos = array($nombrePDF, $archivoPDF);
        error_log(2);
        ob_flush();
        ob_clean();
    }
    global $SITE_ROOT;
    error_log($archivoPDF);
    @file_put_contents($SITE_ROOT . "gui/" . $archivoPDF, $pdfcode);
    /*$fp = fopen($archivoPDF,'w+');
    		fwrite($fp,$pdfcode);
    		fclose($fp);*/
    return $archivos;
}
Beispiel #15
0
 function pdf_einauszugsbestaetigung(Cezpdf $pdf, $mv_id, $einzug = 0)
 {
     $pdf->ezSetMargins(135, 70, 50, 50);
     $mv = new mietvertraege();
     $mv->get_mietvertrag_infos_aktuell($mv_id);
     $oo = new objekt();
     $oo->get_objekt_infos($mv->objekt_id);
     if ($mv->anzahl_personen > 1) {
         $ist_sind = 'sind';
     } else {
         $ist_sind = 'ist';
     }
     if ($einzug == '0') {
         $pdf->ezText("<b>Einzugsbestätigung</b>", 18, array('justification' => 'left'));
         $pdf->ezText("{$mv->einheit_kurzname}", 10, array('justification' => 'right'));
     } else {
         $pdf->ezText("<b>Auszugsbestätigung</b>", 18, array('justification' => 'left'));
         $pdf->ezText("{$mv->einheit_kurzname}", 10, array('justification' => 'right'));
     }
     $pdf->ezText("<b>Wohnungsgeberbescheinigung gemäß § 19 des Bundesmeldegesetzes (BMG)</b>", 11, array('justification' => 'left'));
     $pdf->ezSetDy(-35);
     // Abstand
     $pdf->ezText("Hiermit bestätige(n) ich/wir als Wohnungsgeber/Vermieter, dass", 10);
     $pdf->ezSetDy(-15);
     // Abstand
     $pdf->ezText("{$mv->personen_name_string_u}", 10);
     $pdf->ezSetDy(-15);
     // Abstand
     if ($einzug == '0') {
         $pdf->ezText("in die von mir/uns vermietete Wohnung", 10);
     } else {
         $pdf->ezText("aus der von mir/uns vermieteten Wohnung", 10);
     }
     $pdf->ezSetDy(-15);
     // Abstand
     $pdf->ezText("unter der Anschrift: {$mv->haus_strasse} {$mv->haus_nr}, {$mv->haus_plz} {$mv->haus_stadt}  (Wohnlage:</b> {$mv->einheit_lage})", 10);
     $pdf->ezSetDy(-15);
     // Abstand
     if ($einzug == '0') {
         $pdf->ezText("am _______________________  eingezogen {$ist_sind}.", 10);
     } else {
         $pdf->ezText("am _______________________  ausgezogen {$ist_sind}.", 10);
     }
     $pdf->ezSetDy(-20);
     // Abstand
     if (empty($oo->objekt_eigentuemer)) {
         $pdf->ezSetDy(-30);
         // Abstand
         $this->kasten($pdf, 1, 50, 10, 10);
         $pdf->addText(70, $pdf->y + 1, 10, 'Der Wohnungsgeber/Vermieter ist gleichzeitig <b>Eigentümer</b> der Wohnung oder');
         $pdf->ezSetDy(-20);
         // Abstand
         $this->kasten($pdf, 1, 50, 10, 10);
         $pdf->addText(70, $pdf->y + 1, 10, "Der Wohnungsgeber/Vermieter ist <b>nicht</b> Eigentümer der Wohnung");
         $pdf->ezSetDy(-15);
         // Abstand
         $pdf->ezSetDy(-25);
         // Abstand
         $pdf->line(50, $pdf->y, 550, $pdf->y);
         $pdf->ezSetDy(-25);
         // Abstand
         $pdf->line(50, $pdf->y, 550, $pdf->y);
     } else {
         $this->kasten($pdf, 1, 50, 10, 10);
         $pdf->addText(50, $pdf->y + 2, 10, 'X');
         $pdf->addText(70, $pdf->y + 1, 10, "Der Wohnungsgeber ist <b>nicht</b> Eigentümer der Wohnung");
         $pdf->ezSetDy(-15);
         // Abstand
         $pdf->ezText("Name und Anschrift des <b>Eigentümers</b> lauten:", 10);
         $pdf->ezText("{$oo->objekt_eigentuemer}", 10);
         $pp = new partners();
         $pp->get_partner_info($oo->objekt_eigentuemer_id);
         $pdf->ezText("{$pp->partner_strasse} {$pp->partner_hausnr}, {$pp->partner_plz} {$pp->partner_ort}", 10);
     }
     $pdf->ezSetDy(-25);
     // Abstand
     $pdf->ezText("Ich bestätige mit meiner Unterschrift den Ein- bzw. Auszug der oben genannten Person(en) in die näher bezeichnete Wohnung und dass ich als Wohnungsgeber oder als beauftragte Person diese Bescheinigung ausstellen darf. Ich habe davon Kenntnis genommen, da ich ordnungswidrig handele, wenn ich hierzu nicht berechtigt bin und dass es verboten ist, eine Wohnanschrift für eine Anmeldung eines Wohnsitzes einem Dritten anzubieten oder zur Verfügung zu stellen, obwohl ein tatsächlicher Bezug der Wohnung durch einen Dritten weder stattfindet noch beabsichtigt ist. Ein Verstoß gegen das Verbot stellt auch einen Ordnungswidrigkeit dar.", 8);
     /* Footer */
     $pdf->ezSetDy(-25);
     // Abstand
     $pdf->ezText("{$mv->haus_stadt}, __________________", 9, array('justification' => 'left'));
     $pdf->ezSetDy(-7);
     // Abstand
     $pdf->addText(125, $pdf->y, 6, "Datum");
     $pdf->ezSetDy(-30);
     // Abstand
     $pdf->ezText("____________________________________________", 9, array('justification' => 'left'));
     $pdf->ezSetDy(-8);
     // Abstand
     $pdf->addText(57, $pdf->y, 6, "Unterschrift des Wohnungsgebers/Vermieters oder der beauftragten Person");
     $pdf->ezSetDy(-15);
     // Abstand
 }
Beispiel #16
0
 function get_printable_file($_FORM = array())
 {
     global $TPL;
     $db = new db_alloc();
     $TPL["companyName"] = config::get_config_item("companyName");
     $TPL["companyNos1"] = config::get_config_item("companyACN");
     $TPL["companyNos2"] = config::get_config_item("companyABN");
     $TPL["img"] = config::get_config_item("companyImage");
     $TPL["companyContactAddress"] = config::get_config_item("companyContactAddress");
     $TPL["companyContactAddress2"] = config::get_config_item("companyContactAddress2");
     $TPL["companyContactAddress3"] = config::get_config_item("companyContactAddress3");
     $email = config::get_config_item("companyContactEmail");
     $email and $TPL["companyContactEmail"] = "Email: " . $email;
     $web = config::get_config_item("companyContactHomePage");
     $web and $TPL["companyContactHomePage"] = "Web: " . $web;
     $phone = config::get_config_item("companyContactPhone");
     $fax = config::get_config_item("companyContactFax");
     $phone and $TPL["phone"] = "Ph: " . $phone;
     $fax and $TPL["fax"] = "Fax: " . $fax;
     $taskPriorities = config::get_config_item("taskPriorities");
     $projectPriorities = config::get_config_item("projectPriorities");
     // Add requested fields to pdf
     $_FORM["showEdit"] = false;
     $fields["taskID"] = "ID";
     $fields["taskName"] = "Task";
     $_FORM["showProject"] and $fields["projectName"] = "Project";
     $_FORM["showPriority"] || $_FORM["showPriorityFactor"] and $fields["priorityFactor"] = "Pri";
     $_FORM["showPriority"] and $fields["taskPriority"] = "Task Pri";
     $_FORM["showPriority"] and $fields["projectPriority"] = "Proj Pri";
     $_FORM["showCreator"] and $fields["creator_name"] = "Creator";
     $_FORM["showManager"] and $fields["manager_name"] = "Manager";
     $_FORM["showAssigned"] and $fields["assignee_name"] = "Assigned To";
     $_FORM["showDate1"] and $fields["dateTargetStart"] = "Targ Start";
     $_FORM["showDate2"] and $fields["dateTargetCompletion"] = "Targ Compl";
     $_FORM["showDate3"] and $fields["dateActualStart"] = "Start";
     $_FORM["showDate4"] and $fields["dateActualCompletion"] = "Compl";
     $_FORM["showDate5"] and $fields["dateCreated"] = "Created";
     $_FORM["showTimes"] and $fields["timeBestLabel"] = "Best";
     $_FORM["showTimes"] and $fields["timeExpectedLabel"] = "Likely";
     $_FORM["showTimes"] and $fields["timeWorstLabel"] = "Worst";
     $_FORM["showTimes"] and $fields["timeActualLabel"] = "Actual";
     $_FORM["showTimes"] and $fields["timeLimitLabel"] = "Limit";
     $_FORM["showPercent"] and $fields["percentComplete"] = "%";
     $_FORM["showStatus"] and $fields["taskStatusLabel"] = "Status";
     $rows = task::get_list($_FORM);
     $taskListRows = array();
     foreach ((array) $rows as $row) {
         $row["taskPriority"] = $taskPriorities[$row["priority"]]["label"];
         $row["projectPriority"] = $projectPriorities[$row["projectPriority"]]["label"];
         $row["taskDateStatus"] = strip_tags($row["taskDateStatus"]);
         $row["percentComplete"] = strip_tags($row["percentComplete"]);
         $taskListRows[] = $row;
     }
     if ($_FORM["format"] != "html" && $_FORM["format"] != "html_plus") {
         // Build PDF document
         $font1 = ALLOC_MOD_DIR . "util/fonts/Helvetica.afm";
         $font2 = ALLOC_MOD_DIR . "util/fonts/Helvetica-Oblique.afm";
         $pdf_table_options = array("showLines" => 0, "shaded" => 0, "showHeadings" => 0, "xPos" => "left", "xOrientation" => "right", "fontSize" => 10, "rowGap" => 0, "fontSize" => 10);
         $pdf_table_options3 = array("showLines" => 2, "shaded" => 0, "width" => 750, "xPos" => "center", "fontSize" => 10, "lineCol" => array(0.8, 0.8, 0.8), "splitRows" => 1, "protectRows" => 0);
         $pdf = new Cezpdf(null, 'landscape');
         $pdf->ezSetMargins(40, 40, 40, 40);
         $pdf->selectFont($font1);
         $pdf->ezStartPageNumbers(436, 30, 10, 'center', 'Page {PAGENUM} of {TOTALPAGENUM}');
         $pdf->ezSetY(560);
         $TPL["companyContactAddress"] and $contact_info[] = array($TPL["companyContactAddress"]);
         $TPL["companyContactAddress2"] and $contact_info[] = array($TPL["companyContactAddress2"]);
         $TPL["companyContactAddress3"] and $contact_info[] = array($TPL["companyContactAddress3"]);
         $TPL["companyContactEmail"] and $contact_info[] = array($TPL["companyContactEmail"]);
         $TPL["companyContactHomePage"] and $contact_info[] = array($TPL["companyContactHomePage"]);
         $TPL["phone"] and $contact_info[] = array($TPL["phone"]);
         $TPL["fax"] and $contact_info[] = array($TPL["fax"]);
         $pdf->selectFont($font2);
         $y = $pdf->ezTable($contact_info, false, "", $pdf_table_options);
         $pdf->selectFont($font1);
         $line_y = $y - 10;
         $pdf->setLineStyle(1, "round");
         $pdf->line(40, $line_y, 801, $line_y);
         $pdf->ezSetY(570);
         $image_jpg = ALLOC_LOGO;
         if (file_exists($image_jpg)) {
             $pdf->ezImage($image_jpg, 0, sprintf("%d", config::get_config_item("logoScaleX")), 'none');
             $y = 700;
         } else {
             $y = $pdf->ezText($TPL["companyName"], 27, array("justification" => "right"));
         }
         $nos_y = $line_y + 22;
         $TPL["companyNos2"] and $nos_y = $line_y + 34;
         $pdf->ezSetY($nos_y);
         $TPL["companyNos1"] and $y = $pdf->ezText($TPL["companyNos1"], 10, array("justification" => "right"));
         $TPL["companyNos2"] and $y = $pdf->ezText($TPL["companyNos2"], 10, array("justification" => "right"));
         $pdf->ezSetY($line_y - 10);
         $y = $pdf->ezText("Task List", 20, array("justification" => "center"));
         $pdf->ezSetY($y - 20);
         $y = $pdf->ezTable($taskListRows, $fields, "", $pdf_table_options3);
         $pdf->ezSetY($y - 20);
         $pdf->ezStream();
         // Else HTML format
     } else {
         echo task::get_list_html($taskListRows, $_FORM);
     }
 }
Beispiel #17
0
 function generate_invoice_file($verbose = false, $getfile = false)
 {
     // Build PDF document
     $font1 = ALLOC_MOD_DIR . "util/fonts/Helvetica.afm";
     $font2 = ALLOC_MOD_DIR . "util/fonts/Helvetica-Oblique.afm";
     $db = new db_alloc();
     // Get client name
     $client = $this->get_foreign_object("client");
     $clientName = $client->get_value("clientName");
     // Get cyber info
     $companyName = config::get_config_item("companyName");
     $companyNos1 = config::get_config_item("companyACN");
     $companyNos2 = config::get_config_item("companyABN");
     $phone = config::get_config_item("companyContactPhone");
     $fax = config::get_config_item("companyContactFax");
     $phone and $phone = "Ph: " . $phone;
     $fax and $fax = "Fax: " . $fax;
     $img = config::get_config_item("companyImage");
     $companyContactAddress = config::get_config_item("companyContactAddress");
     $companyContactAddress2 = config::get_config_item("companyContactAddress2");
     $companyContactAddress3 = config::get_config_item("companyContactAddress3");
     $email = config::get_config_item("companyContactEmail");
     $email and $companyContactEmail = "Email: " . $email;
     $web = config::get_config_item("companyContactHomePage");
     $web and $companyContactHomePage = "Web: " . $web;
     $footer = config::get_config_item("timeSheetPrintFooter");
     $taxName = config::get_config_item("taxName");
     if ($this->get_value("invoiceDateFrom") && $this->get_value("invoiceDateTo") && $this->get_value("invoiceDateFrom") != $this->get_value("invoiceDateTo")) {
         $period = format_date(DATE_FORMAT, $this->get_value("invoiceDateFrom")) . " to " . format_date(DATE_FORMAT, $this->get_value("invoiceDateTo"));
     } else {
         $period = format_date(DATE_FORMAT, $this->get_value("invoiceDateTo"));
     }
     $default_header = "Tax Invoice";
     $default_id_label = "Invoice Number";
     $pdf_table_options = array("showLines" => 0, "shaded" => 0, "showHeadings" => 0, "xPos" => "left", "xOrientation" => "right", "fontSize" => 10, "rowGap" => 0, "fontSize" => 10);
     $cols = array("one" => "", "two" => "", "three" => "", "four" => "");
     $cols3 = array("one" => "", "two" => "");
     $cols_settings["one"] = array("justification" => "right");
     $cols_settings["three"] = array("justification" => "right");
     $pdf_table_options2 = array("showLines" => 0, "shaded" => 0, "showHeadings" => 0, "width" => 400, "fontSize" => 10, "xPos" => "center", "xOrientation" => "center", "cols" => $cols_settings);
     $cols_settings2["gst"] = array("justification" => "right");
     $cols_settings2["money"] = array("justification" => "right");
     $cols_settings2["unit"] = array("justification" => "right");
     $pdf_table_options3 = array("showLines" => 2, "shaded" => 0, "width" => 400, "xPos" => "center", "fontSize" => 10, "cols" => $cols_settings2, "lineCol" => array(0.8, 0.8, 0.8), "splitRows" => 1, "protectRows" => 0);
     $cols_settings["two"] = array("justification" => "right", "width" => 80);
     $pdf_table_options4 = array("showLines" => 2, "shaded" => 0, "width" => 400, "showHeadings" => 0, "fontSize" => 10, "xPos" => "center", "cols" => $cols_settings, "lineCol" => array(0.8, 0.8, 0.8));
     $pdf = new Cezpdf();
     $pdf->ezSetMargins(90, 90, 90, 90);
     $pdf->selectFont($font1);
     $pdf->ezStartPageNumbers(436, 80, 10, 'right', 'Page {PAGENUM} of {TOTALPAGENUM}');
     $pdf->ezStartPageNumbers(200, 80, 10, 'left', '<b>' . $default_id_label . ': </b>' . $this->get_value("invoiceNum"));
     $pdf->ezSetY(775);
     $companyName and $contact_info[] = array($companyName);
     $companyContactAddress and $contact_info[] = array($companyContactAddress);
     $companyContactAddress2 and $contact_info[] = array($companyContactAddress2);
     $companyContactAddress3 and $contact_info[] = array($companyContactAddress3);
     $companyContactEmail and $contact_info[] = array($companyContactEmail);
     $companyContactHomePage and $contact_info[] = array($companyContactHomePage);
     $phone and $contact_info[] = array($phone);
     $fax and $contact_info[] = array($fax);
     $pdf->selectFont($font2);
     $y = $pdf->ezTable($contact_info, false, "", $pdf_table_options);
     $pdf->selectFont($font1);
     $line_y = $y - 10;
     $pdf->setLineStyle(1, "round");
     $pdf->line(90, $line_y, 510, $line_y);
     $pdf->ezSetY(782);
     $image_jpg = ALLOC_LOGO;
     if (file_exists($image_jpg)) {
         $pdf->ezImage($image_jpg, 0, sprintf("%d", config::get_config_item("logoScaleX")), 'none');
         $y = 700;
     } else {
         $y = $pdf->ezText($companyName, 27, array("justification" => "right"));
     }
     $nos_y = $line_y + 22;
     $companyNos2 and $nos_y = $line_y + 34;
     $pdf->ezSetY($nos_y);
     $companyNos1 and $y = $pdf->ezText($companyNos1, 10, array("justification" => "right"));
     $companyNos2 and $y = $pdf->ezText($companyNos2, 10, array("justification" => "right"));
     $pdf->ezSetY($line_y - 20);
     $y = $pdf->ezText($default_header, 20, array("justification" => "center"));
     $pdf->ezSetY($y - 20);
     $ts_info[] = array("one" => "<b>" . $default_id_label . ":</b>", "two" => $this->get_value("invoiceNum"), "three" => "<b>Date Issued:</b>", "four" => date("d/m/Y"));
     $ts_info[] = array("one" => "<b>Client:</b>", "two" => $clientName, "three" => "<b>Billing Period:</b>", "four" => $period);
     $y = $pdf->ezTable($ts_info, $cols, "", $pdf_table_options2);
     $pdf->ezSetY($y - 20);
     list($rows, $info) = $this->get_invoiceItem_list_for_file($verbose);
     $cols2 = array("desc" => "Description", "quantity" => "Qty", "unit" => "Unit Price", "money" => "Charges", "gst" => $taxName);
     $taxPercent = config::get_config_item("taxPercent");
     if ($taxPercent === '') {
         unset($cols2["gst"]);
     }
     $rows[] = array("desc" => "<b>TOTAL</b>", "money" => $info["total"], "gst" => $info["total_gst"]);
     $y = $pdf->ezTable($rows, $cols2, "", $pdf_table_options3);
     $pdf->ezSetY($y - 20);
     if ($taxPercent !== '') {
         $totals[] = array("one" => "TOTAL " . $taxName, "two" => $info["total_gst"]);
     }
     $totals[] = array("one" => "TOTAL CHARGES", "two" => $info["total"]);
     $totals[] = array("one" => "<b>TOTAL AMOUNT PAYABLE</b>", "two" => "<b>" . $info["total_inc_gst"] . "</b>");
     $y = $pdf->ezTable($totals, $cols3, "", $pdf_table_options4);
     $pdf->ezSetY($y - 20);
     $pdf->ezText(str_replace(array("<br>", "<br/>", "<br />"), "\n", $footer), 10);
     // Add footer
     #$all = $pdf->openObject();
     #$pdf->saveState();
     #$pdf->addText(415,80,12,"<b>".$default_id_label.":</b>".$this->get_value("invoiceNum"));
     #$pdf->restoreState();
     #$pdf->closeObject();
     #$pdf->addObject($all,'all');
     if ($getfile) {
         return $pdf->ezOutput();
     } else {
         $pdf->ezStream(array("Content-Disposition" => "invoice_" . $this->get_id() . ".pdf"));
     }
 }
Beispiel #18
0
$bat_sendid = '';
$bat_recvid = '';
$bat_content = '';
$bat_gscount = 0;
$bat_stcount = 0;
$bat_time = time();
$bat_hhmm = date('Hi', $bat_time);
$bat_yymmdd = date('ymd', $bat_time);
$bat_yyyymmdd = date('Ymd', $bat_time);
// Minutes since 1/1/1970 00:00:00 GMT will be our interchange control number:
$bat_icn = sprintf('%09.0f', $bat_time / 60);
$bat_filename = date("Y-m-d-Hi", $bat_time) . "-batch.";
$bat_filename .= isset($_POST['bn_process_hcfa']) ? 'pdf' : 'txt';
if (isset($_POST['bn_process_hcfa'])) {
    $pdf = new Cezpdf('LETTER');
    $pdf->ezSetMargins(trim($_POST['top_margin']) + 0, 0, trim($_POST['left_margin']) + 0, 0);
    $pdf->selectFont($GLOBALS['fileroot'] . "/library/fonts/Courier.afm");
}
function append_claim(&$segs)
{
    global $bat_content, $bat_sendid, $bat_recvid, $bat_sender, $bat_stcount;
    global $bat_gscount, $bat_yymmdd, $bat_yyyymmdd, $bat_hhmm, $bat_icn;
    foreach ($segs as $seg) {
        if (!$seg) {
            continue;
        }
        $elems = explode('*', $seg);
        if ($elems[0] == 'ISA') {
            if (!$bat_content) {
                $bat_sendid = trim($elems[6]);
                $bat_recvid = trim($elems[8]);
    case "namen":
        // name zusammenfassen
        $name_join = array("abtitel", "abnamra", "abnamvor", "abamtbezkurz", "abad");
        //$cfg["db"]["sql"][2] = "SELECT !felder! FROM db_adrb INNER JOIN db_adrb_dienst ON abdienst_id=abdstposten INNER JOIN db_adrb_amtbez ON abamtbez_id=abamtbez WHERE abdststelle = \"". $HTTP_GET_VARS["adid"]."\" AND abanrede !=\"Raum\" ORDER BY abnamra";
        // alle sql befehle
        $cfg["db"]["sql"][1] = "SELECT adkate, adststelle, adtelver, adbnet, adcnet  FROM db_adrd WHERE adid =" . $HTTP_GET_VARS["adid"];
        $cfg["db"]["sql"][2] = "SELECT !felder! FROM db_adrb INNER JOIN db_adrb_dienst ON abdienst_id=abdstposten INNER JOIN db_adrb_amtbez ON abamtbez_id=abamtbez WHERE abdststelle =  " . $HTTP_GET_VARS["adid"] . " ORDER BY abnamra";
        #$cfg["db"]["sql"][3] = "SELECT !felder! FROM db_adrb WHERE abdststelle = \"". $HTTP_GET_VARS["adid"]."\" AND abanrede =\"Raum\" ORDER BY abnamra";
        #$cfg["db"]["sql"][3] = "SELECT !felder! FROM db_adrb WHERE abdststelle = '". $HTTP_GET_VARS["adid"]."' AND (abdstmobil != '+49-' AND abdstmobil != '') ORDER BY abnamra";
        // besondere nicht benötigte felder entfernen
        $kck_main = $kick;
        #$tab_left = array( "abtitel", "abnamra", "abnamvor", "abdstmobil");
        $pdfkopf = "telint";
        break;
        #        case "adrd":
        #            $cfg["sql"][1] = "";
        #            $cfg["sql"][2] = "";
        #            break;
}
include_once $pathvars["libraries"] . "xtra.pdf.php";
include_once $pathvars["libraries"] . "xtra.ezpdf.php";
$pdf = new Cezpdf();
$pdf->selectFont('./fonts/Helvetica.afm');
$pdf->openHere("Fit");
// seiten raender
#    $pdf->ezSetMargins(80,40,50,40); // top, bottom, left, right
$pdf->ezSetMargins(80, 90, 50, 40);
// top, bottom, left, right
// seiten nummern
$pdf->ezStartPageNumbers(330, 20, 12, '', 'Seite {PAGENUM} von {TOTALPAGENUM}', 1);
////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Beispiel #20
0
     }
     if (strstr($key, 'team50_')) {
         $parts = explode('_', $key);
         $tid = $parts[1];
         $teamList[] = $tid;
     }
 }
 $diplomaType = $_POST['diplomaType'];
 //echo("select * from tblSwimmer where id in (" . implode(',', $swimmerList) . ")");
 $rsSwimmers = $db->diplomaSwimmers($id, $swimmerList);
 $pdf = new Cezpdf();
 $pdf->selectFont('./fonts/Times-Roman');
 if ($diplomaType == 'HASI') {
     $logo = $pdf->openObject();
     $pdf->ezSetY(640);
     $pdf->ezSetMargins(0, 0, 200, 200);
     $pdf->ezImage('diploma/logo.jpg', 0, 195, 'none', 'left');
     $pdf->closeObject();
     $border = $pdf->openObject();
     $pdf->ezSetY(803.4);
     $pdf->ezSetMargins(0, 0, 23.8, 0);
     $pdf->ezImage('diploma/border.jpg', 0, 547.4, 'none', 'left');
     $pdf->closeObject();
     $pdf->ezSetMargins(0, 0, 30, 30);
     $firstPage = true;
     $swimmername = '';
     $clubname = '';
     $date = date('d-m-Y', strtotime($aryCompo['date']));
     $currentswimmer = -1;
     while ($swimmer = $db->fetch_array($rsSwimmers)) {
         if ($swimmer['sid'] != $currentswimmer) {
    c/o Werner Ammon
    Lerchenstr. 11c

    86343 Königsbrunn

    URL: http://www.chaos.de
*/
////////////////////////////////////////////////////////////////////////////////////////////////////////////////
if ($debugging["html_enable"]) {
    $debugging["ausgabe"] .= "[ ** " . $script["name"] . " ** ]" . $debugging["char"];
}
include_once $pathvars["libraries"] . "xtra.pdf.php";
include_once $pathvars["libraries"] . "xtra.ezpdf.php";
$pdf = new Cezpdf();
// seiten raender
$pdf->ezSetMargins(220, 180, 50, 40);
// top, bottom, left, right
$pdf->selectFont('./fonts/Helvetica.afm');
#$pdf->openHere("Fit");
// kunden
if (strstr($environment["ebene"], "kunden")) {
    $abstand = -60;
    $aheader = "<b>Ansprechpartner</b>";
    $art = "kunden";
    $anhang = "Firma";
    $pdfkopf = "Kunden";
    #$header_allgemein = "<b>Angaben zur ".$anhang."</b>";
    $ip_class = explode(".", $_SERVER["REMOTE_ADDR"]);
    $sql = "SELECT * FROM db_adrk WHERE akid = " . $environment["parameter"][1];
    $result = $db->query($sql);
    $data = $db->fetch_array($result, 1);
 /**
  * Crea un pdf con el estado de cuenta de el cliente especificado
  * @param Array $args,  $args['id_cliente'=>12[,'tipo_venta'=> 'credito | contado | saldo'] ], por default obtiene todas las compras del cliente
  */
 public static function imprimirEstadoCuentaCliente($args)
 {
     //verificamos que se haya especificado el id del cliente
     if (!isset($args['id_cliente'])) {
         Logger::log("Error al obtener el estado de cuenta, no se ha especificado un cliente.");
         die('{"success": false, "reason": "Error al obtener el estado de cuenta, no se ha especificado un cliente."}');
     }
     //verificamos que el cliente exista
     if (!($cliente = ClienteDAO::getByPK($args['id_cliente']))) {
         Logger::log("Error al obtener el estado de cuenta, no se tiene registro del cliente {$args['id_cliente']}.");
         die('{"success": false, "reason": "Error al obtener el estado de cuenta, no se tiene registro del cliente ' . $args['id_cliente'] . '"}');
     }
     //obtenemos los datos del emisor
     $estado_cuenta = estadoCuentaCliente($args);
     //buscar los datos del emisor
     if (!($emisor = PosConfigDAO::getByPK('emisor'))) {
         Logger::log("no encuentro los datos del emisor");
         die("no encuentro los datos del emisor");
     }
     $emisor = json_decode($emisor->getValue())->emisor;
     $sucursal = SucursalDAO::getByPK($_SESSION['sucursal']);
     if (!$sucursal) {
         die("Sucursal invalida");
     }
     include_once 'librerias/ezpdf/class.pdf.php';
     include_once 'librerias/ezpdf/class.ezpdf.php';
     $pdf = new Cezpdf();
     $pdf->selectFont('../server/librerias/ezpdf/fonts/Helvetica.afm');
     //margenes de un centimetro para toda la pagina
     $pdf->ezSetMargins(1, 1, 1, 1);
     /*
      * LOGO
      */
     if (!($logo = PosConfigDAO::getByPK('url_logo'))) {
         Logger::log("Verifique la configuracion del pos_config, no se encontro el camṕo 'url_logo'");
         die("Verifique la configuracion del POS, no se encontro el url del logo");
     }
     //addJpegFromFile(imgFileName,x,y,w,[h])
     //detectamos el tipo de imagen del logo
     if (substr($logo->getValue(), -3) == "jpg" || substr($logo->getValue(), -3) == "JPG" || substr($logo->getValue(), -4) == "jpeg" || substr($logo->getValue(), -4) == "JPEG") {
         $pdf->addJpegFromFile($logo->getValue(), puntos_cm(2), puntos_cm(25.5), puntos_cm(3.5));
     } elseif (substr($logo->getValue(), -3) == "png" || substr($logo->getValue(), -3) == "PNG") {
         $pdf->addPngFromFile($logo->getValue(), puntos_cm(2), puntos_cm(25.5), puntos_cm(3.5));
     } else {
         Logger::log("Verifique la configuracion del pos_config, la extension de la imagen del logo no es compatible");
         die("La extension de la imagen usada para el logo del negocio no es valida.");
     }
     /*     * ************************
      * ENCABEZADO
      * ************************* */
     $e = "<b>" . self::readableText($emisor->nombre) . "</b>\n";
     $e .= formatAddress($emisor);
     $e .= "RFC: " . $emisor->rfc . "\n\n";
     //datos de la sucursal
     $e .= "<b>Lugar de expedicion</b>\n";
     $e .= self::readableText($sucursal->getDescripcion()) . "\n";
     $e .= formatAddress($sucursal);
     $datos = array(array("emisor" => $e));
     $pdf->ezSetY(puntos_cm(28.6));
     $opciones_tabla = array();
     $opciones_tabla['showLines'] = 0;
     $opciones_tabla['showHeadings'] = 0;
     $opciones_tabla['shaded'] = 0;
     $opciones_tabla['fontSize'] = 8;
     $opciones_tabla['xOrientation'] = 'right';
     $opciones_tabla['xPos'] = puntos_cm(7.3);
     $opciones_tabla['width'] = puntos_cm(11);
     $opciones_tabla['textCol'] = array(0, 0, 0);
     $opciones_tabla['titleFontSize'] = 12;
     $opciones_tabla['rowGap'] = 3;
     $opciones_tabla['colGap'] = 3;
     $pdf->ezTable($datos, "", "", $opciones_tabla);
     $cajero = UsuarioDAO::getByPK($_SESSION['userid'])->getNombre();
     $datos = array(array("col" => "<b>Cajero</b>"), array("col" => self::readableText($cajero)), array("col" => "<b>Cliente</b>"), array("col" => self::readableText($cliente->getRazonSocial())), array("col" => "<b>Limite de  Credito</b>"), array("col" => FormatMoney($estado_cuenta->limite_credito, DONT_USE_HTML)), array("col" => "<b>Saldo</b>"), array("col" => FormatMoney($estado_cuenta->saldo, DONT_USE_HTML)));
     $pdf->ezSetY(puntos_cm(28.8));
     $opciones_tabla['xPos'] = puntos_cm(12.2);
     $opciones_tabla['width'] = puntos_cm(6);
     $opciones_tabla['showLines'] = 0;
     $opciones_tabla['shaded'] = 2;
     $opciones_tabla['shadeCol'] = array(1, 1, 1);
     //$opciones_tabla['shadeCol2'] = array(0.054901961, 0.756862745, 0.196078431);
     $opciones_tabla['shadeCol2'] = array(0.8984375, 0.95703125, 0.99609375);
     $pdf->ezTable($datos, "", "", $opciones_tabla);
     //roundRect($pdf, puntos_cm(12.2), puntos_cm(28.8), puntos_cm(6), puntos_cm(4.25));
     /**
      * ESTADO DE CUENTA
      */
     $elementos = array(array('id_venta' => 'Venta', 'fecha' => 'Fecha', 'sucursal' => 'Sucursal', 'cajero' => 'Cajero', 'tipo_venta' => 'Tipo', 'tipo_pago' => 'Pago', 'total' => 'Total', 'pagado' => 'Pagado', 'saldo' => 'Saldo'));
     foreach ($estado_cuenta->array_ventas as $venta) {
         $array_venta = array();
         $array_venta['id_venta'] = $venta['id_venta'];
         $array_venta['fecha'] = $venta['fecha'];
         $array_venta['sucursal'] = self::readableText($venta['sucursal']);
         $array_venta['cajero'] = self::readableText($venta['cajero']);
         $array_venta['cancelada'] = self::readableText($venta['cancelada']);
         $array_venta['tipo_venta'] = self::readableText($venta['tipo_venta']);
         $array_venta['tipo_pago'] = self::readableText($venta['tipo_pago']);
         $array_venta['total'] = FormatMoney($venta['total'], DONT_USE_HTML);
         $array_venta['pagado'] = FormatMoney($venta['pagado'], DONT_USE_HTML);
         $array_venta['saldo'] = FormatMoney($venta['saldo'], DONT_USE_HTML);
         array_push($elementos, $array_venta);
     }
     $pdf->ezText("", 8, array('justification' => 'center'));
     $pdf->ezSetY(puntos_cm(24));
     $opciones_tabla['xPos'] = puntos_cm(2);
     $opciones_tabla['width'] = puntos_cm(16.2);
     $pdf->ezTable($elementos, "", "Estado de Cuenta", $opciones_tabla);
     //roundRect($pdf, puntos_cm(2), puntos_cm(24.3), puntos_cm(16.2), puntos_cm(3.2));
     /*     * ************************
      * notas de abajo
      * ************************* */
     $pdf->setLineStyle(1);
     $pdf->setStrokeColor(0.3359375, 0.578125, 0.89453125);
     $pdf->line(puntos_cm(2), puntos_cm(1.3), puntos_cm(18.2), puntos_cm(1.3));
     $pdf->addText(puntos_cm(2), puntos_cm(1.0), 7, "Fecha de impresion: " . date("d/m/y") . " " . date("H:i:s"));
     //addJpegFromFile(imgFileName,x,y,w,[h])
     //$pdf->addJpegFromFile("../www/media/logo_simbolo.jpg", puntos_cm(15.9), puntos_cm(.25), 25);
     $pdf->addText(puntos_cm(16.7), puntos_cm(0.6), 8, "caffeina.mx");
     $pdf->ezStream();
 }
Beispiel #23
0
function citeRecords($result, $rowsFound, $query, $queryURL, $showQuery, $showLinks, $rowOffset, $showRows, $previousOffset, $nextOffset, $wrapResults, $citeStyle, $citeOrder, $citeType, $orderBy, $headerMsg, $userID, $viewType)
{
    global $officialDatabaseName;
    // these variables are defined in 'ini.inc.php'
    global $databaseBaseURL;
    global $contentTypeCharset;
    global $pdfPageSize;
    global $client;
    // The array '$transtab_refbase_pdf' contains search & replace patterns for conversion from refbase markup to PDf markup & entities
    global $transtab_refbase_pdf;
    // defined in 'transtab_refbase_pdf.inc.php'
    // Initialize array variables:
    $yearsArray = array();
    $typeTitlesArray = array();
    // Define inline text markup to be used by the 'citeRecord()' function:
    $markupPatternsArray = array("bold-prefix" => "<b>", "bold-suffix" => "</b>", "italic-prefix" => "<i>", "italic-suffix" => "</i>", "underline-prefix" => "<u>", "underline-suffix" => "</u>", "endash" => "¦", "emdash" => "©", "ampersand" => "&", "double-quote" => '"', "double-quote-left" => "ª", "double-quote-right" => "¬", "single-quote" => "'", "single-quote-left" => "®", "single-quote-right" => "¶", "less-than" => "<", "greater-than" => ">", "newline" => "\n");
    // Defines search & replace 'actions' that will be applied upon PDF output to all those refbase fields that are listed
    // in the corresponding 'fields' element:
    $pdfSearchReplaceActionsArray = array(array('fields' => array("title", "publication", "abbrev_journal", "address", "keywords", "abstract", "orig_title", "series_title", "abbrev_series_title", "notes"), 'actions' => $transtab_refbase_pdf));
    // For CLI queries, we'll allow paging thru the result set, i.e. we honour the values of the CLI options '-S|--start' ('$rowOffset')
    // and '-R|--rows' ('$showRows') ('$rowOffset' and '$showRows' are re-assigned in function 'seekInMySQLResultsToOffset()' in 'include.inc.php')
    if (preg_match("/^cli/i", $client)) {
        // if the query originated from a command line client such as the "refbase" CLI client ("cli-refbase-1.0")
        $showMaxRows = $showRows;
    } else {
        $showMaxRows = $rowsFound;
    }
    // otherwise show all rows
    // Setup the basic PDF document structure (PDF functions defined in 'class.ezpdf.php'):
    $pdf = new Cezpdf($pdfPageSize, 'portrait');
    // initialize PDF object
    if (!empty($headerMsg)) {
        // adjust upper page margin if a custom header message was given
        $pageMarginTop = "70";
    } else {
        $pageMarginTop = "50";
    }
    $pdf->ezSetMargins($pageMarginTop, 70, 50, 50);
    // set document margins (top, bottom, left, right)
    // Set fonts:
    $headingFont = 'includes/classes/org/pdf-php/fonts/Helvetica.afm';
    $textBodyFont = 'includes/classes/org/pdf-php/fonts/Times-Roman.afm';
    // Re-map character numbers from the 0->255 range to a named character, i.e. replace an (unused) character for any other PostScript char;
    // see the PDF reference for a list of supported PostScript/PDF character names: <http://www.adobe.com/devnet/pdf/pdf_reference.html>;
    // for the decimal code numbers of the ISO-8859-1 character set, see e.g.: <http://www.ramsch.org/martin/uni/fmi-hp/iso8859-1.html>
    $diff = array(166 => 'endash', 169 => 'emdash', 170 => 'quotedblleft', 172 => 'quotedblright', 174 => 'quoteleft', 182 => 'quoteright');
    // Select a font:
    $pdf->selectFont($textBodyFont, array('encoding' => 'WinAnsiEncoding', 'differences' => $diff));
    $pdf->openHere('Fit');
    // Put a footer (and optionally a header) on all the pages:
    $all = $pdf->openObject();
    // start an independent object; all further writes to a page will actually go into this object, until a 'closeObject()' call is made
    $pdf->saveState();
    $pdf->setStrokeColor(0, 0, 0, 1);
    // set line color
    $pdf->setLineStyle(0.5);
    // set line width
    // - print header line and header message at the specified x/y position:
    if (!empty($headerMsg)) {
        // Remove any colon (":") from end of header message:
        $headerMsg = trimTextPattern($headerMsg, ":", false, true);
        // function 'trimTextPattern()' is defined in 'include.inc.php'
        // Decode any HTML entities:
        // (these may occur in the header message e.g. if the user's preferred display language is not English but German or French, etc)
        $headerMsg = decodeHTML($contentTypeCharset, $headerMsg);
        // function 'decodeHTML()' is defined in 'include.inc.php', and '$contentTypeCharset' is defined in 'ini.inc.php'
        // Convert refbase markup in the header message into appropriate PDF markup & entities:
        $headerMsg = searchReplaceText($transtab_refbase_pdf, $headerMsg, true);
        // function 'searchReplaceText()' is defined in 'include.inc.php'
        if ($pdfPageSize == 'a4') {
            $pdf->line(20, 800, 575, 800);
            $pdf->addText(50, 805, 10, $headerMsg);
        } elseif ($pdfPageSize == 'letter') {
            $pdf->line(20, 750, 592, 750);
            $pdf->addText(50, 755, 10, $headerMsg);
        }
    }
    // - print footer line and footer text at the specified x/y position:
    if ($pdfPageSize == 'a4') {
        $pdf->line(20, 40, 575, 40);
        $pdf->addText(50, 28, 10, $officialDatabaseName . ' ¦ ' . $databaseBaseURL);
        // w.r.t. the endash, see notes at '$markupPatternsArray' and '$diff' above
    } elseif ($pdfPageSize == 'letter') {
        $pdf->line(20, 40, 592, 40);
        $pdf->addText(50, 28, 10, $officialDatabaseName . ' ¦ ' . $databaseBaseURL);
    }
    $pdf->restoreState();
    $pdf->closeObject();
    // close the currently open object; further writes will now go to the current page
    $pdf->addObject($all, 'all');
    // note that object can be told to appear on just odd or even pages by changing 'all' to 'odd' or 'even'
    // Start printing page numbers:
    if ($pdfPageSize == 'a4') {
        $pdf->ezStartPageNumbers(550, 28, 10, '', '', 1);
    } elseif ($pdfPageSize == 'letter') {
        $pdf->ezStartPageNumbers(567, 28, 10, '', '', 1);
    }
    // LOOP OVER EACH RECORD:
    // Fetch one page of results (or less if on the last page)
    // (i.e., upto the limit specified in $showMaxRows) fetch a row into the $row array and ...
    for ($rowCounter = 0; $rowCounter < $showMaxRows && ($row = @mysql_fetch_array($result)); $rowCounter++) {
        foreach ($row as $rowFieldName => $rowFieldValue) {
            // Apply search & replace 'actions' to all fields that are listed in the 'fields' element of the arrays contained in '$pdfSearchReplaceActionsArray':
            foreach ($pdfSearchReplaceActionsArray as $fieldActionsArray) {
                if (in_array($rowFieldName, $fieldActionsArray['fields'])) {
                    $row[$rowFieldName] = searchReplaceText($fieldActionsArray['actions'], $row[$rowFieldName], true);
                }
            }
        }
        // function 'searchReplaceText()' is defined in 'include.inc.php'
        // Order attributes according to the chosen output style & record type:
        $record = citeRecord($row, $citeStyle, $citeType, $markupPatternsArray, false);
        // function 'citeRecord()' is defined in the citation style file given in '$citeStyleFile' (which, in turn, must reside in the 'cite' directory of the refbase root directory), see function 'generateCitations()'
        // Print out the current record:
        if (!empty($record)) {
            // Print any section heading(s):
            if (preg_match("/year|type/i", $citeOrder)) {
                $headingPrefix = "";
                $headingSuffix = "";
                $sectionMarkupPrefix = "<b>";
                $sectionMarkupSuffix = "</b>\n";
                $subSectionMarkupPrefix = "";
                $subSectionMarkupSuffix = "\n";
                if ($citeOrder == "type-year") {
                    $sectionMarkupSuffix .= "\n";
                }
                list($yearsArray, $typeTitlesArray, $sectionHeading) = generateSectionHeading($yearsArray, $typeTitlesArray, $row, $citeOrder, $headingPrefix, $headingSuffix, $sectionMarkupPrefix, $sectionMarkupSuffix, $subSectionMarkupPrefix, $subSectionMarkupSuffix);
                // function 'generateSectionHeading()' is defined in 'cite.inc.php'
                if (!empty($sectionHeading)) {
                    $pdf->selectFont($headingFont, array('encoding' => 'WinAnsiEncoding', 'differences' => $diff));
                    // use Helvetica
                    $pdf->ezText($sectionHeading, '14', array('justification' => 'left'));
                    // create heading using a font size of 14pt
                }
            }
            // If character encoding is not UTF-8 already, convert record text to UTF-8:
            //				if ($contentTypeCharset != "UTF-8")
            //					$record = convertToCharacterEncoding("UTF-8", "IGNORE", $record); // function 'convertToCharacterEncoding()' is defined in 'include.inc.php'
            // NOTE: Export of cited references to PDF does currently only work with a latin1 database but not with UTF-8 (since I don't know how to write Unicode characters to PDF).
            //       As a workaround, we could convert UTF-8 characters to latin1 if possible (and omit any other higher ASCII chars)
            // TODO: While this workaround indeed fixes display issues with higher ASCII chars that have equivalents in the latin1 charset, this will currently swallow higher ASCII
            //       hyphens/dashes such as endashes (which display correctly without this workaround).
            //				if ($contentTypeCharset == "UTF-8")
            //					$record = convertToCharacterEncoding("ISO-8859-1", "TRANSLIT", $record, "UTF-8"); // function 'convertToCharacterEncoding()' is defined in 'include.inc.php'
            // Set paragraph text options:
            $textOptions = array('justification' => 'full');
            // possible array options:
            // 'left'=> number, gap to leave from the left margin
            // 'right'=> number, gap to leave from the right margin
            // 'aleft'=> number, absolute left position (overrides 'left')
            // 'aright'=> number, absolute right position (overrides 'right')
            // 'justification' => 'left','right','center','centre','full'
            //
            // only set one of the next two items (leading overrides spacing)
            // 'leading' => number, defines the total height taken by the line, independent of the font height.
            // 'spacing' => a real number, though usually set to one of 1, 1.5, 2 (line spacing as used in word processing)
            // Write PDF paragraph:
            $pdf->selectFont($textBodyFont, array('encoding' => 'WinAnsiEncoding'));
            // use Times-Roman
            $pdf->ezText($record . "\n", '12', $textOptions);
            // create text block with record text using "Times Roman" and a font size of 12pt
        }
    }
    return $pdf->ezStream();
}
Beispiel #24
0
function upload_file_to_client_pdf($file_to_send)
{
    //Function reads a HTML file and converts to pdf.
    global $STMT_TEMP_FILE_PDF;
    global $srcdir;
    if ($GLOBALS['statement_appearance'] == '1') {
        require_once "{$srcdir}/html2pdf/vendor/autoload.php";
        $pdf2 = new HTML2PDF($GLOBALS['pdf_layout'], $GLOBALS['pdf_size'], $GLOBALS['pdf_language'], true, 'UTF-8', array($GLOBALS['pdf_left_margin'], $GLOBALS['pdf_top_margin'], $GLOBALS['pdf_right_margin'], $GLOBALS['pdf_bottom_margin']), $_SESSION['language_direction'] == 'rtl' ? true : false);
        ob_start();
        echo readfile($file_to_send, "r");
        //this file contains the HTML to be converted to pdf.
        //echo $file;
        $content = ob_get_clean();
        // Fix a nasty html2pdf bug - it ignores document root!
        global $web_root, $webserver_root;
        $i = 0;
        $wrlen = strlen($web_root);
        $wsrlen = strlen($webserver_root);
        while (true) {
            $i = stripos($content, " src='/", $i + 1);
            if ($i === false) {
                break;
            }
            if (substr($content, $i + 6, $wrlen) === $web_root && substr($content, $i + 6, $wsrlen) !== $webserver_root) {
                $content = substr($content, 0, $i + 6) . $webserver_root . substr($content, $i + 6 + $wrlen);
            }
        }
        $pdf2->WriteHTML($content);
        $temp_filename = $STMT_TEMP_FILE_PDF;
        $content_pdf = $pdf2->Output($STMT_TEMP_FILE_PDF, 'F');
    } else {
        $pdf = new Cezpdf('LETTER');
        //pdf creation starts
        $pdf->ezSetMargins(45, 9, 36, 10);
        $pdf->selectFont('Courier');
        $pdf->ezSetY($pdf->ez['pageHeight'] - $pdf->ez['topMargin']);
        $countline = 1;
        $file = fopen($file_to_send, "r");
        //this file contains the text to be converted to pdf.
        while (!feof($file)) {
            $OneLine = fgets($file);
            //one line is read
            if (stristr($OneLine, "\f") == true && !feof($file)) {
                $pdf->ezNewPage();
                $pdf->ezSetY($pdf->ez['pageHeight'] - $pdf->ez['topMargin']);
                str_replace("\f", "", $OneLine);
            }
            if (stristr($OneLine, 'REMIT TO') == true || stristr($OneLine, 'Visit Date') == true || stristr($OneLine, 'Future Appointments') == true || stristr($OneLine, 'Current') == true) {
                //lines are made bold when 'REMIT TO' or 'Visit Date' is there.
                $pdf->ezText('<b>' . $OneLine . '</b>', 12, array('justification' => 'left', 'leading' => 6));
            } else {
                $pdf->ezText($OneLine, 12, array('justification' => 'left', 'leading' => 6));
            }
            $countline++;
        }
        $fh = @fopen($STMT_TEMP_FILE_PDF, 'w');
        //stored to a pdf file
        if ($fh) {
            fwrite($fh, $pdf->ezOutput());
            fclose($fh);
        }
    }
    header("Pragma: public");
    //this section outputs the pdf file to browser
    header("Expires: 0");
    header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
    header("Content-Type: application/force-download");
    header("Content-Length: " . filesize($STMT_TEMP_FILE_PDF));
    header("Content-Disposition: attachment; filename=" . basename($STMT_TEMP_FILE_PDF));
    header("Content-Description: File Transfer");
    readfile($STMT_TEMP_FILE_PDF);
    // flush the content to the browser. If you don't do this, the text from the subsequent
    // output from this script will be in the file instead of sent to the browser.
    flush();
    exit;
    //added to exit from process properly in order to stop bad html code -ehrlive
    // sleep one second to ensure there's no follow-on.
    sleep(1);
}
    print "<ul>";
    for ($a = 0; $a < $numRecords / $recordsPerPage; $a++) {
        $startRecord = 1 + $a * $recordsPerPage;
        if ($numRecords > $startRecord + $recordsPerPage) {
            $endRecord = $startRecord + $recordsPerPage - 1;
        } else {
            $endRecord = $numRecords - 1;
        }
        print "<li><a href=\"create_badge.php?USERS_PK[]=all&numRecords={$numRecords}&pageNumber={$a}\">PDF file for records {$startRecord}-{$endRecord}</a></li>";
    }
    print "</ul>";
    print "</div>";
} else {
    // this is the closest predefined page size matching the labels
    $pdf = new Cezpdf('LETTER', 'portrait');
    $pdf->ezSetMargins($top_margin, $bottom_margin, $left_margin, $right_margin);
    $pdf->selectFont('../../accounts/include/fonts/Helvetica.afm');
    $pdf->setFontFamily('b');
    $pdf->addInfo("Creator", "Sakai Conference Badge Generator");
    $pdf->addInfo("Author", "Educational Technologies at Virginia Tech");
    $pdf->addInfo("Title", "Sakai Conference Badges");
    $pdf->addInfo("CreationDate", localtime());
    $pageCount = 0;
    $offsetRow = 2;
    foreach ($people as $person) {
        if ($pageCount > 0 && $offsetRow == 2) {
            $pdf->ezNewPage();
        }
        for ($columnOffset = 0; $columnOffset <= 1; $columnOffset++) {
            $left_edge = $left_margin + $badge_width * $columnOffset + $margin;
            $right_edge = $left_edge + $badge_width - $margin * 2;
Beispiel #26
0
 $scorecourse = $category[0]->calc_score($user_id);
 $scorecourse_display = isset($scorecourse) ? $scoredisplay->display_score($scorecourse, SCORE_AVERAGE) : get_lang('NoResultsAvailable');
 $cattotal = Category::load(0);
 $scoretotal = $cattotal[0]->calc_score($user_id);
 $scoretotal_display = isset($scoretotal) ? $scoredisplay->display_score($scoretotal, SCORE_PERCENT) : get_lang('NoResultsAvailable');
 //prepare all necessary variables:
 $organization_name = api_get_setting('Institution');
 $portal_name = api_get_setting('siteName');
 $stud_fn = $user['firstname'];
 $stud_ln = $user['lastname'];
 $certif_text = sprintf(get_lang('CertificateWCertifiesStudentXFinishedCourseYWithGradeZ'), $organization_name, $stud_fn . ' ' . $stud_ln, $category[0]->get_name(), $scorecourse_display);
 $certif_text = str_replace("\\n", "\n", $certif_text);
 $date = api_convert_and_format_date(null, DATE_FORMAT_SHORT);
 $pdf = new Cezpdf('a4', 'landscape');
 $pdf->selectFont(api_get_path(LIBRARY_PATH) . 'ezpdf/fonts/Courier.afm');
 $pdf->ezSetMargins(30, 30, 50, 50);
 //line Y coordinates in landscape mode are upside down (500 is on top, 10 is on the bottom)
 $pdf->line(50, 50, 790, 50);
 $pdf->line(50, 550, 790, 550);
 $pdf->ezSetY(450);
 //@todo replace image
 //$pdf->ezImage(api_get_path(SYS_CODE_PATH).'img/dokeos_logo_certif.png',1,400,'','center','');
 $pdf->ezSetY(480);
 $pdf->ezText($certif_text, 28, array('justification' => 'center'));
 //$pdf->ezSetY(750);
 $pdf->ezSetY(50);
 $pdf->ezText($date, 18, array('justification' => 'center'));
 $pdf->ezSetY(580);
 $pdf->ezText($organization_name, 22, array('justification' => 'left'));
 $pdf->ezSetY(580);
 $pdf->ezText($portal_name, 22, array('justification' => 'right'));
function creaPDF($colname_factura, $tmpName)
{
    global $database_f4, $f4, $interface, $setsProlec, $url_dir;
    $FWK_PDFFONTS = 'pdf/fonts/';
    $FWK_PDFDEFAULTFONT = '/face5/' . $url_dir . '/f4/extensiones/pdf/fonts/Helvetica.afm';
    $FWK_PDFCOURIERFONT = 'pdf/fonts/Courier.afm';
    // Obtener factura y sus anexos
    $TIPOSCOMPROBANTEMXP = array(1 => "Factura", 3 => "Nota de Cr.", 2 => "NOTA DE DEBITO");
    mysql_select_db($database_f4, $f4);
    $query_factura = sprintf("SELECT  facturas.idfactura,  facturas.idempresa,  facturas.idsello,\n\tfacturas.serie, facturas.folio, archivo,\n\tdate_format( facturas.timestampemision, '%%d/%%m/%%Y %%T') as timestampemision,\n\tfacturas.noaprob, facturas.rfccliente, facturas.estatus, facturas.sello, facturas.cadena, facturas.factura,\n\tfacturas.idif, facturas.tipocfd, empresa.bu\n\tFROM facturas inner join empresa on (facturas.idempresa=empresa.idempresa)\n\tWHERE facturas.idfactura = %s", $colname_factura);
    $factura = mysql_query($query_factura, $f4);
    $row_factura = mysql_fetch_assoc($factura);
    $totalRows_factura = mysql_num_rows($factura);
    print_r($row_factura);
    mysql_select_db($database_f4, $f4);
    $query_partida = sprintf("SELECT * FROM face_partidas WHERE face_factura_idface_factura = %s ORDER BY numero ASC", $row_factura['idif']);
    $partidas = mysql_query($query_partida, $f4);
    $partidasArray = array();
    while ($partRow = mysql_fetch_assoc($partidas)) {
        array_push($partidasArray, $partRow);
    }
    $dom = new DOMDocument();
    $dom->loadXML(base64_decode($row_factura['factura']));
    $NS = "http://www.sat.gob.mx/cfd/2";
    $NSP = "";
    $xp = new DOMXPath($dom);
    $nsElems = $dom->getElementsByTagNameNS($NS, 'Comprobante');
    if ($nsElems->item(0) != null) {
        $xp->registerNamespace("C", "http://www.sat.gob.mx/cfd/2");
        $NSP = "C:";
    }
    $comprobanteNode = null;
    $elements = $xp->query("/" . $NSP . "Comprobante");
    foreach ($elements as $comprobanteNode) {
    }
    $emisorNode = null;
    $elements = $xp->query("/" . $NSP . "Comprobante/" . $NSP . "Emisor");
    foreach ($elements as $emisorNode) {
    }
    $emisordomicilioNode = null;
    $elements = $xp->query("/" . $NSP . "Comprobante/" . $NSP . "Emisor/" . $NSP . "DomicilioFiscal");
    foreach ($elements as $emisordomicilioNode) {
    }
    $expedidoNode = null;
    $elements = $xp->query("/" . $NSP . "Comprobante/" . $NSP . "Emisor/" . $NSP . "ExpedidoEn");
    foreach ($elements as $expedidoNode) {
    }
    $receptorNode = null;
    $elements = $xp->query("/" . $NSP . "Comprobante/" . $NSP . "Receptor");
    foreach ($elements as $receptorNode) {
    }
    $receptordomicilioNode = null;
    $elements = $xp->query("/" . $NSP . "Comprobante/" . $NSP . "Receptor/" . $NSP . "Domicilio");
    foreach ($elements as $receptordomicilioNode) {
    }
    $conceptoNode = null;
    $conceptos = $xp->query("/" . $NSP . "Comprobante/" . $NSP . "Conceptos/" . $NSP . "Concepto");
    $impuestosNode = null;
    $elements = $xp->query("/" . $NSP . "Comprobante/" . $NSP . "Impuestos");
    foreach ($elements as $impuestosNode) {
    }
    $trasladoNode = null;
    $traslados = $xp->query("/" . $NSP . "Comprobante/" . $NSP . "Impuestos/" . $NSP . "Traslados/" . $NSP . "Traslado");
    $retencionNode = null;
    $retenciones = $xp->query("/" . $NSP . "Comprobante/" . $NSP . "Impuestos/" . $NSP . "Retenciones/" . $NSP . "Retencion");
    mysql_select_db($database_f4, $f4);
    $query_empresa = sprintf("SELECT * FROM empresa WHERE idempresa = %s", $row_factura['idempresa']);
    $empresa = mysql_query($query_empresa, $f4);
    $row_empresa = mysql_fetch_assoc($empresa);
    mysql_select_db($database_f4, $f4);
    $query_sello = sprintf("SELECT * FROM sellos WHERE idsello = %s", $row_factura['idsello']);
    $sello = mysql_query($query_sello, $f4);
    $row_sello = mysql_fetch_assoc($sello);
    mysql_select_db($database_f4, $f4);
    $query_sucursal = "SELECT * FROM sucursales WHERE sucursal = '" . $row_sello['sucursal'] . "'";
    $sucursal = mysql_query($query_sucursal, $f4);
    $row_sucursal = mysql_fetch_assoc($sucursal);
    $totalRows_sucursal = mysql_num_rows($sucursal);
    //descuentos
    $desc1 = 0.0;
    $desc2 = 0.0;
    //==================================================================================================================
    // Crea el documento pdf
    $pdf = new Cezpdf('LETTER', 'portrait');
    //'LETTER' (612.00,792.00)
    $pdf->ezSetMargins(100, 30, 30, 30);
    //$pdf->selectFont($FWK_PDFDEFAULTFONT);
    $pdf->setLineStyle(0.7, '', '', '', 0);
    $pdf->openHere('Fit');
    if ($row_factura['tipocfd'] == 3) {
        $pdf->setStrokeColor(255, 0, 0);
    }
    if ($row_factura['tipocfd'] == 2) {
        $pdf->setStrokeColor(0, 255, 0);
    }
    // Inicia numeracin de páginas.
    $pdf->ezStartPageNumbers(400, 50, 10, 'left', '{PAGENUM} of {TOTALPAGENUM}', 1);
    $pagina = 1;
    $primeraPagina = $pdf->currentPage;
    // i. Agrega el logo de la empresa
    $logofile = "logos/prueba_logo.jpg";
    //TENDRA QUE VENIR DE UN PARAMETRO EN LA BD.
    $pdf->addJpegFromFile($logofile, 30, 655, 200);
    // i. Agrega la leyenda "cancelada"
    if ($row_factura['estatus'] == 0) {
        $pdf->setColor(0.9, 0.9, 0.9);
        $pdf->addText(180, 200, 65, "<b>CANCELADA</b>", -45);
        $pdf->setColor(0, 0, 0);
    }
    // ------------------------------------------ENCABEZADO ------------------------------------------
    //ENCABEZADO DE LA FACTURA
    $tipoDocto = $TIPOSCOMPROBANTEMXP[$row_factura['tipocfd']];
    $emisor = utf8_decode($emisorNode->getAttribute('rfc')) . "\n";
    $emisor .= utf8_decode($emisordomicilioNode->getAttribute('calle') . " " . $emisordomicilioNode->getAttribute('noExterior') . " " . $emisordomicilioNode->getAttribute('noInterior')) . "\n";
    $emisor .= utf8_decode($emisordomicilioNode->getAttribute('colonia'));
    if ($emisordomicilioNode->getAttribute('localidad') != "") {
        $emisor .= "\n" . utf8_decode($emisordomicilioNode->getAttribute('localidad'));
    }
    if ($emisordomicilioNode->getAttribute('municipio') != "") {
        $emisor .= "\n" . utf8_decode($emisordomicilioNode->getAttribute('municipio'));
    }
    if ($emisordomicilioNode->getAttribute('estado') != "") {
        $emisor .= ", " . utf8_decode($emisordomicilioNode->getAttribute('estado'));
    }
    if ($emisordomicilioNode->getAttribute('codigoPostal') != "") {
        $emisor .= "\nCP " . utf8_decode($emisordomicilioNode->getAttribute('codigoPostal'));
    }
    $emisor .= " " . utf8_decode($emisordomicilioNode->getAttribute('pais'));
    $sucursal = "";
    if ($row_sucursal['sucursal'] != "Principal_") {
        $sucursal = "Sucursal " . utf8_decode($row_sucursal['sucursal']) . "\n";
        $sucursal .= utf8_decode($expedidoNode->getAttribute('calle') . " " . $expedidoNode->getAttribute('noExterior') . " " . $expedidoNode->getAttribute('noInterior')) . "\n";
        $sucursal .= utf8_decode($expedidoNode->getAttribute('colonia')) . "\n";
        $sucursal .= utf8_decode($expedidoNode->getAttribute('municipio')) . ", " . utf8_decode($expedidoNode->getAttribute('estado')) . "\n";
        $sucursal .= "CP " . utf8_decode($expedidoNode->getAttribute('codigoPostal')) . " " . utf8_decode($expedidoNode->getAttribute('pais'));
    }
    ////////// i. Nombre del emisor
    $tableData = array(array("dato" => "<b>Obintel S.A. de C.V.</b>"));
    $colOptions = array("dato" => array('justification' => 'left', 'width' => 200));
    $options = array('showLines' => 0, 'showHeadings' => 0, 'shaded' => 0, 'shadeCol' => array(1, 1, 1), 'fontSize' => 9, 'textCol' => array(0, 0, 0), 'rowGap' => 0, 'colGap' => 0, 'xPos' => 240, 'xOrientation' => 'right', 'width' => 200, 'cols' => $colOptions, 'innerLineThickness' => 0.3, 'outerLineThickness' => 0.3);
    // Dibuja la tabla nombre del emisor
    $pdf->ezSetY(714);
    $pdf->ezTable($tableData, $colNames, "", $options);
    ////////// i. Datos del emisor y de la sucursal
    $tableData = array(array("emisor" => $emisor, "espacio" => "", "sucursal" => $sucursal));
    $colOptions = array("emisor" => array('justification' => 'left', 'width' => 205), "espacio" => array('justification' => 'left', 'width' => 10), "sucursal" => array('justification' => 'left', 'width' => 120));
    $options = array('showLines' => 0, 'showHeadings' => 0, 'shaded' => 0, 'shadeCol' => array(1, 1, 1), 'fontSize' => 7, 'textCol' => array(0, 0, 0), 'rowGap' => 0, 'colGap' => 0, 'xPos' => 240, 'xOrientation' => 'right', 'width' => 335, 'cols' => $colOptions, 'innerLineThickness' => 0.3, 'outerLineThickness' => 0.3);
    // Dibuja la tabla
    $pdf->ezSetDy(-6);
    $pdf->ezTable($tableData, "", "", $options);
    ////////// i. Datos del documento
    $foliodocto = rellena("0", 6, $comprobanteNode->getAttribute('folio'));
    $seriedocto = $comprobanteNode->getAttribute('serie');
    if (!empty($seriedocto)) {
        $foliodocto = $seriedocto . "-" . rellena("0", 6, $comprobanteNode->getAttribute('folio'));
    }
    $fechastr = $comprobanteNode->getAttribute('fecha');
    $fechatok = explode("T", $fechastr);
    $toksf = explode("-", $fechatok[0]);
    $fechastr = $toksf[2] . "-" . $toksf[1] . "-" . $toksf[0] . " " . $fechatok[1];
    $ncert = $comprobanteNode->getAttribute('noCertificado');
    $aprob = $comprobanteNode->getAttribute('anoAprobacion') . "-" . $comprobanteNode->getAttribute('noAprobacion');
    $tableData = array(array("dato" => "<b>" . $tipoDocto . "</b>"), array("dato" => "<b>" . $foliodocto . "</b>"), array("dato" => "Fecha"), array("dato" => $fechastr), array("dato" => "Certificado"), array("dato" => $ncert), array("dato" => "Año y No. Aprobación"), array("dato" => $aprob));
    $colOptions = array("dato" => array('justification' => 'left', 'width' => 120));
    $options = array('showLines' => 1, 'showHeadings' => 0, 'shaded' => 2, 'shadeCol' => array(1, 1, 1), 'shadeCol2' => array(0.9, 0.9, 0.9), 'fontSize' => 7, 'textCol' => array(1, 1, 1), 'rowGap' => 2, 'colGap' => 5, 'xPos' => 455, 'xOrientation' => 'right', 'width' => 120, 'cols' => $colOptions, 'innerLineThickness' => 0.3, 'outerLineThickness' => 0.3);
    // Dibuja la tabla datos del documento
    //$pdf->ezSetDy(-12);
    $pdf->ezTable($tableData, "", "", $options);
    ////////// i. Datos del cliente
    $tableData = array(array("dato" => "<b>Cliente</b>"), array("dato" => utf8_decode($receptorNode->getAttribute('nombre'))), array("dato" => utf8_decode($receptorNode->getAttribute('rfc'))), array("dato" => utf8_decode($receptordomicilioNode->getAttribute('calle')) . " " . utf8_decode($receptordomicilioNode->getAttribute('noExterior')) . " " . utf8_decode($receptordomicilioNode->getAttribute('noInterior')) . " " . utf8_decode($receptordomicilioNode->getAttribute('colonia'))), array("dato" => utf8_decode($receptordomicilioNode->getAttribute('municipio')) . ", " . utf8_decode($receptordomicilioNode->getAttribute('estado'))), array("dato" => utf8_decode($receptordomicilioNode->getAttribute('estado'))), array("dato" => utf8_decode($receptordomicilioNode->getAttribute('codigoPostal'))));
    $colOptions = array("dato" => array('justification' => 'left', 'width' => 410));
    $options = array('showLines' => 1, 'showHeadings' => 0, 'shaded' => 1, 'shadeCol' => array(0.9, 0.9, 0.9), 'fontSize' => 7, 'textCol' => array(0, 0, 0), 'rowGap' => 2, 'colGap' => 5, 'xPos' => 35, 'xOrientation' => 'right', 'width' => 410, 'cols' => $colOptions, 'innerLineThickness' => 0.3, 'outerLineThickness' => 0.3);
    // Dibuja la tabla datos del cliente
    $pdf->ezSetDy(84);
    $pdf->ezTable($tableData, "", "", $options);
    $actualY = $pdf->y;
    $pdf->setColor(0, 0, 0);
    $pdf->filledRectangle(30, $actualY - 30, 540, 18);
    $pdf->ezSetY($actualY - 15);
    $pdf->setColor(1, 1, 1);
    $pdf->ezText("<b>Cant</b>", 7, array('left' => 18, 'justification' => 'left'));
    $pdf->ezSetY($actualY - 15);
    $pdf->ezText("<b>Descripción</b>", 7, array('left' => 55, 'justification' => 'left'));
    $pdf->ezSetY($actualY - 15);
    $pdf->ezText("<b>Unitario</b>", 7, array('left' => 448, 'justification' => 'left'));
    $pdf->ezSetY($actualY - 15);
    $pdf->ezText("<b>Importe</b>", 7, array('left' => 513, 'justification' => 'left'));
    ////////// i. Partidas
    $tableData = array();
    $renglones = 0;
    $rowData = array("cantidad" => "", "descripcion" => "", "unitario" => "", "importe" => "");
    $partidaCnt = 0;
    foreach ($conceptos as $conceptoNode) {
        $partidaCnt++;
        $renglones += 2;
        $currentObj = array();
        $currentObj["cantidad"] = number_format(abs(doubleval($conceptoNode->getAttribute('cantidad'))), 0);
        $currentObj["descripcion"] = utf8_decode($conceptoNode->getAttribute('descripcion'));
        $currentObj["unitario"] = number_format($conceptoNode->getAttribute('valorUnitario'), 2);
        $currentObj["importe"] = number_format(doubleval($conceptoNode->getAttribute('importe')), 2);
        array_push($tableData, $currentObj);
    }
    $currentObj = array();
    $currentObj["cantidad"] = "";
    $currentObj["descripcion"] = "";
    $currentObj["unitario"] = "";
    $currentObj["importe"] = "";
    if ($renglones < 10) {
        for ($renglones; $renglones < 10; $renglones++) {
            array_push($tableData, $currentObj);
        }
    }
    $colNames = array("cantidad" => "<b>Cant</b>", "descripcion" => "<b>Descripción</b>", "unitario" => "<b>Unitario</b>", "importe" => "<b>Precio</b>");
    $colOptions = array("cantidad" => array('justification' => 'center', 'width' => 50), "descripcion" => array('justification' => 'left', 'width' => 370), "unitario" => array('justification' => 'right', 'width' => 60), "importe" => array('justification' => 'right', 'width' => 60));
    $options = array('showLines' => 1, 'showHeadings' => 1, 'shaded' => 1, 'shadeCol' => array(0.9, 0.9, 0.9), 'fontSize' => 7, 'textCol' => array(0, 0, 0), 'rowGap' => 4, 'colGap' => 5, 'xPos' => 35, 'xOrientation' => 'right', 'width' => 410, 'cols' => $colOptions, 'innerLineThickness' => 0.3, 'outerLineThickness' => 0.3);
    // Dibuja la tabla partidas
    $pdf->ezSetDy(11);
    $pdf->ezTable($tableData, $colNames, "", $options);
    ////////// i. Cantidad con letra
    $cadena = covertirNumLetras(number_format($comprobanteNode->getAttribute('total'), 2, ".", ''));
    $tableData = array(array("dato" => "<b>Total con letra</b>\n" . trim($cadena)));
    $colNames = array("dato" => "<b>Cant</b>");
    $colOptions = array("dato" => array('justification' => 'left', 'width' => 420));
    $options = array('showLines' => 1, 'showHeadings' => 0, 'shaded' => 0, 'shadeCol' => array(0.9, 0.9, 0.9), 'fontSize' => 7, 'textCol' => array(0, 0, 0), 'rowGap' => 10, 'colGap' => 10, 'xPos' => 40, 'xOrientation' => 'right', 'width' => 120, 'cols' => $colOptions, 'innerLineThickness' => 0.3, 'outerLineThickness' => 0.3);
    // Dibuja la tabla cantidad con letra
    $pdf->ezSetDy(0);
    $pdf->ezTable($tableData, $colNames, "", $options);
    ////////// i. Totales
    $f_importe = "\$" . number_format($comprobanteNode->getAttribute('subTotal'), 2);
    $f_iva_T = $impuestosNode->getAttribute('totalImpuestosTrasladados');
    $f_total = "\$" . number_format($comprobanteNode->getAttribute('total'), 2);
    $tableData = array();
    $rowData = array("leyenda" => "", "cantidad" => "");
    $subtotal = array("dato" => "Subtotal", "valor" => $f_importe);
    array_push($tableData, $subtotal);
    foreach ($traslados as $trasladoNode) {
        $tasaImpuesto = array();
        $tasaImpuesto_t = number_format($trasladoNode->getAttribute('tasa'), 0);
        $tasaImpuesto["dato"] = $trasladoNode->getAttribute('impuesto') . " " . $tasaImpuesto_t . "%";
        $tasaImpuesto["valor"] = "\$" . number_format($trasladoNode->getAttribute('importe'), 2);
        array_push($tableData, $tasaImpuesto);
    }
    foreach ($retenciones as $retencionNode) {
        $tasaImpuesto = array();
        $tasaImpuesto_t = number_format($retencionNode->getAttribute('tasa'), 0);
        $tasaImpuesto["dato"] = "Ret. " . $retencionNode->getAttribute('impuesto') . " " . $tasaImpuesto_t . "%";
        $tasaImpuesto["valor"] = "\$" . number_format($retencionNode->getAttribute('importe'), 2);
        array_push($tableData, $tasaImpuesto);
    }
    $total = array("dato" => "<b>Total</b>", "valor" => "<b>" . $f_total . "</b>");
    array_push($tableData, $total);
    $colNames = array("dato" => "<b>Cant</b>", "valor" => "Precio");
    $colOptions = array("dato" => array('justification' => 'right', 'width' => 60), "valor" => array('justification' => 'right', 'width' => 60));
    $options = array('showLines' => 1, 'showHeadings' => 0, 'shaded' => 1, 'shadeCol' => array(0.9, 0.9, 0.9), 'fontSize' => 7, 'textCol' => array(0, 0, 0), 'rowGap' => 3, 'colGap' => 5, 'xPos' => 455, 'xOrientation' => 'right', 'width' => 120, 'cols' => $colOptions, 'innerLineThickness' => 0.3, 'outerLineThickness' => 0.3);
    // Dibuja la tabla totales
    $pdf->ezSetDy(36);
    $pdf->ezTable($tableData, $colNames, "", $options);
    ////////// i. Sello
    $tableData = array(array("dato" => "<b>Sello Digital</b>\n" . $row_factura['sello']));
    $colNames = array("dato" => "<b>Cant</b>");
    $colOptions = array("dato" => array('justification' => 'left', 'width' => 400));
    $options = array('showLines' => 1, 'showHeadings' => 0, 'shaded' => 0, 'shadeCol' => array(0.8, 0.8, 0.8), 'fontSize' => 7, 'textCol' => array(0, 0, 0), 'rowGap' => 10, 'colGap' => 10, 'xPos' => 40, 'xOrientation' => 'right', 'width' => 120, 'cols' => $colOptions, 'innerLineThickness' => 0.3, 'outerLineThickness' => 0.3);
    // Dibuja la tabla sello
    $pdf->ezSetDy(-5);
    $pdf->ezTable($tableData, $colNames, "", $options);
    ////////// i. Cadena original
    $tableData = array(array("dato" => "<b>Cadena Original</b>\n" . utf8_decode(utf8_decode($row_factura['cadena']))));
    $colNames = array("dato" => "<b>Cant</b>");
    $colOptions = array("dato" => array('justification' => 'left', 'width' => 400));
    $options = array('showLines' => 1, 'showHeadings' => 0, 'shaded' => 0, 'shadeCol' => array(0.8, 0.8, 0.8), 'fontSize' => 7, 'textCol' => array(0, 0, 0), 'rowGap' => 10, 'colGap' => 10, 'xPos' => 40, 'xOrientation' => 'right', 'width' => 120, 'cols' => $colOptions, 'innerLineThickness' => 0.3, 'outerLineThickness' => 0.3);
    // Dibuja la tabla cadena original
    $pdf->ezSetDy(-5);
    $pdf->ezTable($tableData, $colNames, "", $options);
    // Leyendas
    $pdf->ezSetDy(-12);
    $leyendas = 'EFECTOS FISCALES AL PAGO. PAGO EN UNA SOLA EXHIBICION. ESTE DOCUMENTO ES UNA IMPRESION DE UN COMPROBANTE FISCAL DIGITAL';
    $pdf->setColor(0.5, 0.5, 0.5);
    $pdf->ezText($leyendas, 5, array('left' => 0, 'justification' => 'left'));
    $pdf->setColor(0, 0, 0);
    //REGRESA PARA PONER ENCABEZADO EN PAGINAS 2 ->
    if ($pdf->ezPageCount > 1) {
        $datos = array();
        $datos['logo'] = $logofile;
        $datos['totalPaginas'] = $pdf->ezPageCount;
        $datos['tipoDocto'] = $tipoDocto;
        $datos['foliodocto'] = $foliodocto;
        $datos['fechastr'] = $fechastr;
        for ($pn = 2; $pn <= $pdf->ezPageCount; $pn++) {
            $datos['paginaActual'] = $pn;
            //a partir de la segunda pagina.
            $pdf->reopenObject($pdf->ezPages[$pn]);
            headerDoc($pdf, $datos);
        }
    }
    //ESCRIBE REPORTE AL ARCHIVO.
    //================================================================================
    $pdfcode = $pdf->output();
    //save the file
    if ($tmpName) {
        $nombrePDF = tempnam("tmp/", 'face5') . ".pdf";
        $nombreToks = explode("/", $nombrePDF);
        if (count($nombreToks) < 2) {
            $nombreToks = explode("\\", $nombrePDF);
        }
        $lastTok = count($nombreToks) - 1;
        $nombrePDF = $nombreToks[$lastTok];
        $archivoPDF = "tmp/" . $nombrePDF;
        $archivos = array($nombrePDF, $archivoPDF);
    } else {
        $nombrePDF = $tipoDocto . "_" . $row_factura['serie'] . $row_factura['folio'] . ".pdf";
        $archivoPDF = "tmp/" . $nombrePDF;
        $archivos = array($nombrePDF, $archivoPDF);
    }
    $fp = fopen($archivoPDF, 'w');
    fwrite($fp, $pdfcode);
    fclose($fp);
    return $archivos;
}
<?php

require_once "../ConectarSolo.php";
$l = Conectarse("webpmm");
ini_set('post_max_size', '512M');
ini_set('upload_max_filesize', '512M');
ini_set('memory_limit', '500M');
ini_set('max_execution_time', 600);
ini_set('limit', -1);
include 'class.ezpdf.php';
$pdf = new Cezpdf('LETTER', 'portrait');
#					 t, b, l, r
$pdf->ezSetMargins(50, 70, 50, 50);
#w = 612 h = 792
$pdf->setColor(0.16, 0.38, 0.61);
$pdf->selectFont('fonts/Helvetica.afm');
$img = ImageCreatefromjpeg('../img/logo.jpg');
$pdf->addImage($img, 50, 697, 47, 50);
$pdf->addText(110, 722, 24, '<b>ENTREGAS PUNTUALES</b>');
$pdf->setColor(0.79, 0.67, 0.11);
$pdf->addText(110, 702, 16, '<b>Soporte de Factura ' . $_GET[folio] . '</b>');
$pdf->line(50, 690, 560, 690);
$pdf->setColor(0.25, 0.25, 0.25);
$pdf->ezText("\n\n\n\n{$f->fechaactual}", 12, array('justification' => 'right'));
#detallado superior
$s = "SELECT fd.*,SUBSTRING(CONCAT(cc.nombre,' ',cc.paterno,' ',cc.materno),1,25) cliente,gv.totalpaquetes,\n\t\tDATE_FORMAT(fd.fecha,'%d/%m/%Y') AS fecha\n\t\tFROM facturadetalle fd\n\t\tINNER JOIN guiasventanilla gv ON fd.folio=gv.id\n\t\tINNER JOIN catalogocliente cc ON gv.iddestinatario=cc.id\n\t\tWHERE fd.factura = '{$_GET['folio']}'\n\t\tUNION\n\t\tSELECT fd.*,SUBSTRING(CONCAT(cc.nombre,' ',cc.paterno,' ',cc.materno),1,25) cliente,ge.totalpaquetes,\n\t\tDATE_FORMAT(fd.fecha,'%d/%m/%Y') AS fecha\n\t\tFROM facturadetalle fd\n\t\tINNER JOIN guiasempresariales ge ON fd.folio=ge.id\n\t\tINNER JOIN catalogocliente cc ON ge.iddestinatario=cc.id\n\t\tWHERE fd.factura = '{$_GET['folio']}'";
$rx = mysql_query($s, $l) or die($s);
$registros = mysql_num_rows($rx);
if ($registros > 0) {
    $pdf->setColor(0.79, 0.67, 0.11);
    $pdf->ezText("<b>DETALLADO DE FACTURA, GUIAS</b>\n", 12, array('justification' => 'left'));
Beispiel #29
0
function init_pdf($pagesize, $orientation, $title)
{
    global $layout;
    $diff = array(177 => 'aogonek', 161 => 'Aogonek', 230 => 'cacute', 198 => 'Cacute', 234 => 'eogonek', 202 => 'Eogonek', 241 => 'nacute', 209 => 'Nacute', 179 => 'lslash', 163 => 'Lslash', 182 => 'sacute', 166 => 'Sacute', 188 => 'zacute', 172 => 'Zacute', 191 => 'zdot', 175 => 'Zdot', 185 => 'scaron', 169 => 'Scaron', 232 => 'ccaron', 200 => 'Ccaron', 236 => 'edot', 204 => 'Edot', 231 => 'iogonek', 199 => 'Iogonek', 249 => 'uogonek', 217 => 'Uogonek', 254 => 'umacron', 222 => 'Umacron', 190 => 'zcaron', 174 => 'Zcaron');
    $pdf = new Cezpdf($pagesize, $orientation);
    //landscape/portrait
    $pdf->isUnicode = true;
    $pdf->addInfo('Producer', 'LMS Developers');
    $pdf->addInfo('Title', $title);
    $pdf->addInfo('Creator', 'LMS ' . $layout['lmsv']);
    $pdf->setPreferences('FitWindow', '1');
    $pdf->ezSetMargins(PDF_MARGIN_TOP, PDF_MARGIN_BOTTOM, PDF_MARGIN_LEFT, PDF_MARGIN_RIGHT);
    $pdf->setLineStyle(0.5);
    $pdf->setFontFamily('arial', array('b' => 'arialbd'));
    $pdf->selectFont('arial', array('encoding' => 'WinAnsiEncoding', 'differences' => $diff), 1, true);
    return $pdf;
}
 function _print_prescription_old($p, &$toFile)
 {
     $pdf = new Cezpdf($GLOBALS['rx_paper_size']);
     $pdf->ezSetMargins($GLOBALS['rx_top_margin'], $GLOBALS['rx_bottom_margin'], $GLOBALS['rx_left_margin'], $GLOBALS['rx_right_margin']);
     $pdf->selectFont('Helvetica');
     if (!empty($this->pconfig['logo'])) {
         $pdf->ezImage($this->pconfig['logo'], "", "", "none", "left");
     }
     $pdf->ezText($p->get_prescription_display(), 10);
     if ($this->pconfig['use_signature']) {
         $pdf->ezImage($this->pconfig['signature'], "", "", "none", "left");
     } else {
         $pdf->ezText("\n\n\n\nSignature:________________________________", 10);
     }
     if (!empty($toFile)) {
         $toFile = $pdf->ezOutput();
     } else {
         $pdf->ezStream();
         // $pdf->ezStream(array('compress' => 0)); // for testing with uncompressed output
     }
     return;
 }