Customize Header And Footer Of Your PDFs

Fri 18 March 2011

The Pdfcrowd API has supported a customized page footer since its early beta stage. However, the functionality was quite limited since it allowed to insert plain text only.

Based on the feedback from our users, we have implemented an advanced solution recently which allows you to place HTML code inside a header and a footer. In this post we will show how you can make use of this new feature in your applications.

Step-By-Step Example

We will use Python 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 object and setting the page format to Letter:

client = pdfcrowd.Client("***", "***")
client.setPageWidth("8.5in")
client.setPageHeight("11in")

The next step is to design our HTML header and footer. We can use the %p, %n, and %u variables anywhere in the HTML code. The variables will be expanded to the current page number, the total number of pages, and the URL of the original page respectively.

Now that we have the header and footer, we can either load it via HTTP:

client.setHeaderUrl("http://pdfcrowd.com/blog/static/static-html/header.html")
client.setFooterUrl("http://pdfcrowd.com/blog/static/static-html/footer.html")

Or we can write the HTML code inline in our application:

client.setHeaderHtml('<div> ... </div>')
client.setFooterHtml('<table> ... </table>')

The header and footer are placed inside the top and bottom margins. The following line will make them 0.7' tall.

client.setVerticalMargin("0.7in")

Let's finish our application and request the API to convert our test page to PDF.

pdf = client.convertURI('http://pdfcrowd.com/static/misc/lorem.html')

You can check out the result here.

Notes

  • The converted web page, the header and the footer are treated as independent HTML documents, so for instance CSS styles are not shared.
  • The API hard-wires <body style="margin: 0"> for the header/footer HTML code.
  • The following figure depicts the page setup:
    Margins

Try Out The API

You can sign up for a free trial account, download the API client library for your favorite language and start creating PDF from web pages or raw HTML in just a few minutes. Pdfcrowd supports PHP, Java, Ruby, Python, .NET, node.js, Bash, and HTTP POST.

links

social