首页 > 编程语言 >Python 在PDF中生成水印

Python 在PDF中生成水印

时间:2023-11-16 14:11:19浏览次数:61  
标签:Canvas Python 水印 pdf PDF page

前言

在PDF中插入水印是比较常用的一种功能。一般在生成比较重要的,或者需要注明版权、作者的文档时使用比较多。

这里我将分享一个通过python代码为PDF文档添加水印的办法(包括文本水印和图像水印)。这种方法也适用于批量添加水印的情况。

所需工具:

这个方法将用到以下程序和组件

下载链接:Spire.PDF for Python

试用版链接:30天免费试用

安装方法:

首先,在VS Code中安装Spire.PDF for Python和plum-dispatch v1.7.4。

在这之前请先确认是否已经安装Python

安装好后,可以直接进行以下步骤:

  1. 打开VS Code,在中搜索到Python并安装。
  2. 依次选择Explorer - NO FOLRDER OPENED- Open Folder
  3. 选择一个文件夹,然后在里面创建一个“ .py ”文件。
  4. 创建后,点击Terminal- New Terminal
  5. 输入命令: pip install Spire.PDF

示例代码

PDF中生成文本水印

完整代码:

from spire.pdf import *
from spire.pdf.common import *
import math

#创建PdfDocument类的对象并加载一个PDF文档
pdf = PdfDocument()
pdf.LoadFromFile("C:/Users/Administrator/Desktop/Sample.pdf")

#创建一个PdfTrueTypeFont类的对象
font = PdfTrueTypeFont("Arial", 48.0, 0, True)

#设置水印文本
text = "CONFIDENTIAL"

#计算水印位置
set1 = float (font.MeasureString(text).Width * math.sqrt(2) / 4)
set2 = float (font.MeasureString(text).Height * math.sqrt(2) / 4)

#遍历所有页面
for i in range(pdf.Pages.Count):

    #获取页面
    page = pdf.Pages.get_Item(i)

    #设置水印透明度
    page.Canvas.SetTransparency(0.5)

    #将页面坐标系平移到指定位置
    page.Canvas.TranslateTransform(page.Canvas.Size.Width / 2 - set1 - set2, 
                                   page.Canvas.Size.Height / 2 + set1 - set2)

    #逆时针旋转坐标系45度
    page.Canvas.RotateTransform(-45.0)

    #绘制水印
    page.Canvas.DrawString(text, font, PdfBrushes.get_LightPink(), 0.0, 0.0)

#保存结果文档
pdf.SaveToFile("C:/Users/Administrator/Desktop/TextWatermark.pdf")
pdf.Close()

代码解释:

以上代码中,主要用到的是PdfPageBase.Canvas.DrawString()方法来绘制水印。绘制时,我们可以根据需求,利用PdfCanvas下的方法来设置水印的大小,位置,透明度,旋转角度,颜色等。具体解释可以参考一下代码注释。

水印效果如图所示:

PDF中生成图片水印

完整代码:

from spire.pdf import *
from spire.pdf.common import *

#创建PdfDocument类的对象并加载一个PDF文档
pdf = PdfDocument()
pdf.LoadFromFile("C:/Users/Administrator/Desktop/Sample.pdf")

#加载图片
image = PdfImage.FromFile("C:/Users/Administrator/Desktop/image.png")

#获取图片的高和宽
imageWidth = float(300)
imageHeight = float(300)

#遍历所有页面
for i in range(pdf.Pages.Count):

    #获取页面
    page = pdf.Pages.get_Item(i)

    #设置水印透明度
    page.Canvas.SetTransparency(0.3)

    #获取页面的高和宽
    pageWidth = page.ActualSize.Width
    pageHeight = page.ActualSize.Height

    #在页面绘制图片水印
    page.Canvas.DrawImage(image, pageWidth/2 - imageWidth/2, pageHeight/2 - imageHeight/2, imageWidth, imageHeight)

#保存结果文档
pdf.SaveToFile("C:/Users/Administrator/Desktop/ImageWatermark.pdf")
pdf.Close()

代码解释:

