完整页面大小的图像,但仅适用于单个页面

  • 本文关键字:图像 适用于 单个页 mpdf
  • 更新时间 :
  • 英文 :


我知道有类似的问题,但没有一个能解决我的问题。我想用mPDF做的事情如下:

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
...

下面的代码以我想要实现的方式扩展图像:

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

但是这导致在每个页面上设置图像(我知道,它的body元素)。所以我尝试了以下操作:

<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>

但这不起作用。所以我尝试了相同的代码,只是用一个颜色,而不是一个图像:

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

这是有效的。整页都是红色的。那么如何在图像上实现同样的效果呢?

任何想法?

经过多次尝试后,我发现,最简单的方法是将HTML代码分成单独的部分,并使用单独的WriteHtml调用插入它们。例如:

// 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>');
...

尺寸约束:在编写HTML时,图像大小会自动约束到当前页边距和页面位置。添加到Image()函数末尾的一个额外参数允许您覆盖这个:

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

这是很有用的,例如你的文档的封面。

这可以使用HTML和CSS实现,如下所示:

<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>

我试过Sunchock的答案,并没有为我工作,但经过一些修改,我终于创建了一个完整的图像封面(第一个PDF页)。

下面是代码。基本上,我删除了img标签,并将大小样式移动到div。最后在html的样式中(也许可以作为div中的内联样式)添加了图像作为背景。您可以在mpdf文档中找到有关background-image-resize标签的更多信息

<style>
#cover {
  background-image: url("http://php72.com/resources/image.png");
  background-image-resize: 6;
}
</style>
<div id="cover" style="position: absolute; left:0; right: 0; top: 0; bottom: 0; width: 210mm; height: 297mm;">
</div>

相关内容

最新更新