python创建pdf水印,希望根据文本长度调整水印字体大小,避免超出页面

为了根据文本长度动态调整水印字体大小,可以先测量文本长度,然后根据页面宽度和高度动态计算合适的字体大小。以下是修改后的代码:

python 复制代码
from reportlab.pdfgen import canvas
from reportlab.lib.pagesizes import letter
from reportlab.pdfbase.ttfonts import TTFont
from reportlab.pdfbase import pdfmetrics
from reportlab.lib import colors

def create_watermark(watermark_text, watermark_pdf_path):
    chinese_font_path = "MSYH.TTC"  # 替换为中文字体路径
    pdfmetrics.registerFont(TTFont("微软雅黑", chinese_font_path))  # 注册字体
    c = canvas.Canvas(watermark_pdf_path, pagesize=letter)
    width, height = letter

    # Function to calculate font size based on text length and page size
    def calculate_font_size(text, max_width, max_height):
        # Start with a large font size
        font_size = 60
        while font_size > 10:  # Minimum font size to avoid being too small
            c.setFont("微软雅黑", font_size)
            text_width = c.stringWidth(text, "微软雅黑", font_size)
            if text_width <= max_width * 0.8:  # Allow some margin
                return font_size
            font_size -= 2  # Decrease font size step by step
        return font_size

    # Calculate maximum diagonal space for the rotated text
    max_diagonal_space = ((width ** 2 + height ** 2) ** 0.5) * 0.7  # Allow some margin
    font_size = calculate_font_size(watermark_text, max_diagonal_space, max_diagonal_space)

    # Set transparency (optional)
    c.setFillColor(colors.grey, alpha=0.3)

    # Rotate the canvas to draw diagonal text
    c.saveState()
    c.translate(width / 2, height / 2)
    c.rotate(45)
    c.setFont("微软雅黑", font_size)
    c.drawCentredString(0, 0, watermark_text)
    c.restoreState()

    c.save()

# 示例调用
create_watermark("这是一个水印", "watermark.pdf")

修改点:

  1. 添加 calculate_font_size 函数,用于根据文本长度动态计算字体大小。
  2. 将文本限制在页面对角线的 70% 内,以保证水印不会超出页面。
  3. 在循环中逐步减小字体大小,直到文本宽度符合要求。

运行该代码时,可以根据不同长度的水印文本动态调整字体大小,从而适配页面尺寸。

相关推荐
☼←安于亥时→❦19 小时前
PyTorch 梯度与微积分
人工智能·pytorch·python
程序员三藏20 小时前
2025最新的软件测试面试八股文(800+道题)
自动化测试·软件测试·python·功能测试·测试工具·面试·职场和发展
Pocker_Spades_A20 小时前
Python快速入门专业版(二十三):for循环基础:遍历字符串、列表与range()函数(计数案例)
python
闲人编程20 小时前
图像去雾算法:从物理模型到深度学习实现
图像处理·人工智能·python·深度学习·算法·计算机视觉·去雾
Kyln.Wu21 小时前
【python实用小脚本-211】[硬件互联] 桌面壁纸×Python梦幻联动|用10行代码实现“开机盲盒”自动化改造实录(建议收藏)
开发语言·python·自动化
Ms_Big1 天前
ppliteseg改rknn,部署在嵌入式板,加速模型
人工智能·python·深度学习
折翼的恶魔1 天前
数据分析:合并
python·数据分析·pandas
百锦再1 天前
在 CentOS 系统上实现定时执行 Python 邮件发送任务
java·linux·开发语言·人工智能·python·centos·pygame
I'm a winner1 天前
第五章:Python 数据结构:列表、元组与字典(二)
数据结构·python
番薯大佬1 天前
Python学习-day8 元组tuple
java·python·学习