Dompdf Watermark Implementation
November 10, 2024 ยท AI Conversations
### Step 1: Add the Watermark using Dompdf's Canvas
Here is an example of how to add a text watermark:
use DompdfDompdf;
use DompdfOptions;
// Initialize Dompdf
$options = new Options();
$options->set('isHtml5ParserEnabled', true);
$options->set('isRemoteEnabled', true); // Enable if you're using remote assets (e.g., images)
$dompdf = new Dompdf($options);
// Load HTML content
$html = '<h1>Sample PDF Content</h1><p>This is a PDF generated by Dompdf.</p>';
$dompdf->loadHtml($html);
// (Optional) Set paper size and orientation
$dompdf->setPaper('A4', 'portrait');
// Render the PDF
$dompdf->render();
// Add Watermark
$canvas = $dompdf->getCanvas();
$canvas->set_opacity(0.1); // Set transparency (0 to 1)
$canvas->text(50, 400, 'WATERMARK', 'Helvetica', 50, [0.85, 0.85, 0.85]);
// Output the PDF
$dompdf->stream('document.pdf', ['Attachment' => false]);
### Explanation
1. **Initialize Dompdf**:
– Create an instance of Dompdf and set options as needed.
– Enable remote assets if required using `$options->set('isRemoteEnabled', true);`.
2. **Load HTML content**:
– Use `$dompdf->loadHtml($html);` to load your content.
3. **Render the PDF**:
– Call `$dompdf->render();` to generate the PDF.
4. **Add Watermark**:
– Get the canvas using `$dompdf->getCanvas();`.
– Set the transparency with `$canvas->set_opacity(0.1);` (adjust between 0 and 1).
– Draw text or an image using `$canvas->text()` or `$canvas->image()`.
### Step 2: Adding an Image Watermark (Optional)
If you want to use an image as a watermark, replace the watermark text section with this:
$canvas = $dompdf->getCanvas();
$canvas->set_opacity(0.1);
$canvas->image('path/to/watermark.png', 50, 100, 500, 500);
– Adjust the path, position `(x, y)`, and size `(width, height)` as needed.
### Notes
– Ensure `isRemoteEnabled` is `true` if using external image URLs.
– You might need to adjust the coordinates based on your page size.
This method should work seamlessly with your WooCommerce setup, assuming you're using Dompdf for generating invoices, order confirmations, etc.