Я пытаюсь создать PDF-файл с CSS и HTML, но мой CSS не появляется в моем PDF-файле. Учитывается только размер шрифта и цвет шрифта.
Я даю вам код (извините, он немного длинный ...)
$config = sfTCPDFPluginConfigHandler::loadConfig('my_config');
$doc_title = "Fiche Logement";
$html = <<<EOF
<style>
.informations {
padding: 10px;
margin: 10px;
border: 1px dotted black;}
.informations table {
margin-top: 10px;}
#modif {
margin: 20px;
text-align: left;
float: right;}
#modif th {
padding-left: 10px;}
#modif td {
padding-left: 10px;}
#adresse {
width: 307px;
float: left;}
#reservataire {
width: 307px;
float: right;}
#intergen {
width: 307px;
float: right;}
#infos {
width: 290px;
float: left;}
#handicap {
padding-bottom: 12px;
width: 324px;
float: right;}
#charges {
margin-bottom: 20px;
width: 307px;
float: left;}
#loyer {
width: 307px;
float: right;}
#commentaires {
clear: both;}
h2 {
font-variant: small-caps;
text-align: center;
font-size: 19px;
font-weight: bold;
padding: 0px 0px 2px 5px;
margin: 15px 0px 20px 0px;
color: #000000;
border-top: 1px dotted black;
border-bottom: 1px dotted black;}
h3 {
width: 250px;
font-variant: small-caps;
font-size: 15px;
font-weight: bold;
padding: 0px 0px 0px 5px;
margin: 0px;
color: #225D6D;
border-top: 1px dotted black;
border-bottom: 1px dotted black;}
</style>
<div id='intergen' class='informations'>
<h3>Intergénérationnel</h3>
<table>
<tr>
<th>Intergénérationnel :</th> <td><?php echo \$logement->getIntergen() ?></td>
</tr>
</table>
</div>
<div id='infos' class='informations'>
<h3>Informations logement</h3>
<table>
<tr>
<th>Bâtiment :</th> <td><?php echo \$logement->Parclogement->getBatiment() ?></td>
</tr>
<tr>
<th>Taille :</th> <td><?php echo \$logement->getTaille() ?></td>
</tr>
<tr>
<th>Type :</th> <td><?php echo \$logement->getTypelog() ?></td>
</tr>
<tr>
<th>Surface habitable :</th> <td><?php if(\$logement->getSurfacehab() == 0){ echo 'Non Spécifié';} else {echo \$logement->getSurfacehab(). " m²";} ?></td>
</tr>
<tr>
<th>Chauffage :</th> <td><?php echo \$logement->getChauffage() ?></td>
</tr>
<tr>
<th>Ascenseur :</th> <td><?php echo \$logement->getAscenseur() ?></td>
</tr>
</table>
</div>
<div id='handicap' class='informations'>
<h3>Infrastructures handicapés</h3>
<table>
<tr>
<th>Immeuble accessible :</th> <td><?php echo \$logement->getAccessibl() ?></td>
</tr>
<tr>
<th>Ascenceur accessible :</th> <td><?php echo \$logement->getAscenseuracc() ?></td>
</tr>
<tr>
<th>Logement adaptable :</th> <td><?php echo \$logement->getAdaptable() ?></td>
</tr>
<tr>
<th>Logement adapté :</th> <td><?php echo \$logement->getAdapte() ?></td>
</tr>
</table>
</div>
EOF;
//create new PDF document (document units are set by default to millimeters)
$pdf = new sfTCPDF(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true);
// set document information
$pdf->SetCreator(PDF_CREATOR);
$pdf->SetAuthor(PDF_AUTHOR);
$pdf->SetTitle($doc_title);
//set default header data
$pdf->SetHeaderData(PDF_HEADER_LOGO, PDF_HEADER_LOGO_WIDTH, PDF_HEADER_TITLE, PDF_HEADER_STRING);
//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 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);
// Fixe la taille de la page
$pdf->SetDisplayMode(90);
//initialize document
$pdf->SetFont('helvetica', '', 10);
$pdf->AddPage();
// output some HTML code
$pdf->writeHTML($html , true, false, true, false, '');
//reset pointer to the last page
$pdf->lastPage();
// Close and output PDF document
$pdf->Output('fichelogement.pdf', 'I');
// Stop symfony process
throw new sfStopException();
В первую очередь, вы должны заметить, что PDF и HTML - разные форматы, которые почти не имеют ничего общего. Если TCPDF позволяет вам предоставлять входные данные с помощью HTML и CSS, то это потому, что он реализует простой парсер для этих двух языков и пытается понять, как перевести их в PDF. Поэтому логично, что TCPDF поддерживает только небольшое подмножество спецификаций HTML и CSS, и даже в поддерживаемых вещах, вероятно, не все так идеально, как в веб-браузерах первого класса.
Сказав это, возникает вопрос: что поддерживается, а что нет? Документация в основном пропускает этот вопрос и позволяет вам наслаждаться методом проб и ошибок.
Взглянув на исходный код, мы видим, что есть защищенный метод TCPDF::getHtmlDomArray()
, который, помимо прочего, анализирует CSS объявления. Я вижу такие вещи, как font-family
, list-style-type
или text-indent
, но нет margin
или padding
, насколько я могу видеть, и, определенно, нет float
вообще.
Подведем итоги: в TCPDF вы можете использовать CSS для некоторого базового форматирования. Если вам нужно преобразовать HTML в PDF, это не тот инструмент. (Если это так, могу ли я предложить wkhtmltopdf?)
Начиная с версии 5.7 TCPDF включает поддержку границ CSS. Margins, padding и float пока не поддерживаются. Посетите веб-сайт TCPDF по адресу http://www.tcpdf.org и посетите официальный форум для получения дополнительной информации.