带有TCPDF的Symfony 1.4:如何从数据库中检索数据并将其显示为.pdf文件?

时间:2013-11-06 01:26:08

标签: php symfony-1.4 tcpdf

我使用Symfony 1.4。我想使用TCPDF创建一个pdf文件,其中包含涉及多个表的查询内容。 这是我在actions.class.php中的代码:

public function executeTest()
{ 
     $this->conflictos1s = Doctrine_Core::getTable('Conflictos1')
      ->createQuery('a') 
      ->leftJoin('a.SectorActividadCiuTa7')     
      ->leftJoin('a.RelacionConflictualPrincipalTa9') 
      ->leftJoin('a.SubsectorActividadTa8')       
       ->leftJoin('a.DemandasTa2')      
       ->leftJoin('a.ActoresTa1')     
       ->leftJoin('a.Conflictos1HasActoresTa1')    
      ->orderBy('a.Id DESC')
            ->execute();  

  $config = sfTCPDFPluginConfigHandler::loadConfig();

  // pdf object
  $pdf = new sfTCPDF();

  // set document information
  $pdf->SetCreator(PDF_CREATOR);
  $pdf->SetAuthor('J. H.');
  $pdf->SetTitle('TCPDF Example 001');
  $pdf->SetSubject('TCPDF Tutorial');
  $pdf->SetKeywords('TCPDF, PDF, example, test, guide');

  // set default header data
 $pdf->SetHeaderData(PDF_HEADER_LOGO, PDF_HEADER_LOGO_WIDTH, PDF_HEADER_TITLE.' 001', PDF_HEADER_STRING);

  // set header and footer fonts
  $pdf->setHeaderFont(Array(PDF_FONT_NAME_MAIN, '', PDF_FONT_SIZE_MAIN));
  $pdf->setFooterFont(Array(PDF_FONT_NAME_DATA, '', PDF_FONT_SIZE_DATA));

  // set default monospaced font
  $pdf->SetDefaultMonospacedFont(PDF_FONT_MONOSPACED);

  //set margins
  $pdf->SetMargins(PDF_MARGIN_LEFT, PDF_MARGIN_TOP, PDF_MARGIN_RIGHT);
  $pdf->SetHeaderMargin(PDF_MARGIN_HEADER);
  $pdf->SetFooterMargin(PDF_MARGIN_FOOTER);

  //set auto page breaks
  $pdf->SetAutoPageBreak(TRUE, PDF_MARGIN_BOTTOM);

  //set image scale factor
  $pdf->setImageScale(PDF_IMAGE_SCALE_RATIO);

  // ---------------------------------------------------------

  // set default font subsetting mode
  $pdf->setFontSubsetting(true);

  // Set font
  // dejavusans is a UTF-8 Unicode font, if you only need to
  // print standard ASCII chars, you can use core fonts like
  // helvetica or times to reduce file size.
  $pdf->SetFont('dejavusans', '', 10);

  // Add a page
  // This method has several options, check the source code documentation for more information.

$pdf->AddPage();

$pdf->Write(0, '', '', 0, 'L', true, 0, false, false, 0);

$pdf->SetFont('helvetica', '', 6);
  // Set some content to print
 $html = $this->getPartial(
    'generar_pdf', 
    // put in this array all variables you want to give to the partial

   array('posts' => $posts)
  );
  $pdf->writeHTML($html, true, false, false, false, '');

  // ---------------------------------------------------------

  // Close and output PDF document
  // This method has several options, check the source code documentation for more information.
  $pdf->Output('example_conflictos.pdf', 'I');

  // Stop symfony process
  throw new sfStopException();
}

这是我的模板代码(部分名为_generar_pdf.php)。我遵循了这里的建议: Using PHP with TCPDF to retrieve data(using mysql) from a database and show it as a .pdf file

<?php ob_start(); ?>
<h2>Listado de Conflictos</h2>
<table cellspacing="1" border="1">       
  <thead>
    <tr>
      <th>Id</th>
       <th>Ver acciones<br>conflictivas</th>
      <th>Ver actores</th>
       <th>Fecha comienzo</th>
      <th>Relacion conflictual principal</th>
      <th>Sector actividad</th>
      <th>Subsector actividad</th>
      <th>Demandas</th>      
      <th>Descripcion-general</th>
      <th>Descripcion protagonista</th>
      <th>Descripcion antagonista</th>
      <th>Descripcion demandaprinc</th>
      <th>Nivel estado</th>
      <th>Descripcion sector</th>
      <th>Fecha final</th>
