Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MPdf - Full page size image, but only for single page

Tags:

mpdf

I know there are similar questions, but non of them solve my problem. What i want to do with mPDF is the following:

Page 1: Text for item 1
Page 2: Full width and height image to cover the page with an image of item 1
Page 3: Text for item 2
Page 4: Full width and height image to cover the page with an image of item 2
...

The following code stretches an image in the way, I want to achieve:

    body {
        background-image:url("image1.jpg");
        background-image-resize: 5;
        background-position: top center;
    }

But this results to set the image on EVERY page (i know, its the body element). So i tried the following:

<div style='
        position: absolute;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
        background-image:url("image1.jpg");
        background-image-resize: 5;
        background-position: top center;
    '></div>

But that is not working. So i tried the same code, just with an color, instead an image:

    <div style='
        position: absolute;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
        background: #F00;
        '>
    </div>
    <div style="page-break-before: always;"></div>

And this is working. The whole page is red. So how to achive the same with an image?

Any ideas?

like image 724
bernhardh Avatar asked Oct 11 '25 18:10

bernhardh


2 Answers

After a lot of tryouts, I found out, that the easist way to do this, is just to split up the HTML code into separate parts and insert them with separate WriteHtml calls. For example:

// Create object
$mpdf = new \mPDF('utf-8');

// Create first text page
$mpdf->WriteHTML('<p>Text for item 1</p>');

// Add a new page with the image
$mpdf->AddPage();
$mpdf->WriteHTML("<html><body style='background-image:url(\"image1.jpg\"); background-image-resize: 5; background-position: top center;'></body></html>");


// Create second page
$mpdf->AddPage();
$mpdf->WriteHTML('<p>Text for item 1</p>');

...
like image 146
bernhardh Avatar answered Oct 16 '25 06:10

bernhardh


Size constraint : When writing HTML, image size is automatically constrained to current margins and page position. An extra parameter added to end of the Image() function allows you to override this:

<?php
// the last "false" allows a full page picture
$mpdf->Image('files/images/frontcover.jpg', 0, 0, 210, 297, 'jpg', '', true, false);

This is useful for e.g. a cover page for your document.

This can be achieved using HTML and CSS like this:

<div style="position: absolute; left:0; right: 0; top: 0; bottom: 0;">
    <img src="/files/images/frontcover.jpg" 
         style="width: 210mm; height: 297mm; margin: 0;" />
</div>

See https://mpdf.github.io/what-else-can-i-do/images.html#size-constraint for more info.

like image 32
Sunchock Avatar answered Oct 16 '25 07:10

Sunchock