【问题标题】:FPDF PHP MYSQL Text Does Not Fit In CellFPDF PHP MYSQL 文本不适合单元格
【发布时间】:2023-10-15 12:35:01
【问题描述】:

我想以 pdf 格式从 MySql 数据库中导出数据。我可以从 mysql 数据库中执行此操作,这非常好。我试图自动化这个。我使用了 FPDF 库,但数据不适合表格。我搜索了但无法修复它。

我该怎么办?

图片:

我的专栏:

示例内容:

我的代码:

<?php
 require('./fpdf/fpdf.php');

//Database 
require_once __DIR__ . '/db_config.php';
$connection = 
mysqli_connect(DB_SERVER,DB_USER,DB_PASSWORD,DB_DATABASE);

if(!$connection){
    die("Connection error  : " . mysqli_connect_eror());
}

class PDF extends FPDF
 {
    // Page header
    function Header()
    {
        $ImagePath ='image url';
        // Logo
        $this->Image($ImagePath,10,70,0,90);
        $this->SetFont('Arial','B',13);
        // Move to the right
        $this->Cell(80);
        // Title
        $this->Cell(80,10,'title',1,0,'C');
        // Line break
        $this->Ln(20);
    }
     
    // Page footer
    function Footer()
    {
        // Position at 1.5 cm from bottom
        $this->SetY(-15);
        // Arial italic 8
        $this->SetFont('Arial','I',8);
        // Page number
        $this->Cell(0,10,'Page '.$this- 
    >PageNo().'/{nb}',0,0,'C');
    }
    
 }
 // Columns 
    $display_heading = array('JobId'=>'JobId','ReleaseDate'=> 
'ReleaseDate', 
'StartingDate'=> 
'StartingDate','TargetTime'=>'TargetTime','JobContent'=> 

     'JobContent','KindId'=>'KindId','JobStatus'=>'JobStatus','CustomerId'  
=>'CustomerId');
    
 // Database Result    
    $result = mysqli_query($connection, "SELECT * FROM Jobs;") or die("database 
 error:". mysqli_error($connection));
    $header = mysqli_query($connection, "SHOW columns FROM Jobs");
    
    // Settings
    $pdf = new PDF();
    //header
    $pdf->AddPage();
    //foter page
    $pdf->AliasNbPages();
    $pdf->SetFont('Arial','B',8);
    foreach($header as $heading) {
    $pdf->Cell(24,7,$display_heading[$heading['Field']],1);
    }
    foreach($result as $row) {
    $pdf->Ln();
    foreach($row as $column)
    $pdf->Cell(24,7,$column,1);
    
    }
    $pdf->Output();

 //Connection close
 mysqli_close($connection);

 ?>

【问题讨论】:

标签: php mysql pdf fpdf


【解决方案1】:

您可能想查看http://www.fpdf.org/en/script/script62.php 上的“将文本固定到单元格”扩展程序。在http://www.fpdf.org/en/script/ex62.pdf 上查看生成的示例 PDF 以了解它的外观。

如果您不想像那样压缩文本,那么@stui 建议的方式可能效果最好(获取字符串宽度,并将文本拆分为多行)。

【讨论】:

    【解决方案2】:

    您可以使用GetStringWidth() 来确定当前字体配置中给定字符串的宽度是多少毫米。基于此,如果字符串宽度大于您的阈值(在您的情况下为单元格宽度),您可以减小字体大小或插入换行符。

    $fontSize = 14;
    while($pdf->GetStringWidth($text) > 80){
        $pdf->setFontSize(--$fontSize);
    }
    

    【讨论】: