In this tutorial you will learn how to add header and footer to PDF created by Pdfcrowd API. We will use PHP for illustrative purposes, but the code would be essentially the same in all languages the API supports.
Let's start with instantiating the Pdfcrowd client and setting the page format to Letter:
$client = new \Pdfcrowd\HtmlToPdfClient($user_name, $api_key); $client->setPageSize('Letter');
The next step is to design our HTML footer and header. We can use special CSS classes that will be expanded as follows:
pdfcrowd-page-count- the total page count of printed pages
pdfcrowd-page-number- the current page number
pdfcrowd-source-url- the source URL of the main document
The footer HTML containing the current page number and the total number of pages can look like this:
<div style="text-align: right; background-color: gray;"> Page <span class="pdfcrowd-page-number"></span> of <span class="pdfcrowd-page-count" style="font-weight: bold"></span> pages </div>
Here is a preview of our footer:
The header HTML containing a logo image and the link to the converted document can look as follows:
<div style="text-align: center; padding: 10pt 0;"> <img src="https://static.htmltopdf.dev/images/icon2.svg" style="height: 0.2in; margin-right: 24pt;" alt="the logo"> <a class="pdfcrowd-source-url" data-pdfcrowd-placement="href-and-content"></a> </div>
data-pdfcrowd-placement attribute set to
href-and-content determines that the link will be assigned to the href attribute and also to the element's text content.
Here is a preview of our header:
Call the API
Now we can pass our header and footer to the API:
$client->setHeaderHtml('<div> ... </div>'); $client->setFooterHtml('<div> ... </div>');
Or we can load them via HTTP:
The following code will make them 0.7' tall:
Let's finish our application and request the API to convert our test page to PDF.
You can find the complete code and the resulting PDF in the API Playground. The API playground also shows the code in other supported languages.
- Page number can be formatted in different ways: arabic, roman, eastern-arabic, bengali, devanagari, thai, east-asia and chinese-formal. The desired format is defined by the attribute
- Pdfcrowd provides other API methods and special CSS classes so that you can create advanced documents with e.g. different header on the first page and last page or different header for single page and multipage output.
- The footer and header height are independent of the page margins, the following figure depicts the page layout: