python-docx处理word文件指定页面批量打印

python docx处理word文档中表格合并问题 #问题描述 python中用docx库读取word文件,若word文件中包含合并的表格表格 则通过docx读取显示: file = docx.Document(path) for table in file.tables: for row in table.rows: for cell in row.cells: print(cell.text) ... 阅读详情

需求如下:word文件670份,每份8-17页不等,要求奇数页打-5至-1页(两张),偶数页的文件打后4页(两张)。最终查到解决方案如下:
(1)word文件的docx格式先转为pdf格式,防止在分页时出现错误;
(2)pdf格式文件按奇偶数页不同分为两大类,放入不同文件夹;
(3)使用截取页数,偶数页截后4页,奇数页截倒数5至1页;
(4)使用批量pdf打印即可。

代码如下:
1 docx文件转pdf

# Imports =============================================================
import comtypes.client
import time
import os
file_path = r"C:/Users/Administrator/Desktop/E/"
out_path = r"C:/Users/Administrator/Desktop/B/"
# Variables and Inputs=================================================
# File = r'C:\Users\Administrator\Desktop\TS-PM-0001矮地茶饮片※生产工艺规程(B00版).docx'
# Or .doc, rtf files
# Functions ============================================================
def convert_word_to_pdf(inputFile,outputFile):
    ''' the following lines that are commented out are items that others shared with me they used when 
    running loops to stop some exceptions and errors, but I have not had to use them yet (knock on wood) '''
    word = comtypes.client.CreateObject('Word.Application')
    # word.visible = False
    # time.sleep(3)
    doc = word.Documents.Open(inputFile)
    doc.SaveAs(outputFile, FileFormat = 17)
    doc.close()
    word.visible = False
    word.Quit()

# Main Body=================================================================
def main():
    for name in os.listdir(file_path):
        print(name)
        file = file_path + name
        outfile = out_path + name[:-5] +'.pdf'
        if file.split(".")[-1] == 'docx':
            convert_word_to_pdf(file,outfile)
        print("^"*30)  

if __name__ == '__main__':
    main()  

2pdf文件按奇偶分类

import os
import PyPDF2
import shutil
file_path = r"C:/Users/Administrator/Desktop/B/"
ou_file_path = r"C:/Users/Administrator/Desktop/oushu/"
ji_file_path=r"C:/Users/Administrator/Desktop/jishu/"

for name in os.listdir(file_path):
        print(name)
        file = file_path + name
        ou_file=ou_file_path + name
        ji_file=ji_file_path + name
        if file.split(".")[-1] == 'pdf':
            reader = PyPDF2.PdfFileReader(file)
            # 获取单个文件页数
            pageNum = reader.getNumPages()
            if pageNum%2 == 0:
                shutil.move(file,ou_file)
            else:
                shutil.move(file,ji_file)
            # print(pageNum)

3 分别截取需要的4页

# -- coding: utf-8 --
# 导入PYPDF2库
from PyPDF2 import PdfFileReader, PdfFileWriter
import os
ou_file_path = r"C:/Users/Administrator/Desktop/oushu/"
# ji_file_path=r"C:/Users/Administrator/Desktop/jishu/"
pdf_file_path=r"C:/Users/Administrator/Desktop/pdf2/"
def main():
    for name in os.listdir(ou_file_path):
            print(name)
            ou_file=ou_file_path + name
            pdf_file=pdf_file_path + name
            # start = -5
            # 切分结束页面
            # end = -1
            start = -4
            # 切分结束页面
            end = 0
            split_single_pdf(ou_file, start, end, pdf_file)

def split_single_pdf(read_file, start_page, end_page, pdf_file):
    # 1. 获取原始pdf文件
    fp_read_file = open(read_file, 'rb')
    # 2. 将要分割的PDF内容格式化
    pdf_input = PdfFileReader(fp_read_file)
    # 3. 实例一个 PDF文件编写器
    pdf_output = PdfFileWriter()
    # 4. 把3到4页放到PDF文件编写器
    for i in range(start_page, end_page):
        pdf_output.addPage(pdf_input.getPage(i))
    # 5. PDF文件输出
    with open(pdf_file, 'wb') as pdf_out:
        pdf_output.write(pdf_out)
    print(f'{read_file}分割{start_page}页-{end_page}页完成,保存为{pdf_file}!')





if __name__ == '__main__':
    main()  

4 批量打印

import win32api
import win32print
import os
import time
def printer_loading(filename):
    win32api.ShellExecute (
    0,
    "print",
    filename,
    '/d:"%s"' % win32print.GetDefaultPrinter (),
    ".",
    0
    )
    time.sleep(20)
path=r'C:\Users\Administrator\Desktop\pdf'
for filenames in os.listdir(path):
    file_path=os.path.join(path,filenames)
    print("您要打印的文件是%s"%filenames)
    printer_loading(os.path.join(path,filenames))

参考了网上较多高手的代码,在此深感谢意。

python文件处理:解析docx/word文件文字、图片、复选框 可用:使用python解析docx/word文件中的表格、文本、图片、复选框数据,提供实际方案及代码 阅读详情

