title: TCPDF with FPDI templates and CSS
body: <p>When using TCPDF together with FPDI templates, some CSS support is lost in the process. The problem are things like borders or background-colors, that end up in layers below the PDF template. TCPDF uses <code>SetLineStyle()</code> to convert CSS borders/backgrounds to PDF and this seems to be the problem. </p>
  
  <p>For example:</p>
  
  <pre><code>$this-&gt;setSourceFile($filename); // /path/to/my/background.pdf
  $imported_page = $this-&gt;ImportPage(1);
  $this-&gt;useTemplate($imported_page);
  
  ...
  
  $html = '&lt;table style="border: 1px solid #000;"&gt;&lt;tr&gt;&lt;td style="background-color: #ff0000;"&gt;...&lt;/td&gt;&lt;/tr&gt;&lt;/table&gt;';
  
  $this-&gt;writeHTMLCell(45, 25, 160, 29, $html); 
  </code></pre>
  
  <p>doesn't render the CSS borders. As soon as <code>useTemplate()</code> is removed the borders are there. Analyzing the resulting PDFs with Illustrator shows some interesting things:</p>
  
  <p>PDF layers with <code>useTemplate()</code> - top to bottom:</p>
  
  <ol>
  <li>Table/Content layers</li>
  <li>PDF Template layers (group)</li>
  <li>Border and background layers (paths)</li>
  </ol>
  
  <p>PDF layers without <code>useTemplate()</code> - top to bottom:</p>
  
  <ol>
  <li>Table/Content layers</li>
  <li>Border and background layers (paths)</li>
  </ol>
  
  <p>When disabling the layer group containing the PDF template in Illustrator, the borders and backgrounds become visible.</p>
  
  <p>Unfortunately we didn't find a way to put the PDF template layer group at the bottom of the stack so everything else renders above it. The only workaround we could come up with, was wrapping the <code>writeHTMLCell()</code> call in <code>startTemplate()</code> / <code>endTemplate()</code> and finishing up with <code>printTemplate()</code>:</p>
  
  <pre><code>$this-&gt;setSourceFile($filename); // /path/to/my/background.pdf
  $imported_page = $this-&gt;ImportPage(1);
  $this-&gt;useTemplate($imported_page);
  
  ...
  
  $html = '&lt;table style="border: 1px solid #000;"&gt;&lt;tr&gt;&lt;td style="background-color: #ff0000;"&gt;...&lt;/td&gt;&lt;/tr&gt;&lt;/table&gt;';
  
  $workaround_template = $this-&gt;startTemplate($w, $h);
  $this-&gt;writeHTMLCell(45, 25, 160, 29, $html); 
  $this-&gt;endTemplate();
  $this-&gt;printTemplate($workaround_template, $x, $y, $w, $h, 'T', 'L');
  </code></pre>
  
  <p>So out of curiosity: is this the only way to do it, or is there a way to put the PDF template at the bottom of all things to come?</p>
  
  <p>Thanks in advance!</p>