文字PDF转图片PDF,适合pdf防复制

完整代码已传至github平台:
https://github.com/yaunsine/text_pdf_to_image_pdf

分成两步操作:

1、将文字pdf输出成图片

2、将所有图片合成为pdf

将PDF文件输出为图片的形式
python 复制代码
"""
    pdf转图片
"""
def pyMuPDF_fitz(pdfPath, imagePath):
    startTime_pdf2img = datetime.datetime.now()  # 开始时间
    create_directory(".\\output_img")
    print("imagePath=" + imagePath)
    pdfDoc = fitz.open(pdfPath)
    for pg in range(pdfDoc.pageCount):
        page = pdfDoc[pg]
        rotate = int(0)
        # 每个尺寸的缩放系数为1.3,这将为我们生成分辨率提高2.6的图像。
        # 此处若是不做设置,默认图片大小为:792X612, dpi=96
        zoom_x = 1.33333333  # (1.33333333-->1056x816)   (2-->1584x1224)
        zoom_y = 1.33333333
        mat = fitz.Matrix(zoom_x, zoom_y).prerotate(rotate)
        pix = page.get_pixmap(matrix=mat, alpha=False)

        if not os.path.exists(imagePath):  # 判断存放图片的文件夹是否存在
            os.makedirs(imagePath)  # 若图片文件夹不存在就创建

        pix.save(imagePath + '/' + 'images_%s.png' % pg)  # 将图片写入指定的文件夹内

    endTime_pdf2img = datetime.datetime.now()  # 结束时间
    print('pdf2img时间=', (endTime_pdf2img - startTime_pdf2img).seconds)
将所有的图片合并成PDF
python 复制代码
"""
    合并图片成pdf
"""
def merge_img_to_pdf(path: str, name: str):
    create_directory(".\\output_pdf")
    img_open_list = []                                 # 创建打开后的图片列表
    for root, dirs, files in os.walk(path):
        for i in files:
            file = os.path.join(root, i)               # 遍历所有图片,带绝对路径
            img_open = Image.open(file)                # 打开所有图片
            if img_open.mode != 'RGB':
                img_open = img_open.convert('RGB')     # 转换图像模式
            img_open_list.append(img_open)             # 把打开的图片放入列表
    # pdf_name = name + '.pdf'                           # pdf文件名
    pdf_name = name
    img_1 = img_open_list[0]                           # 打开的第一张图片
    # 把img1保存为PDF文件,将另外的图片添加进来,列表需删除第一张图片,不然会重复
    img_open_list = img_open_list[1:]
    img_1.save(pdf_name, "PDF", resolution=100.0, save_all=True, append_images=img_open_list)
    print('转换成功!pdf文件在当前程序目录下!')
    clear_imgs(path)
相关推荐
十一.3661 分钟前
66-69 原型对象,toString(),垃圾回收
开发语言·javascript·原型模式
小小鱼儿飞2 小时前
QT音乐播放器18----新歌速递播放、隐藏顶部和底部工具栏、自定义ToolTips
开发语言·qt
穆雄雄2 小时前
Rust 程序适配 OpenHarmony 实践:以 sd 工具为例
开发语言·rust·harmonyos
0***142 小时前
Swift资源
开发语言·ios·swift
z***I3942 小时前
Swift Tips
开发语言·ios·swift
J***Q2922 小时前
Swift Solutions
开发语言·ios·swift
铅笔小新z2 小时前
C++入门指南:开启你的编程之旅
开发语言·c++
Gavin-Wang2 小时前
Swift + CADisplayLink 弱引用代理(Proxy 模式) 里的陷阱
开发语言·ios·swift
molunnnn7 小时前
第四章 Agent的几种经典范式
开发语言·python