Print CSS: How to print an image only on the first page with fixed coordinates?

88 Views Asked by At

I have a xhtml document, which is rendered with openhtmltopdf into a pdf. The content of this document can vary, which results in a one or multi page pdf. I would like to print a logo always on the first page, at the exact coordinates of 20mm from top, 20mm from right.

Approach 1

This approach will print the image on each page:

.logo { 
  width: 100mm; 
  position: fixed; 
  right: 20mm; 
  top: 20mm; 
}

How can I prevent this from appearing on any page that is not the first?

Approach 2

I already tried it with the @page:first configuration:

@page :first { 
  @top-right { 
    background-image: url("logo.png"); 
    background-repeat: no-repeat;  
    background-size: contain; 
  }
}

The problem is that the logo has to be exactly at the desired coordinates, which is not possible with the page margin boxes in my understanding.

1

There are 1 best solutions below

1
obourgain On BEST ANSWER

You can fix both approaches.

Approach 1

Use position:absolute instead of position:fixed. This will make the image appear only once. The position is specified relative to the page area, so you have to deduct the page margin size. I don't know the default size of the margin with OpenHtmlToPdf, so you may want to set them.

Example:

@page{
    margin: 15mm;
}
.logo{
    position: absolute;
    right: 5mm;
    top: 5mm;
}

Approach 2

Use @top-right-corner instead of top-right, insert a div in this corner, with the image in it. You can then position the image with position:absolute.

@page:first {
    @top-right-corner {
        content: element(header);
    }
}
div.header-logo {
    position: running(header);
}
.logo{
    position: absolute;
    top:20mm;
    right:20mm;
}