</tr>
</thead>
<tbody>
  <?php foreach ($conflictos1s as $conflictos1): ?>
    <tr>
      <td><?php echo $conflictos1->getId() ?></a></td>
      <td><?php echo date('d/m/Y', strtotime($conflictos1->getFechaComienzo())) ?></td>
      <td><?php echo $conflictos1->getRelacionConflictualPrincipalTa9() ?></td>
      <td><?php echo $conflictos1->getSectorActividadCiuTa7() ?></td>
      <td><?php echo $conflictos1->getSubsectorActividadTa8() ?></td>
      <td><?php echo $conflictos1->getDemandasTa2() ?></td>
       <td width="20%"><?php echo substr($conflictos1->getDescripcionGeneral(),0,60) ?></td> 
      <td><?php echo $conflictos1->getDescripcionProtagonista() ?></td>
      <td><?php echo $conflictos1->getDescripcionAntagonista() ?></td>
      <td><?php echo $conflictos1->getDescripcionDemandaprinc() ?></td>
      <td><?php echo $conflictos1->getNivelEstado() ?></td>
      <td><?php echo $conflictos1->getDescripcionSector() ?></td>
      <td><?php if(!is_null($conflictos1->getFechaFinal())){ echo date('d/m/Y', strtotime($conflictos1->getFechaFinal()));} ?></td> 
    </tr>
    <?php endforeach; ?>      
  </tbody>
</table>
<?php $posts = ob_get_contents();
ob_end_clean(); 
echo $posts ?>

这是我的结果: PDF file 我看不到可变数据。我做错了什么?

1 个答案:

答案 0 :(得分:1)

这是我遇到的解决方案:我将问题分成两部分。首先,我使用查询构建了一个操作:操作已调用executeTest(请参阅下面的代码)

public function executeTest()
{ 
     $this->conflictos1s = Doctrine_Core::getTable('Conflictos1')
      ->createQuery('a') 
      ->leftJoin('a.SectorActividadCiuTa7')     
      ->leftJoin('a.RelacionConflictualPrincipalTa9') 
      ->leftJoin('a.SubsectorActividadTa8')       
       ->leftJoin('a.DemandasTa2')      
       ->leftJoin('a.ActoresTa1')     
       ->leftJoin('a.Conflictos1HasActoresTa1')    
      ->orderBy('a.Id')
      ->execute();  
}   

然后我构建了一个名为testSuccess.php的模板。到目前为止,Symfony 1.4没有什么新东西。但是在这个模板中,我添加了以下代码行。起初:

<?php ob_start(); ?>

最后,在我写的模板中:

<?php $posts = ob_get_contents(); ?>

<?php ob_end_clean(); ?>

视图内容记录在变量$posts

//testSuccess.php

<?php ob_start(); ?>


<h2>Listado de Conflictos</h2>
<table cellspacing="1" border="1">       
  <thead>
    <tr>
      <th width="2%">Id</th>
       <th width="6%">Fecha comienzo</th>
      <th>Relacion conflictual principal</th>
      <th>Sector actividad</th>
      <th>Subsector actividad</th>
      <th>Demandas</th>      
      <th width="20%">Descripcion-general</th>
      <th>Descripcion protagonista</th>
      <th>Descripcion antagonista</th>
      <th>Descripcion demandaprinc</th>
      <th>Nivel estado</th>
      <th>Descripcion sector</th>
