Giordano Giordano - 2 months ago 21
CSS Question

How to divide a document in sections without showing the <h*> tags when using wkhtmltopdf?

I'm implementing a catalog using wkhtmltopdf.

In order to generate the table of contents I must place the tags in the document, as mentioned in the documentation:


The table of content is generated based on the H tags in the input
documents. First a XML document is generated, then it is converted to
HTML using XSLT.


For product design reasons I need to make it so that such strings are neither displayed nor they take space in the final PDF.

I tried to use absolute positioning and using the "transparent" color to hide the text, however sometimes this doesn't work well, since wkhtmltopdf excludes them from the toc. I guess that the webkit engine optimizes them out.

Is it possible to somehow "tag" the content instead of including the actual HTML tags?

Thanks

Answer

Ok, after quite a few attempts and testing I might have found a solution for this problem.

Mark your sections with the H tags. For example:

<h1 class="section-marker">Section title</h1>
[... content]
<h2 class="section-marker">Sub-Section title</h2>
[... content]
<h3 class="section-marker">Sub-Sub-Section title</h3>
[... content]

To make sure that such tags are not visible and don't occupy any space (and wkhtmltopdf still catches them) you can use these CSS rules:

.section-marker {
    width: 2px !important;
    height: 2px !important;
    padding: 0 !important;
    overflow: hidden !important;
    opacity: 0 !important;
    font-size: 1px;
    float: left;
}

UPDATE: below my original answer, which was suboptimal. After some tests I adapted @lorenzo-s css solution to a more "universal" version that should always work (@lorenzo-s's solution was not working in my case) and doesn't require any "section-separator".

To make sure that such tags are not visible and don't occupy any space (and wkhtmltopdf still catches them) you can use these CSS rules:

.section-marker {
    font-size: 0;
    color: transparent;
    float: left;
  }

I noticed one small problem though. If 2 H tags are adjacent, wkhtmltopdf fails to recognize them as separate markers (perhaps because of the float property, I'm not sure).

Something like this will not work properly:

<h1 class="section-marker">Section title</h1>
<h2 class="section-marker">Sub-Section title</h2>

You need to change it to this:

<h1 class="section-marker">Section title</h1>
<br class="section-separator">
<h2 class="section-marker">Sub-Section title</h2>

with these rules (which I derived from this answer and some trial/error attempts):

br.section-separator {
  content:' ';
  display: block;
  margin-top: 2px;
  line-height:2px;
}