2013-08-07 2 views
0

Ну, мне нужно сохранить содержимое pdf-файла в базу данных и получить его. Я использую fpdf для создания содержимого моего pdf. Когда я использую $ pdf-> Output ("", "I"); или $ pdf-> Output ("", "D"); , Я могу видеть содержимое и сохранять в моей базе данных. Мой код является то, что: класс FPDF расширяет tFPDF {Загрузить pdf-блок из базы данных

       function Header() 
          { 
           $hoje = date("d/m/y"); 
           $this->Cell(10,10,"$hoje",0,'L'); 
           $this->Image('./images/logo.png',170,10,30); 

           $this->SetFont('Arial','',9); 

           $this->Cell(70); 

           $this->Cell(30,10,'Nome da empresa',0,'C'); 

           $this->Ln(15); 
          } 

           function NomeComprador($nomeUser,$apelido,$nomeCategoria) 
           { 

            $this->SetFont('DejaVu','',10); 

            $this->Cell(0,4,"Nome do Utilizador: $nomeUser" . " $apelido",0,1,'C'); 
            $this->Cell(-1); 
            $this->Cell(0,5,"Categoria: $nomeCategoria",0,1,'C'); 

            $this->Ln(4); 
           } 

           function informacaoImagem($nomeImagem,$titulo,$descricao,$poupa,$desconto,$quantidade){ 

           $this->nomeImagem = $nomeImagem; 
           $total = $quantidade * $poupa; 
           $this->Image('./images/paginaPrincipal/' . $this->nomeImagem,30,50,50); 
           $this->Cell(125,30,"Nome do Voucher: $titulo",0,1,'R'); 
           $this->Cell(120.5,-15,"Descrição: $descricao",0,1,'R'); 
           $this->SetFont('DejaVu','B',22); 
           $this->Cell(180,40,"$total" . " €",0,1,'C'); 
           $this->SetFont('DejaVu','',11); 
           $this->Cell(250,-45,"Desconto: $desconto" . '%',0,1,'C');        
           } 

           function informacaoOferta($menus,$descricoes){ 

            foreach ($menus as $key => $value) { 
              foreach ($descricoes as $key2 => $value2){ 
               if($key == 0 && $key2 == 0){ 
                $valor = strip_tags($value2); 
                $this->SetFont('DejaVu', 'B', 14); 
                $this->Cell(125,100,"$value:",0,1,'L'); 
                $this->SetFont('DejaVu','','11'); 
                $this->Write(5,$this->Cell(125,-75,"$valor")); 
                $this->Ln(10); 
              }elseif ($key == 1 && $key2 == 1){ 
               $valorFinal = strip_tags($value2); 
               $this->SetFont('DejaVu','B',13); 
               $this->Cell(125,-30,"$value:",0,1,'L'); 
               $this->SetFont('DejaVu','','11'); 
               $this->Write(5,"$valorFinal"); 
               $this->Ln(50); 
              }elseif($key == 2 && $key2 == 2){ 
               $valor3 = strip_tags($value2); 
               $this->SetFont('DejaVu','B',13); 
               $this->Cell(125,-50,"$value:",0,1,'L'); 
               $this->SetFont('DejaVu','','11'); 
               $this->Write(7,"$valor3"); 
               $this->Ln(30); 
              }elseif($key == 3 && $key2 == 3){ 
               $valor4 = strip_tags($value2); 
               $this->SetFont('DejaVu','B',13); 
               $this->Cell(125,-10,"$value:",0,1,'L'); 
               $this->SetFont('DejaVu','','11'); 
               $this->Write(3,"$valor4"); 
               $this->Ln(40); 
              }elseif($key == 4 && $key2 == 4){ 
               $valor5 = strip_tags($value2); 
               $this->SetFont('DejaVu','B',13); 
               $this->Cell(125,20,"$value:",0,1,'L'); 
               $this->SetFont('DejaVu','','11'); 
               $this->Write(0,"$valor5"); 
               $this->Ln(20); 
              } 
             }       
            } 
           } 

           function EAN13($x, $y, $barcode, $h=16, $w=.35) 
            { 
             $this->Barcode($x,$y,$barcode,$h,$w,13); 
            } 

            function UPC_A($x, $y, $barcode, $h=16, $w=.35) 
            { 
             $this->Barcode($x,$y,$barcode,$h,$w,12); 
            } 

            function GetCheckDigit($barcode) 
            { 

             $sum=0; 
             for($i=1;$i<=11;$i+=2) 
              $sum+=3*$barcode[$i]; 
             for($i=0;$i<=10;$i+=2) 
              $sum+=$barcode[$i]; 
             $r=$sum%10; 
             if($r>0) 
              $r=10-$r; 
             return $r; 
            } 

            function TestCheckDigit($barcode) 
            { 

             $sum=0; 
             for($i=1;$i<=11;$i+=2) 
              $sum+=3*$barcode[$i]; 
             for($i=0;$i<=10;$i+=2) 
              $sum+=$barcode[$i]; 
             return ($sum+$barcode[12])%10==0; 
            } 

            function Barcode($x, $y, $barcode, $h, $w, $len) 
            { 

             $barcode=str_pad($barcode,$len-1,'0',STR_PAD_LEFT); 
             if($len==12) 
              $barcode='0'.$barcode; 

             if(strlen($barcode)==12) 
              $barcode.=$this->GetCheckDigit($barcode); 
             elseif(!$this->TestCheckDigit($barcode)) 
              $this->Error('Incorrect check digit'); 

             $codes=array(
              'A'=>array(
               '0'=>'0001101','1'=>'0011001','2'=>'0010011','3'=>'0111101','4'=>'0100011', 
               '5'=>'0110001','6'=>'0101111','7'=>'0111011','8'=>'0110111','9'=>'0001011'), 
              'B'=>array(
               '0'=>'0100111','1'=>'0110011','2'=>'0011011','3'=>'0100001','4'=>'0011101', 
               '5'=>'0111001','6'=>'0000101','7'=>'0010001','8'=>'0001001','9'=>'0010111'), 
              'C'=>array(
               '0'=>'1110010','1'=>'1100110','2'=>'1101100','3'=>'1000010','4'=>'1011100', 
               '5'=>'1001110','6'=>'1010000','7'=>'1000100','8'=>'1001000','9'=>'1110100') 
              ); 
             $parities=array(
              '0'=>array('A','A','A','A','A','A'), 
              '1'=>array('A','A','B','A','B','B'), 
              '2'=>array('A','A','B','B','A','B'), 
              '3'=>array('A','A','B','B','B','A'), 
              '4'=>array('A','B','A','A','B','B'), 
              '5'=>array('A','B','B','A','A','B'), 
              '6'=>array('A','B','B','B','A','A'), 
              '7'=>array('A','B','A','B','A','B'), 
              '8'=>array('A','B','A','B','B','A'), 
              '9'=>array('A','B','B','A','B','A') 
              ); 
             $code='101'; 
             $p=$parities[$barcode[0]]; 
             for($i=1;$i<=6;$i++) 
              $code.=$codes[$p[$i-1]][$barcode[$i]]; 
             $code.='01010'; 
             for($i=7;$i<=12;$i++) 
              $code.=$codes['C'][$barcode[$i]]; 
             $code.='101'; 

             for($i=0;$i<strlen($code);$i++) 
             { 
              if($code[$i]=='1') 
               $this->Rect($x+$i*$w,$y,$w,$h,'F'); 
             } 

             $this->SetFont('Arial','',12); 
             $this->Text($x,$y+$h+11/$this->k,substr($barcode,-$len)); 
            } 

           function PrintComprador($nomeUser,$apelido,$nomeCategoria,$titulo,$nomeImagem,$descricao,$poupa,$desconto,$quantidade) 
           { 
            $this->AddPage(); 
            $this->NomeComprador($nomeUser,$apelido,$nomeCategoria); 
            $this->informacaoImagem($nomeImagem,$titulo,$descricao,$poupa,$desconto,$quantidade); 

           } 

           function PrintOferta($menus,$descricoes) 
           { 
            $this->informacaoOferta($menus,$descricoes); 
           } 

            function Footer() 
            { 

            $this->SetY(-15); 

            $this->SetFont('DejaVu', '', 8); 

            $this->Cell(0,10,'Página '.$this->PageNo().'/{nb}',0,0,'C'); 
            } 
           } 
           $pdf = new FPDF(); 
           $pdf->AddFont('DejaVu','','DejaVuSansCondensed.ttf',true); 
           $pdf->AddFont('DejaVu', 'B', 'DejaVuSansCondensed-Bold.ttf', true); 
           $pdf->SetFont('DejaVu', '', 14); 
           $pdf->AliasNbPages(); 
           for($i = 0; $i < $quantidade; $i++){ 
            $pdf->PrintComprador($nomeUser,$apelido,$nomeCategoria,$titulo,$nomeImagem,$descricao,$poupa,$desconto,$quantidade); 
            $random = substr(number_format(time() * rand(),0,'',''),0,12); 
            $pdf->EAN13(40,20,$random); 
            $pdf->PrintOferta($menus,$descricoes); 
            $pdf->Write(40,"Para descobrir a localização, descubra "); 
            $pdf->SetFont('','U'); 
            $link = $pdf->AddLink(); 
            $pdf->Write(40,'aqui',$hiperlink); 
            $pdf->SetFont('DejaVu', 'B', 12); 
            $pdf->Ln(2); 
            $pdf->Write(70,"Procedimento:"); 
            $pdf->Ln(2); 
            $pdf->SetFont('DejaVu', '', 11); 
            $pdf->Write(90,"1- Imprimir o cupão."); 
            $pdf->Ln(2); 
            $pdf->SetFont('DejaVu', '', 11); 
            $pdf->Write(110,"2- Leia atentamente as condições e os detalhes da compra."); 
            $pdf->Ln(2); 
            $pdf->SetFont('DejaVu', '', 11); 
            $pdf->Write(130,"3- Apresentação do cupão no estabelecimento previsto."); 

           } 
           $file = $pdf->Output("","S"); 


       $query = "INSERT INTO historico   (nomeUser,email,nomeVoucher,categoria,quantidade,preco,confirmacao,filePDF,idUser) VALUES (?,?,?,?,?,?,?,?,?)"; 
        $stmt = $mybd->prepare($query) or die("Erro na base de dados"); 
        $ficheiro = addslashes($file); 
        $stmt->bind_param("ssssiissi",$nomeUser,$email,$titulo,$nomeCategoria,$quantidade,$total,$confirmacao,$ficheiro,$idUser); 
        $stmt->execute();    
        $stmt->close(); 