</tr>
</thead>
<tbody>
  <?php foreach ($conflictos1s as $conflictos1): ?>
    <tr>
      <td width="2%"><?php echo $conflictos1->getId() ?></td>
      <td width="6%"><?php echo date('d/m/Y', strtotime($conflictos1->getFechaComienzo())) ?></td>
      <td><?php echo $conflictos1->getRelacionConflictualPrincipalTa9() ?></td>
      <td><?php echo $conflictos1->getSectorActividadCiuTa7() ?></td>
      <td><?php echo $conflictos1->getSubsectorActividadTa8() ?></td>
      <td><?php echo $conflictos1->getDemandasTa2() ?></td>
       <td width="20%"><?php echo substr($conflictos1->getDescripcionGeneral(),0,60).'...' ?></td> 
      <td><?php echo $conflictos1->getDescripcionProtagonista() ?></td>
      <td><?php echo $conflictos1->getDescripcionAntagonista() ?></td>
      <td><?php echo $conflictos1->getDescripcionDemandaprinc() ?></td>
      <td><?php echo $conflictos1->getNivelEstado() ?></td>
      <td><?php echo $conflictos1->getDescripcionSector() ?></td>   
    </tr>
    <?php endforeach; ?>      
  </tbody>
</table>
<?php $posts = ob_get_contents();
ob_end_clean(); ?>
<?php $sf_user->setAttribute('para_pdf', $posts); ?>
 <a href="<?php echo url_for('conflictos/testpdf') ?>">Generar Pdf</a>

这个想法来自https://stackoverflow.com/users/1029908/alexey-gerasimov的回答:

Using PHP with TCPDF to retrieve data(using mysql) from a database and show it as a .pdf file

在此模板中,我们生成视图并捕获浏览器“写入”的所有内容。我添加了一个链接以立即生成PDF <a href="<?php echo url_for('conflictos/testpdf') ?>">Generar Pdf</a>。它通过Symfony的用户类将变量$posts的内容传递给新的操作testpdf

<?php $sf_user->setAttribute('para_pdf', $posts); ?>

它要求一个名为testpdf的新动作。在新操作executeTestpdf中,请注意以下代码行,该代码行检索变量$posts的值:

$ html = $ this-> getUser () -> getAttribute ('para_pdf');

public function executeTestpdf()
{       
  $config = sfTCPDFPluginConfigHandler::loadConfig();

  // pdf object
  $pdf = new sfTCPDF();

  // set document information
  $pdf->SetCreator(PDF_CREATOR);
  $pdf->SetAuthor('J. H.');
  $pdf->SetTitle('TCPDF Example 001');
  $pdf->SetSubject('TCPDF Tutorial');
  $pdf->SetKeywords('TCPDF, PDF, example, test, guide');

  // set default header data
 $pdf->SetHeaderData(PDF_HEADER_LOGO, PDF_HEADER_LOGO_WIDTH, PDF_HEADER_TITLE.' 001', PDF_HEADER_STRING);

  // set header and footer fonts
  $pdf->setHeaderFont(Array(PDF_FONT_NAME_MAIN, '', PDF_FONT_SIZE_MAIN));
  $pdf->setFooterFont(Array(PDF_FONT_NAME_DATA, '', PDF_FONT_SIZE_DATA));

  // set default monospaced font
  $pdf->SetDefaultMonospacedFont(PDF_FONT_MONOSPACED);

  //set margins
  $pdf->SetMargins(PDF_MARGIN_LEFT, PDF_MARGIN_TOP, PDF_MARGIN_RIGHT);
  $pdf->SetHeaderMargin(PDF_MARGIN_HEADER);
  $pdf->SetFooterMargin(PDF_MARGIN_FOOTER);

  //set auto page breaks
  $pdf->SetAutoPageBreak(TRUE, PDF_MARGIN_BOTTOM);

  //set image scale factor
  $pdf->setImageScale(PDF_IMAGE_SCALE_RATIO);

  // ---------------------------------------------------------
 $pdf->setPageOrientation("L");


  // set default font subsetting mode
  $pdf->setFontSubsetting(true);

  // Set font
  $pdf->SetFont('helvetica', '', 6);

  // Add a page
  // This method has several options, check the source code documentation for more information.

$pdf->AddPage();

$pdf->Write(0, '', '', 0, 'L', true, 0, false, false, 0);


  // Set some content to print


 $html = $this->getUser()->getAttribute('para_pdf');


  $pdf->writeHTML($html, true, false, false, false, '');

  // ---------------------------------------------------------

  // Close and output PDF document
  // This method has several options, check the source code documentation for more information.
  $pdf->Output('example_conflictos.pdf', 'I');

  // Stop symfony process
  throw new sfStopException();
}

然后,最后我生成了PDF,并正确显示了所有数据!