[英]How to use html code in fpdf to create a pdf?
require('fpdf/fpdf.php');
class PDF extends FPDF
{
function Header()
{
// Logo
$this->Image('asset/logo.png',10,6,20);
// Arial bold 15
$this->SetFont('Arial','B',15);
// Move to the right
$this->Cell(80);
// Title
$this->SetDrawColor(0,80,180);
$this->SetFillColor(230,230,0);
$this->SetTextColor(220,50,50);
$this->Cell(100,15,'FREE PEACE ASSESSMENT',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');
}
}
// Instanciation of inherited class
$pdf = new PDF();
$pdf->AliasNbPages();
$pdf->AddPage();
$html='<p>HI</p>';
$pdf->WriteHTML(utf8_decode($html));
$pdf->Output();
這是我的代碼。 我只是用 $html 來使用 writehtml 但是我得到了一個致命錯誤的錯誤:未捕獲的錯誤:調用未定義的方法 PDF::WriteHTML()錯誤:調用未定義的方法 PDF::WriteHTML() ....
Fpdf默認不提供寫HTML的功能。 你需要開發代碼。
<?php
require('fpdf/fpdf.php');
class PDF extends FPDF
{
protected $B = 0;
protected $I = 0;
protected $U = 0;
protected $HREF = '';
function WriteHTML($html)
{
// HTML parser
$html = str_replace("\n",' ',$html);
$a = preg_split('/<(.*)>/U',$html,-1,PREG_SPLIT_DELIM_CAPTURE);
foreach($a as $i=>$e)
{
if($i%2==0)
{
// Text
if($this->HREF)
$this->PutLink($this->HREF,$e);
else
$this->Write(5,$e);
}
else
{
// Tag
if($e[0]=='/')
$this->CloseTag(strtoupper(substr($e,1)));
else
{
// Extract attributes
$a2 = explode(' ',$e);
$tag = strtoupper(array_shift($a2));
$attr = array();
foreach($a2 as $v)
{
if(preg_match('/([^=]*)=["\']?([^"\']*)/',$v,$a3))
$attr[strtoupper($a3[1])] = $a3[2];
}
$this->OpenTag($tag,$attr);
}
}
}
}
function OpenTag($tag, $attr)
{
// Opening tag
if($tag=='B' || $tag=='I' || $tag=='U')
$this->SetStyle($tag,true);
if($tag=='A')
$this->HREF = $attr['HREF'];
if($tag=='BR')
$this->Ln(5);
}
function CloseTag($tag)
{
// Closing tag
if($tag=='B' || $tag=='I' || $tag=='U')
$this->SetStyle($tag,false);
if($tag=='A')
$this->HREF = '';
}
function SetStyle($tag, $enable)
{
// Modify style and select corresponding font
$this->$tag += ($enable ? 1 : -1);
$style = '';
foreach(array('B', 'I', 'U') as $s)
{
if($this->$s>0)
$style .= $s;
}
$this->SetFont('',$style);
}
function PutLink($URL, $txt)
{
// Put a hyperlink
$this->SetTextColor(0,0,255);
$this->SetStyle('U',true);
$this->Write(5,$txt,$URL);
$this->SetStyle('U',false);
$this->SetTextColor(0);
}
}
$pdf = new PDF();
// First page
$pdf->AddPage();
$pdf->SetFont('Arial','B',16);
$pdf->WriteHTML('You can<br><p align="center">center a line</p>and add a horizontal rule:<br><hr>');
$pdf->Output();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.