相关推荐

python读取excel写入word模板_使用python将Excel数据填充Word模板并生成Word

【项目需求】Excel中有一万多条学生学平险数据,需要给每位学生打印购买回执单,回执单包括学生姓名,身份证号,学校等信息,目前只能从Excel拷贝数据到Word模板中,然后打印,效率及其低下,寻求帮助。【解决方案】1、设计Word模板。2、读取Excel中的数据,并按Word模板生成Word文件。3、使用批量打印软件进行批量打印。关键需要解决word模板如何设计,像数据一样,定义好字段,后期能插入...

weixin_39805883的博客 4396

如何用Python批量打印PDF文档、Word文档、Excel表格、图片呢?

如何用Python批量打印PDF文档、Word文档、Excel表格、图片呢?

weixin_55609727的博客 8732

python批量提取word指定内容到excel_python批量提取word内信息

单位收集了很多word格式的调查表,领导需要收集表单里的信息,我就把所有调查表放一个文件里,写了个python小程序把所需的信息打印出来 #coding:utf-8import osimport win32comfrom win32com.client import Dispatch, constantsfrom docx import Documentdef parse_doc(f):"""读取...

weixin_39693971的博客 2863

Python:通过Win32模块操作Office对象之打印

此文主要展示三种文件打印的示例代码,具体参数等可以参考我之前的几篇VBA的文章中的VBA代码,因为Win32中的代码书写方式和VBA中基本一样。守候ExcelVBA批量对文件任意重命名(移动)https守候PPTVBA批量转PDFhttps之所以用Win32模块,是因为它是最全面的。只要在这些文件中可以手动设置的属性,全部可以通过代码实现。httpshttpshttpshttpshttpshttpshttpst=M666httpst=M666守候ExcelVBA。...

qq_64613735的博客 1977

在Python中实现单例模式.docx

在Python中实现单例模式.docx

word文件批量打印助手破解版

word文件批量打印助手破解版,word文件,cad图等等,都可以批量打印。

Python 批量打印Word文档

批量打印Word文档

淘气の小狼人的博客 1322

Bellhop水声信道模型的仿真

Bellhop是一种基于射线追踪的水声信道模型,广泛用于预测水下环境中的声压场。它通过模拟声波在水中的传播路径,计算声场分布,适用于复杂的水下通信场景。

yt94832的博客 1324

Python截取文章段落

在盛世时享受着家人的呵护,畅想过未来幸福美好的生活。在初窥知识的边界后,为拓宽人类见闻而奋发图强过,都会在某时某刻,被迫离开心里的象牙塔,破开“自己永远会被他人照顾”的茧房,踏上普通平淡的生活之路。都是要用自己的头脑和双手在这片土地上创作着属于自己的小世界,在这个世间守住属于自己的一隅,普通地活下去。都是要用自己的头脑和双手在这片土地上创作着属于自己的小世界,在这个世间守住属于自己的一隅,普通地活下去。都是要用自己的头脑和双手在这片土地上创作着属于自己的小世界,在这个世间守住属于自己的一隅,普通地活下去。

Saki_Python的博客 450

告别卡顿!用ARMv8.1-M的MVE(Helium)技术,让你的嵌入式DSP应用飞起来

本文深入探讨了ARMv8.1-M架构的MVE(Helium)技术如何显著提升嵌入式DSP应用的性能。通过介绍MVE的向量处理能力、关键指令集和实战优化示例(如FIR滤波器的向量化实现),展示了从标量到向量代码的转变路径。性能对比显示,MVE优化可带来高达8倍的性能提升,特别适用于音频处理、电机控制等嵌入式场景。

weixin_28693683的博客 237

NXP应用随记(八):S32K3XX的HSE学习记录(HSE\MU\UTEST\IVT\A,B SWAP)

HSE,即硬件安全引擎(Hardware Security Engine),是NXP S32K312微控制器(MCU)中的一个功能,它提供了一系列的安全特性,包括加密、安全启动和密钥存储等。这些功能旨在增强汽车电子系统的信息安全,符合ISO26262标准,达到ASIL D安全等级。具体来说,S32K312的HSE支持AES-128/192/256加密、RSA、ECC等加密算法,以及侧通道保护,确保了数据传输和存储的安全性。

梦想技术家 9780

【教学类-06-04】20220330 5以内加减法不重复题 及生成word打印docx纸(方法二)(Python VS)

【教学类-06-04】20220330 5以内加减法不重复题 及生成word打印docx纸(方法二)(Python VS)

reasonsummer的博客 1836

【WRF编译-Lab1】使用自动脚本编译WRF:错误总结

WRF编译过程及错误总结

WW、forever的博客 89

基于pdf2docx模块Python实现批量将PDF转Word文档(安装+完整代码教程)

基于pdf2docx模块Python实现批量将PDF转Word文档(安装+完整代码教程)

努力让自己发光,对的人才能迎着光而来 2万+

AEJoy —— 最受欢迎的 5 个 Ae 表达方式