与添加文本水印的代码相似,绘制时也可以根据需求,利用PdfCanvas下的方法来设置水印的大小,位置等信息。但在绘制时,使用的是PdfPageBase.Canvas.DrawImage()方法来将加载的图片作为水印添加到PDF页面中。详细解释参考代码注释。

水印效果如图所示:

如果需要其他的示例代码的话,可以直接下载这个库,里面包含了大部分比较常用的demo。

标签:Canvas,Python,水印,pdf,PDF,page
From: https://www.cnblogs.com/Gia-/p/17836083.html

相关文章

  • ReportViewer (RDLC)导出Excel或PDF无法打开问题
    WebForms的ReportViewer提供了导出成EXCEL或者PDF的报表。(ReportingServices)但是导出时报表会另存为.xls[1]或者.pdf[1],导致文件无法直接打开。这需要给ReportViewer设定一个DisplayName解决。ReportViewer1.LocalReport.DisplayName......
  • Only export to PDF format from ReportViewer add-in
    Hiall,"OnlyexporttoPDFformatfromReportVieweradd-in"...Isthispossible?Rightnowthereportviewerhastwooptionsofexportingthecurrentreport-ExcelandPDF...IsitpossibletohavePDFastheonlyoption.Idon'twantmyclient......
  • 1-3 Python基础语法
    ​ 目录1.循环语句1.1循环语句基本使用1.2综合案例1.3break1.4continue1.5whileelse2.字符串格式化2.1%2.1.1基本格式化操作2.1.2百分比2.2format(推荐)2.3f3.运算符3.1运算符优先级3.2判断题 1.循环语句while循环for循环```while条件: ......
  • 1-2 Python基础语法
    ​ 1.编码计算机所有的数据本质上是以0和1的组合来存储在计算机中会将中文转换为0101010100最终存储到硬盘上计算机中有一个编码的概念(也就是密码本)  武  ->   0111111100011010010110110在计算机中有很多种编码每种编码都有自己的一套密码本,都维护这......
  • python3 json.dumps(OrderDict类型) 报错:TypeError: Object of type datetime is not
    chatgpt给出的解决方案,在json.dumps()函数调用中传入default参数来指定如何处理datetime对象importjsonfromdatetimeimportdatetimedefdatetime_handler(obj):ifisinstance(obj,datetime):returnobj.__str__()#另一种处理,转换为自定义格式化字符串......
  • [940] Create a progress bar in Python
    TocreateaprogressbarinPython,youcanusethetqdmlibrary,whichisapopularlibraryforaddingprogressbarstoyourloops.Ifyouhaven'tinstalledityet,youcandosousing:pipinstalltqdmHere'sasimpleexampleofhowtousetqd......
  • blob:http Status Code: 206 Partial Content 视频去水印
       从视频中删除水印-免费擦除徽标和日期https://online-video-cutter.com/cn/remove-logo#google_vignetteStatusCode:206PartialContentblob:https://online-video-cutter.com/461afc6a-9e64-45ca-9276-4f9489bde7f7  视频去水印先上传再选区域  ......
  • 标量衍射计算指南(python 实现)
    标量衍射计算指南(python实现)Introduction本文的目的总结一些标量衍射的计算方法,并讨论讨论他们的适用条件。代码和例子在:https://github.com/zhemglee/Scalardiffraction需要的预备知识:涉及的数理知识并不高深,主要是线性系统和傅里叶变换(离散傅里叶变换)的基础知识,当然还有光学。涉......
  • Python类对象:属性、继承与多继承
    在Python中,类是创建对象的蓝图。类定义了如何创建对象,并决定了这些对象的属性和行为。本博客将深入探讨Python类对象的属性、继承以及多继承。属性属性是类的特性,它定义了对象的状态。每个对象都有其自己的属性副本。python复制代码classPerson:def__init__(self,name,a......
  • python深度学习——一个简单的全连接神经网络,预测mnist手写数字
    代码来自《python深度学习》第二章:fromtensorflow.keras.datasetsimportmnistfromtensorflowimportkerasfromtensorflow.kerasimportlayers(train_images,train_labels),(test_images,test_labels)=mnist.load_data()print(train_images.shape)print(len(trai......