How to add a watermark on a PDF using TCPDF

How to add a watermark on a PDF using TCPDF

Configuring a "watermark" on your PDF generated by TCPDF could be tricky if you try to do it by yourself without deep understanding of the library. Fortunately, with the help of the original examples of TCPDF, it's possible to render a background image on any page of your PDF that can simulate a watermark.

1. Override original Header method of TCPDF

The first thing that you need to do, is to override the default function Header of TCPDF. This approach works pretty well, however you will be sacrificing the original header data of your pdf, which means that the original method setHeaderData won't have effect anymore:

// This won't work anymore if you decide to add a watermark
$pdf->SetHeaderData(PDF_HEADER_LOGO, PDF_HEADER_LOGO_WIDTH, PDF_HEADER_TITLE.' 006', PDF_HEADER_STRING);

So working with this approach is recommendable only if your "watermark" plays as background of the entire PDF e.g includes header, watermark and footer. If you still want to proceed, then start by overriding the Header method of the TCPDF Class.

This can be done by simply creating a new class wherever you want and with the name you want (as long as you can use it later where you want) that extends the TCPDF class. By doing this, you will need to store some original values of the PDF in order to restore them after you draw the image using the Image method. Theoretically, you can simply copy the following example and change the path to the image that will be used as watermark, however you may want to change the margins and coordinates where the image will be rendered:

class MyCustomPDFWithWatermark extends TCPDF {
    public function Header() {
        // Get the current page break margin
        $bMargin = $this->getBreakMargin();

        // Get current auto-page-break mode
        $auto_page_break = $this->AutoPageBreak;

        // Disable auto-page-break
        $this->SetAutoPageBreak(false, 0);

        // Define the path to the image that you want to use as watermark.
        $img_file = './your-watermark.jpg';

        // Render the image
        $this->Image($img_file, 0, 0, 223, 280, '', '', '', false, 300, '', false, false, 0);

        // Restore the auto-page-break status
        $this->SetAutoPageBreak($auto_page_break, $bMargin);

        // Set the starting point for the page content
        $this->setPageMark();
    }
}

2. Use new class instead of TCPDF

As next, you only need to generate your PDF in the same way you do always except for the instance of TCPDF that you will use. Use the overrided class instead of the original to create your PDF instance:

// If you want to use it without Watermark
// $pdf = new TCPDF(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);

// To use with watermark, use the overrided class that expects the same parameters that TCPDF
// because the class simply extends the original
$pdf = new MyCustomPDFWithWatermark(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);

// Rest of your code here
// $pdf->AddPage();

And that's it, now the image defined in the MyCustomPDFWithWatermark method should be rendered behind your content without any visual obstruction.

Full example

In this example, our watermark for the PDF will be the following (note that this is not the original size of the image, the original size is the same as the size of the impression 1763x2162):

TCPDF Watermark

And our code to generate the PDF is the following:

<?php 

// Create a new PDF but using our own class that extends TCPDF
$pdf = new MyCustomPDFWithWatermark(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);

// set document information
$pdf->SetAuthor('Our Code World');
 
// set default monospaced font
$pdf->SetDefaultMonospacedFont(PDF_FONT_MONOSPACED);
// set default header data
$pdf->SetHeaderData(PDF_HEADER_LOGO, PDF_HEADER_LOGO_WIDTH, PDF_HEADER_TITLE.' 006', PDF_HEADER_STRING);
// set margins
$pdf->SetMargins('10', '40', '10');
$pdf->SetAutoPageBreak(TRUE, PDF_MARGIN_BOTTOM);
$pdf->SetFont('dejavusans', '', 10);

// Add a page
$pdf->AddPage();
 
// Create some HTML content
$html = '<h1>HTML Example</h1>
Some special characters: &lt; € &euro; &#8364; &amp; è &egrave; &copy; &gt; \\slash \\\\double-slash \\\\\\triple-slash
<h2>List</h2>
List example:
<ol>
    <li><b>bold text</b></li>
    <li><i>italic text</i></li>
    <li><u>underlined text</u></li>
    <li><b>b<i>bi<u>biu</u>bi</i>b</b></li>
    <li><a href="http://www.tecnick.com" dir="ltr">link to http://www.tecnick.com</a></li>
    <li>Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo.<br />Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt.</li>
    <li>SUBLIST
        <ol>
            <li>row one
                <ul>
                    <li>sublist</li>
                </ul>
            </li>
            <li>row two</li>
        </ol>
    </li>
    <li><b>T</b>E<i>S</i><u>T</u> <del>line through</del></li>
    <li><font size="+3">font + 3</font></li>
    <li><small>small text</small> normal <small>small text</small> normal <sub>subscript</sub> normal <sup>superscript</sup> normal</li>
</ol>
<dl>
    <dt>Coffee</dt>
    <dd>Black hot drink</dd>
    <dt>Milk</dt>
    <dd>White cold drink</dd>
</dl>
<div style="text-align:center">IMAGES
</div>';

// output the HTML content
$pdf->writeHTML($html, true, false, true, false, '');

// output some RTL HTML content
$html = '<div style="text-align:center">The words &#8220;<span dir="rtl">&#1502;&#1494;&#1500; [mazel] &#1496;&#1493;&#1489; [tov]</span>&#8221; mean &#8220;Congratulations!&#8221;</div>';
$pdf->writeHTML($html, true, false, true, false, '');

// test some inline CSS
$html = '<p>This is just an example of html code to demonstrate some supported CSS inline styles.
<span style="font-weight: bold;">bold text</span>
<span style="text-decoration: line-through;">line-trough</span>
<span style="text-decoration: underline line-through;">underline and line-trough</span>
<span style="color: rgb(0, 128, 64);">color</span>
<span style="background-color: rgb(255, 0, 0); color: rgb(255, 255, 255);">background color</span>
<span style="font-weight: bold;">bold</span>
<span style="font-size: xx-small;">xx-small</span>
<span style="font-size: x-small;">x-small</span>
<span style="font-size: small;">small</span>
<span style="font-size: medium;">medium</span>
<span style="font-size: large;">large</span>
<span style="font-size: x-large;">x-large</span>
<span style="font-size: xx-large;">xx-large</span>
</p>';

$pdf->writeHTML($html, true, false, true, false, '');

// Close and output PDF document
$pdf->Output('example_pdf_ocw.pdf', 'I');

Running the code will generate the following PDF:

TCPDF With Watermark

Pretty awesome and easy right? Happy coding !

This could interest you

Become a more social person