Adding a Watermark with WKHTMLTOPDF

September 5th, 2018 / by api2pdf /

Introduction

If you are on this article, you already know what a watermark is, but just to be sure, it is a way of adding an image to a document to show where it was generated from or to avoid tampering for some reason.  A common use of watermarking is to add the word DRAFT to a document.  It turns out adding a watermark to your PDF document using WKHTMLTOPDF is something a lot of developers struggle with.  In fact I did a quick search on Google to see if anyone solved this.

 

Create the Image File

To add a watermark to the document we will make use of the body class and add a background using CSS.  The trick with WKHTMLTOPDF is to use the correct size image.  In our case we want to show the word DRAFT one time across the middle of each page of the document.

  1. The default DPI (dots per inch) is 96
  2. The default page size is A4 which is approximately 8″ by 11″
  3. Thus our image should be  768 px wide by 1056 px tall
  4. Our image should have a transparent background
  5. Here is the resulting picture.

Use CSS to Add it to the Background

There are many ways to add an image to the background.  In our case will use following CSS

<style>
body {
background: url('https://api2pdf.wpenginepowered.com/wp-content/uploads/2018/09/draft.png');
background-repeat: repeat-y;
background-position: center;
background-attachment: fixed;
background-size: 100%;
}
</style>

See it Live

  1. Get your API Key
  2. Use your API Key in our Playground with this Sample
Tags: , , , , , , , , , , ,

Comments are closed.