Когда я хочу, чтобы получить его, я не могу показать мое содержание и глинобитных скажите мне «Не удалось загрузки PDF» Я использую следующий код для чтения из базы данных:

  $query = "select nomeUser,email,nomeVoucher,categoria,preco,confirmacao,filePDF 
          from historico 
          Where confirmacao = 'a confirmar' 

          LIMIT $start, $per_page"; 
        $stmt = $mybd->prepare($query); 
    $stmt->execute(); 
    $stmt->bind_result($nomeUser,$email,$nomeVoucher, $categoria, $preco, $confirmacao,$filePDF); 
      while ($stmt->fetch()) { 
     if($confirmacao == "a confirmar"){ 
      echo("<tbody >");   
      echo("<tr> 
        <td>$nomeUser</td>"); 
       echo "<td>$email</td>"; 
       echo("<td>$nomeVoucher</td>"); 
       echo("<td>$categoria</td>"); 
       echo("<td>$preco €</td>"); 
       echo("<td>$confirmacao</td>"); 
       header('Content-Type: application/pdf'); 
       header('Accept-Ranges: bytes'); 
       header('Content-Transfer-Encoding: binary'); 
       header("Content-Disposition: inline; filename=" . $nomeVoucher .'.pdf'); 
       echo $row['data']; 
       die(); 
       echo"<input type='hidden' name='mail' value='0' />"; 
       echo "<th><input type='checkbox' name='mail' value='1'></th>"; 
       echo("</tr>"); 
       echo("</tbody>"); 
      } 
     } 

Я не могу найти ответа на свою проблему. Любой может мне помочь. Thanks

ответ

0

Похоже, вы пытаетесь смешать HTML и двоичный выход. Вам нужно будет установить ссылку в вашей таблице HTML, которая указывает на отдельный скрипт PHP. В этом отдельном скрипте вы можете выводить заголовки и только двоичные данные.

Edit: Давать Пример

В вашем HTML таблице, вы будете удалить все header() и die() звонков, и вам потребуется ссылка на документ:

echo("<td><a href='getFile.php?nomeVoucher=".$nomeVoucher."'>Download</a>");

Затем создайте новый сценарий под названием getFile.php в том же каталоге. Он должен выглядеть Somthing так:

<?php 

if(isset($_GET['nomeVoucher'])) { 
    $nomeVoucher = $_GET['nomeVoucher']; 
} else { 
    die("nomeVoucher missing."); 
} 

$query = "select filePDF 
      from historico 
      Where nomeVoucher = ? 
      LIMIT $start, $per_page"; 

$stmt = $mybd->prepare($query); 
$stmt->bind_param('s', $_GET['nomeVoucher']); 
$stmt->execute(); 
$stmt->bind_result($filePDF); 
if($stmt->fetch()) { 
    header('Content-Type: application/pdf'); 
    header('Accept-Ranges: bytes'); 
    header('Content-Transfer-Encoding: binary'); 
    header('Content-Length: '.strlen($filePDF)); 
    header("Content-Disposition: inline; filename=" . $nomeVoucher .'.pdf'); 
    echo $filePDF; 
    die(); 
} else { 
    die("something broke"); 
} 

?> 

Имейте в виду, что это чисто концептуальным. Я не использовал mysqli экстенсивно, особенно с функцией bind_result(), поэтому этот код предполагает, что ваш исходный пример по крайней мере правильно отображает и отображает некоторые данные. Он также предполагает, что $filePDF содержит фактические двоичные данные PDF.

+0

Ну, я не понимаю вашего ответа. Может, вы покажете мне пример? – user2612507

+0

не работает: s. См. Код перед тем, как просмотреть изменения, которые сделали – user2612507

+0

Если я делаю var_dump для переменной $ filePDF, покажите мне двоичный контент и покажу мне эти ошибки: Предупреждение: не удается изменить информацию заголовка - заголовки уже отправлены ... Он показывает мне все заголовки. – user2612507

Смежные вопросы