NOTE] 原文作者我意识到表达式可能令人生畏,有些人宁愿复制粘贴有用的代码,而不愿学习这门语言。对此我完全理解。因此,我想与您分享我的。这些是我几乎在每个项目中都会使用的表达式,我认为它们极大地提升了工作流程。

ShaderJoy 的兴趣技术杂货铺 372

π0.5部署实战(一) ------ 在Thor上使用NVFP4量化

此篇文章是pi05模型在thor上部署系列文章的第一篇.主要介绍如何对pi05 2.6B LLM(Gemma)使用nvfp4进行量化.所有操作使用开源工具可以先参考进行环境的准备和安装,在上完成以下操作.

happyAnger6的专栏 418

python 批量打印文档_使用python将Excel数据填充Word模板并生成Word

【项目需求】Excel中有一万多条学生学平险数据,需要给每位学生打印购买回执单,回执单包括学生姓名,身份证号,学校等信息,目前只能从Excel拷贝数据到Word模板中,然后打印,效率及其低下,寻求帮助。【解决方案】1、设计Word模板。 2、读取Excel中的数据,并按Word模板生成Word文件。 3、使用批量打印软件进行批量打印。 关键需要解决word模板如何设计,像数据一样,定义好字段,后期...

weixin_42511887的博客 2204

LPDDR6与LPDDR5 State Diagram技术探讨

LPDDR6与LPDDR5 State Diagram技术探讨

zilan23的博客 1185

使用Python实现对word的批量操作

Python在平时写写小工具真是方便快捷,大法好。以下所有代码都是找了好多网上的大佬分享的代码按照自己的需求改的。调用的库为Python-docx、、PyPDF2、xlwings(操作excel)。因为公司的任务要对上千个word文件进行批量操作,手工操作太累了,于是加班加点赶出来了一个脚本,虽然还有很多要优化的地方,但已经可以稳定运行了,下面记录一下脚本功能。

2301_79535544的博客 1295

ollama使用CPU安装qwen-coder模型_并在eclipse中使用ai coder插件_配置本地qwen-coder模型_ollama常用操作记录---AI大模型应用探索0002

文章摘要:作者分享了在Windows 10上安装和使用Ollama模型的过程。尝试了不同规模的qwen-coder模型(7b、1.5b和0.5b),发现7b模型响应极慢(需35分钟),而1.5b模型表现较好(3秒响应)。最终选择1.5b版本用于代码开发辅助,支持多语言自动补全。同时提到在最新版Eclipse中的AIcoder配置问题。文章重点比较了不同模型规模在CPU环境下的实际使用体验和响应速度差异。

添柴程序猿的专栏 695

Probability and Statistics - 4th edition

Probability and Statistics - 4th edition

编写python脚本实现批量打开 Word 文件并执行邮件功能

要实现批量打开 Word 文件并执行邮件功能,可以使用 python-docx 来处理 Word 文件,使用 smtplib 和 email 来发送邮件。

Meet....的博客 1359

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

pdf2docx:Python实现PDF转Word

本文简介作者写的一个PDF转Word的Python库pdf2docx,包括基本思路、功能、使用方法及样例。 1 基本思路 PDF文档遵循一定的规范1,例如精确定位了每个字符出现在页面上的坐标、根据坐标绘制的各种形状(线、矩形、曲线等)。所以,用PDF格式传输和打印文档可以保证格式的一致性,不会像Word那样因为渲染引擎的不同而出现格式错乱、多页少页等问题。 Word文档则是一种流式布局,元素之间的相对距离决定了其呈现在页面上的最终位置。因此适合编辑内容,前文内容的修改自动促发后续文档布局的更新。 PDF转

格致 1万+

jre9下载 jdk9

(Java SE Runtime Environment 9.0) 9.0u175 官方最新版 【x86|x64】

SAP B1中文培訓教材_SDK

公司内部培训资料,对开发工具 ,DIAPI, UIAPI,Add-ON有详细解说

Python Word 操作全面指南

本文介绍了 Python Word 基础操作,包括安装 Python Word 库、读取 Word 文件、写入 Word 文件和修改 Word 文件。这些操作是 Python Word 操作的基础,掌握了这些操作,就可以进一步学习更高级的 Python Word 操作了。在下一部分中,我们将介绍如何使用 Python Word 库进行 Word 文档的批量处理。本部分介绍了如何使用 Python 对多个 Word 文件进行批量处理,包括读取、写入和修改。

极客代码 5862

python批量提取word指定内容_python批量提取word内信息

单位收集了很多word格式的调查表,领导需要收集表单里的信息,我就把所有调查表放一个文件里,写了个python小程序把所需的信息打印出来#coding:utf-8import osimport win32comfrom win32com.client import Dispatch, constantsfrom docx import Documentdef parse_doc(f):"""读取d...

weixin_39876145的博客 1273
上一篇: 202104连续间隔60s打印PDF文件
下一篇: 202104修改文件名
lgs2016
博客等级 码龄8年 5粉丝 11原创
评论 4
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值
⌂ 换网址