日常办公

openpyxl

import openpyxl

wb = openpyxl.load_workbook('./1.xlsx')

sheet = wb.active
# 添加超链接
sheet.cell(2, 2).value = '百度'
sheet.cell(2, 2).hyperlink = ('https://www.baidu.com')
# 添加本地跳转链接
sheet.cell(3, 2).value = 'bbc.xlsx'
sheet.cell(3, 2).hyperlink = './b.xlsx'

wb.save('./2.xlsx')

docx2pdf

from docx2pdf import convert

convert("input.docx", "output.pdf")

docx

from docx import Document
from pathlib import Path
from docx import shared
from docx.shared import RGBColor

doc = Document(Path.cwd().joinpath("test/xxx.docx"))
# 获取段落
p = doc.paragraphs
# 输出段落中的文字
for t in p:
    print(t.text)
# 新增段落,填入内容
new_p = doc.add_paragraph('段落内容')
# 追加段落内容
new_p = new_p.add_run('再加点段落内容')
# 设置字体
new_p.font.name = '仿宋'
# 设置下划线
new_p.font.underline = True
# 设置颜色
new_p.font.color.rgb = RGBColor(255, 128, 128)
# 添加图片
new_p.add_picture(str(Path.cwd().joinpath("img/a1.jpg")), width=shared.Inches(1))
# 保存
doc.save(Path.cwd().joinpath("test/xxx.docx"))

pdf

PyPDF2

PyPDF2库可以实现很多PDF相关的功能,如:设置密码、插入新的页面、旋转PDF、设置水印、去除水印等

设置PDF水印:先创建一个水印文件,word -> 设计 -> 水印 -> 另存为pdf文件


from PyPDF2 import PdfFileReader, PdfFileWriter


def watermark(pdf_content, water_mark, pdf_result):
    # 准备合并后的文件对象
    pdf_result_writer = PdfFileWriter()

    # 打开水印文件
    with open(water_mark, 'rb') as f_mark:
        water_mark_file = PdfFileReader(f_mark, strict=False)

        # 打开需要增加水印的文件
        with open(pdf_content, 'rb') as f_content:
            pdf_file = PdfFileReader(f_content, strict=False)
            water = water_mark_file.getPage(0)
            for i in range(pdf_file.getNumPages()):
                # 从第一页开始处理
                page = pdf_file.getPage(i)
                # 合并水印和当前页
                page.mergePage(water)
                # 将合并后的PDF文件写入新的文件
                pdf_result_writer.addPage(page)

                # 写入新的PDF文件
                with open(pdf_result, "wb") as f:
                    pdf_result_writer.write(f)


watermark('./input_file.pdf', './mark_file.pdf', './result_file.pdf')

results matching ""

    No results matching ""