link

PrintCSS

I want to render the same HTML and CSS with different data. Can I do that?

Yes! We support that via the templating engine Twig and an additional data key within the requests body JSON. That data key needs to contain an array of your data objects. If you have only one data object, it still needs to be in an array.

Widespread examples for such data-driven PDF exports are bills, reports, or business cards. In the JSON body below, you see how to create business cards for 3 different people. The HTML contains placeholders like {{FirstName}} which appear as keys in the single data objects. For each data object, the HTML gets rendered once.

{
    "css": "@page { size: 3.5in 2in; marks: crop; bleed: 0.125in; margin: 0.25in; } @page back { background: rgb(188,11,6); background-image: url(https://www.html2pdf.guru/assets/img/html2pdf.guru.png); background-position: center; background-repeat: no-repeat; margin: 0; } body { font-size: 10pt; } b { color: rgb(188,11,6); font-size: 1.5rem; } .head { display: inline-block; margin-bottom: .5rem; } .foot { display: inline-block; margin-top: .75rem; border-left: .25rem solid rgb(188,11,6); padding-left: .5rem; } .break { page: back; page-break-after: always; break-after: always; }",
    "html": "<div class='break'></div><span class='head'><b>{{FirstName}} {{LastName}}</b><br />{{Title}}</span><br />{{EMail}}<br />Mobile {{Phone}}<br />www.example.com<br /><span class='foot'>Example Company<br />Busystreet 5 &amp;amp;amp;amp;amp;middot; 00001 Gotham</span>",
    "data": [
        {"FirstName": "Fabien", "LastName": "Sample", "Title": "Senior Developer", "EMail": "f.sample@example.com", "Phone": "+49 1234 4444 5555"},
        {"FirstName": "Martin", "LastName": "Muster", "Title": "Junior Developer", "EMail": "m.mustermann@example.com", "Phone": "+49 1234 4444 5566"},
        {"FirstName": "Andreas", "LastName": "Doe", "Title": "CFO", "EMail": "a.doe@example.com", "Phone": "+49 1234 4444 5577"}
    ]
}

To send the request to our API now, you need to subscribe to a plan on RapidAPI. With this, you get the API key that is required to authenticate with our REST service. How to send a request you can see in the "How to create a PDF from my HTML and CSS Code?" article.

In the attached PDF below, you can see how this JSONs rendering result looks like.

3 business cards (PDF, 34.13 KB)