一个文件内包含有众多个子文件夹(如:人员信息),这个时候需要你将这些文件全部打印下来。如果手动打开文件并打印将消耗大量的人力与物力,是时候用代码和计算机提高生产力了。
(目前只支持word,pdf,excle文件)
链接:https://pan.baidu.com/s/1YbAec-TLmPrejCJELBPN5w?pwd=zkwi
提取码:zkwi
1.进入云盘并下载到桌面
2.解压文件
3.打开文件找到.exe文件并双击打开
找到保存路径的pdf,默认为hebing.pdf
(每个文件都考虑了双面打印,故每个文件都是偶数页转为pdf再合并为一个整体pdf,方便双面打印)
python环境,需要下载相对应的包
import sys
from win32com.client.gencache import EnsureDispatch
from win32com.client import Dispatch # pip install pywin32
from os import walk
import os
import PyPDF2
import os
import re
from openpyxl import load_workbook
import win32com.client as win32 # 导入模块
from win32com.client import DispatchEx
import shutil
wdFormatPDF = 17 # win32提供了多种word转换为其他文件的接口,其中FileFormat=17是转换为pdf
# xl = EnsureDispatch("Word.Application")
# print(sys.modules[xl.__module__].__file__)
# word 到 pdf
def doc2pdf(input_file, input_file_name, output_dir):
try:
word = Dispatch('Word.Application')
doc = word.Documents.Open(input_file)
except Exception as e:
print("word无法打开, 发生如下错误:\n{}".format(e))
try:
pdf_file_name = input_file_name.replace(".docx", ".pdf").replace(".doc", ".pdf")
pdf_file = os.path.join(output_dir, pdf_file_name)
doc.SaveAs(pdf_file, FileFormat=wdFormatPDF)
doc.Close()
word.Quit()
print("成功转换\"{}\"".format(input_file_name))
print()
except Exception as e:
print("文件保存失败, 发生如下错误:\n{}".format(e))
# xls 到 xlsx
def xls2xlsx(input_file, input_file_name, output_dir):
excel = win32.gencache.EnsureDispatch('Excel.Application') # 启动win32模块
filepath = input_file
wb = excel.Workbooks.Open(filepath)#启动excel
wb.SaveAs(output_dir+"x", FileFormat=51) # 把xls转化成xlsx
print(filepath,'ok-②已转格')#获知那些文件已转化格式
wb.Close() # 停止模块
excel.Application.Quit() # 停止模块
# xlsx 所有列一页
def xls_col_page(input_file, input_file_name, output_dir):
filename = input_file
print(filename)
wb = load_workbook(filename)
ws = wb.active
# 所有列一页
ws.sheet_properties.pageSetUpPr.fitToPage = True#适配页码
ws.page_setup.fitToWidth = False
ws.page_setup.fitToHeight=False #可以直接将Ture/False设置为数字
# 所有行一页
# ws.sheet_properties.pageSetUpPr.fitToPage = True
# ws.page_setup.fitToHeight = False
#ws.page_setup.fitToWidth = 3 #高度/宽度适合,例如3页
#ws.page_setup.fitToHeight = False
wb.save(output_dir)
def xlsx2pdf(input_file, input_file_name, output_dir):
try:
xlApp = DispatchEx("Excel.Application")
#后台运行, 不显示, 不警告
xlApp.Visible = False
xlApp.DisplayAlerts = 0
filename = input_file
books = xlApp.Workbooks.Open(filename, False)
#第一个参数0表示转换pdf
books.ExportAsFixedFormat(0, re.subn('.xlsx', '.pdf', filename)[0])
books.Close(False)
print('保存 PDF 文件:', re.subn('.xlsx', '.pdf', output_dir)[0])
except :
input('转换出错了,按任意键退出')
finally:
xlApp.Quit()
def pdf2pdf(filepath, input_file_name, output_dir):
shutil.copy(filepath, output_dir)
def pdf_all(output_dir, path_out, i):
pdf_writer = PyPDF2.PdfWriter()
# 逐个读取PDF文件并将它们合并到pdf_writer中
for dirs, subdirs, files in os.walk(output_dir):
for name in files:
if re.search('.pdf', name):
path = dirs + '\\' + name
pdf_reader = PyPDF2.PdfReader(path)
for page in range(len(pdf_reader.pages)):
pdf_writer.add_page(pdf_reader.pages[page])
num = len(pdf_writer.pages)
if (num % 2 == 1):
# 添加空白页
pdf_writer.add_blank_page()
# 将合并后的PDF写入到一个新文件中
pdf_writer.write(path_out + '\\' + '{}.pdf'.format(i))
if __name__ == "__main__":
path_in=input("请输入文件夹的路径(绝对路径) 要保证存在 建议复制粘贴")
path_out=input("请输入pdf文件夹的路径(绝对路径) 要保证存在 建议复制粘贴")
doc_files = []
directory = path_in# 文件夹
output_dir =path_out # pdf文件夹
datanames = os.listdir(path_in)
for i in datanames:
directory = path_in + "\\" + i
output_dir = path_out + "\\" + i
os.mkdir(output_dir)
for root, _, filenames in walk(directory): # 第2个返回值是dirs, 用不上使用_占位
for file in filenames:
if file.endswith(".doc") or file.endswith(".docx"):
print("转换{}中......".format(file))
doc2pdf(os.path.join(root, file), file, output_dir)
elif file.endswith(".xlsx"):
print("转换{}中......".format(file))
xlsx2pdf(os.path.join(root, file), file, os.path.join(output_dir, file))
elif file.endswith(".xls"):
print("转换{}中......".format(file))
xls2xlsx(os.path.join(root, file), file,
os.path.join(output_dir, file))
xls_col_page(os.path.join(output_dir, file+'x'),
file, os.path.join(output_dir, file))
path = os.path.join(output_dir, file)
print(path)
os.remove(path)
xlsx2pdf(os.path.join(output_dir, file+'x'),
file, os.path.join(output_dir, file+'x'))
elif file.endswith(".pdf"):
print("复制{}中......".format(file))
pdf2pdf(os.path.join(root, file),
file, os.path.join(output_dir, file))
pdf_all(directory, path_out, i)
pdf_all(path_out, path_out, 'hebing')
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。