You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在WeasyPrint中设置页面居中的斜向水印?

在WeasyPrint生成的PDF中实现居中斜向水印

你之前的问题出在使用了@bottom-right这个页边距固定区域,它的位置被限定在页面右下角,transform-origin仅相对于该小区域生效,自然无法让水印居中到整个页面。以下是两种可靠的解决方案:

方案1:使用固定定位的页面元素(推荐,直观易维护)

在HTML中添加一个水印容器,通过CSS固定定位让它覆盖整个页面,再用Flex布局实现文本居中,最后旋转文本:

<!-- 在HTML的<body>中添加水印元素 -->
<div class="watermark"></div>

对应的CSS:

@page {
  size: A3 portrait;
  margin: 47.5mm 0mm 27.5mm 0mm;

  @bottom-center {
    content: counter(page);
    height: 15mm;
  }

  /* 保留你原有的其他页边距区域样式 */
}

.watermark {
  /* 固定定位确保每页都显示水印 */
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  /* Flex布局实现内容居中 */
  display: flex;
  align-items: center;
  justify-content: center;
  /* 避免干扰页面内容交互(PDF中可忽略,但保持规范) */
  pointer-events: none;
  /* 放在页面内容下方 */
  z-index: -1;
}

.watermark::after {
  content: "Hello world!";
  color: rgba(0, 0, 0, 0.516);
  font-size: 48px;
  font-weight: bold;
  /* 旋转文本 */
  transform: rotate(-45deg);
  /* 防止文本换行 */
  white-space: nowrap;
}

方案2:纯CSS @page伪元素实现

无需修改HTML,直接通过@page的:before伪元素生成水印,利用绝对定位和位移实现居中:

@page {
  size: A3 portrait;
  margin: 47.5mm 0mm 27.5mm 0mm;

  @bottom-center {
    content: counter(page);
    height: 15mm;
  }

  /* 生成居中斜向水印 */
  &:before {
    content: "Hello world!";
    /* 相对于整个页面定位 */
    position: absolute;
    top: 50%;
    left: 50%;
    /* 先位移到中心,再旋转 */
    transform: translate(-50%, -50%) rotate(-45deg);
    color: rgba(0, 0, 0, 0.516);
    font-size: 48px;
    font-weight: bold;
    white-space: nowrap;
    width: 100%;
    text-align: center;
  }

  /* 保留你原有的其他页边距区域样式 */
}

关键说明

  • 两种方案都基于覆盖整个页面的定位范围,而非页边距的固定小区域,因此能真正实现页面中心对齐。
  • transform: translate(-50%, -50%)是实现元素自身居中的核心,它会将元素的中心点移动到页面的中心位置,再旋转就不会偏移。

内容的提问来源于stack exchange,提问作者Prashant Kumar

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.23 05:34:58