python 将pdf分页后插入至word中
所用技术
1. python编程基础
2. 使用pyPdf
3. 使用python操作word
4. 正则表达式的使用
5. windows的bat编程
下面是一个pyPdf库使用的示例:
from pyPdf import PdfFileWriter, PdfFileReader
output = PdfFileWriter()
input1 = PdfFileReader(file("document1.pdf", "rb"))
# add page 1 from input1 to output document, unchanged
output.addPage(input1.getPage(0))
# add page 2 from input1, but rotated clockwise 90 degrees
output.addPage(input1.getPage(1).rotateClockwise(90))
# add page 3 from input1, rotated the other way:
output.addPage(input1.getPage(2).rotateCounterClockwise(90))
# alt: output.addPage(input1.getPage(2).rotateClockwise(270))
# add page 4 from input1, but first add a watermark from another pdf:
page4 = input1.getPage(3)
watermark = PdfFileReader(file("watermark.pdf", "rb"))
page4.mergePage(watermark.getPage(0))
# add page 5 from input1, but crop it to half size:
page5 = input1.getPage(4)
page5.mediaBox.upperRight = (
page5.mediaBox.getUpperRight_x() / 2,
page5.mediaBox.getUpperRight_y() / 2
)
output.addPage(page5)
# print how many pages input1 has:
print "document1.pdf has %s pages." % input1.getNumPages())
# finally, write "output" to document-output.pdf
outputStream = file("document-output.pdf", "wb")
output.write(outputStream)
有了该库,就可以很容易将现有的pdf做分割。
因为我的需求是要将pdf中的关键字提取出来,用它来作为文件名。pyPdf中提供了将pdf中的文字全部提取出来。
inputfile.getPage(0).extractText()
这里返回的unicode,需要转为str
inputfile.getPage(0).extractText().encode("utf-8")
然后将每页的关键字提取出来,增加函数如下:
p_sheetName = re.compile('Blattname: (.+?)project')
def getSheetName(str):
m = p_sheetName.search(str)
if m:
return m.group(1)
else:
return None;
最终代码如下:
from pyPdf import PdfFileWriter, PdfFileReader
import re,os p_sheetName = re.compile('Blattname: (.+?)project')
def getSheetName(str):
m = p_sheetName.search(str)
if m:
return m.group(1)
else:
return None; def splitpdf(srcFile):
input1 = file(srcFile,"rb")
inputfile = PdfFileReader(input1)
numofpages = inputfile.getNumPages()
print "pages: %d" % numofpages
#new directory
folderName,ext_ = os.path.splitext(srcFile)
if not os.path.isdir(folderName):
os.makedirs(folderName)
for page_index in range(1,numofpages+1):
output = PdfFileWriter()
output.addPage(inputfile.getPage(page_index-1)) sheetName = getSheetName(inputfile.getPage(page_index-1).extractText().encode("utf-8"))
#save file
saveFileName = os.path.join(folderName,"%d %s.pdf" % (page_index,sheetName))
print saveFileName
outputFile = file(saveFileName,"wb")
output.write(outputFile)
outputFile.close()
input1.close() splitpdf("E:\\test.pdf")
下一步,将pdf参数化
from pyPdf import PdfFileWriter, PdfFileReader
import re,sys,os,string def translator(frm='', to='', delete='', keep=None):
if len(to) == 1 :
to = to * len(frm)
trans = string.maketrans(frm,to)
if keep is not None:
allchars = string.maketrans('','')
delete = allchars.translate(allchars,keep.translate(allchars,delete))
def translate(s):
return s.translate(trans,delete)
return translate delete_some_speicl = translator(delete="/:\\?*><|") p_sheetName = re.compile('Blattname: (.+?)project')
def getSheetName(str):
m = p_sheetName.search(str)
return delete_some_speicl(m.group(1)) def splitpdf(srcFile):
try:
folderName,ext_ = os.path.splitext(srcFile)
if ext_ != '.pdf':
raise Exception(os.path.basename(srcFile) + " is not pdf!")
input1 = file(srcFile,"rb")
inputfile = PdfFileReader(input1)
numofpages = inputfile.getNumPages()
print "pages: %d" % numofpages
#new directory
if not os.path.isdir(folderName):
os.makedirs(folderName)
for page_index in range(1,numofpages+1):
output = PdfFileWriter()
output.addPage(inputfile.getPage(page_index-1)) sheetName = getSheetName(inputfile.getPage(page_index-1).extractText().encode("utf-8"))
#save file
saveFileName = os.path.join(folderName,"%d %s.pdf" % (page_index,sheetName))
print saveFileName
outputFile = file(saveFileName,"wb")
output.write(outputFile)
outputFile.close()
input1.close()
print "Split success!"
print "please find them at " + folderName
except Exception,e:
print e if __name__ == '__main__':
if len(sys.argv) < 2:
print 'usage: %s filename' % os.path.basename(sys.argv[0])
exit(0)
#print sys.argv[1]
splitpdf(sys.argv[1])
这里translator函数是将关键字中的特殊字符过滤掉,因为新建文件时可能会出错。
其实分开pdf也还需要一些手动操作,不然还需用vba导入到word中,我想直接用python干完这些事,如果就用到了win32com来操作word
下面是使用操作word的一个示例:
import win32com
from win32com.client import Dispatch, constants w = win32com.client.Dispatch('Word.Application')
# 或者使用下面的方法,使用启动独立的进程:
# w = win32com.client.DispatchEx('Word.Application') # 后台运行,不显示,不警告
w.Visible = 0
w.DisplayAlerts = 0 # 打开新的文件
doc = w.Documents.Open( FileName = filenamein )
# worddoc = w.Documents.Add() # 创建新的文档 # 插入文字
myRange = doc.Range(0,0)
myRange.InsertBefore('Hello from Python!') # 使用样式
wordSel = myRange.Select()
wordSel.Style = constants.wdStyleHeading1 # 正文文字替换
w.Selection.Find.ClearFormatting()
w.Selection.Find.Replacement.ClearFormatting()
w.Selection.Find.Execute(OldStr, False, False, False, False, False, True, 1, True, NewStr, 2) # 页眉文字替换
w.ActiveDocument.Sections[0].Headers[0].Range.Find.ClearFormatting()
w.ActiveDocument.Sections[0].Headers[0].Range.Find.Replacement.ClearFormatting()
w.ActiveDocument.Sections[0].Headers[0].Range.Find.Execute(OldStr, False, False, False, False, False, True, 1, False, NewStr, 2) # 表格操作
doc.Tables[0].Rows[0].Cells[0].Range.Text =''
worddoc.Tables[0].Rows.Add() # 增加一行 # 转换为html
wc = win32com.client.constants
w.ActiveDocument.WebOptions.RelyOnCSS = 1
w.ActiveDocument.WebOptions.OptimizeForBrowser = 1
w.ActiveDocument.WebOptions.BrowserLevel = 0 # constants.wdBrowserLevelV4
w.ActiveDocument.WebOptions.OrganizeInFolder = 0
w.ActiveDocument.WebOptions.UseLongFileNames = 1
w.ActiveDocument.WebOptions.RelyOnVML = 0
w.ActiveDocument.WebOptions.AllowPNG = 1
w.ActiveDocument.SaveAs( FileName = filenameout, FileFormat = wc.wdFormatHTML ) # 打印
doc.PrintOut() # 关闭
# doc.Close()
w.Documents.Close(wc.wdDoNotSaveChanges)
w.Quit()
仿照上例,修改前面的代码如下:
from pyPdf import PdfFileWriter, PdfFileReader
import re,sys,os,string,win32com
from win32com.client import Dispatch, constants
win32com.client.gencache.EnsureDispatch('Word.Application') def translator(frm='', to='', delete='', keep=None):
if len(to) == 1 :
to = to * len(frm)
trans = string.maketrans(frm,to)
if keep is not None:
allchars = string.maketrans('','')
delete = allchars.translate(allchars,keep.translate(allchars,delete))
def translate(s):
return s.translate(trans,delete)
return translate delete_some_speicl = translator(delete="/:\\?*><|") p_sheetName = re.compile('Blattname: (.+?)project')
def getSheetName(str):
m = p_sheetName.search(str)
return m.group(1) def splitPdfToWord(srcFile):
try:
folderName,ext_ = os.path.splitext(srcFile)
if ext_ != '.pdf':
raise Exception(os.path.basename(srcFile) + " is not pdf!")
input1 = file(srcFile,"rb")
inputfile = PdfFileReader(input1)
numofpages = inputfile.getNumPages()
print "Total Pages: %d" % numofpages
wordApp = win32com.client.Dispatch('Word.Application')
wordApp.Visible = False
wordApp.DisplayAlerts = 0
doc = wordApp.Documents.Add()
sel = wordApp.Selection
#new directory
if not os.path.isdir(folderName):
os.makedirs(folderName)
for page_index in range(1,numofpages+1):
output = PdfFileWriter()
output.addPage(inputfile.getPage(page_index-1)) sheetName = getSheetName(inputfile.getPage(page_index-1).extractText().encode("utf-8"))
sel.Style = constants.wdStyleHeading1
sel.TypeText("Page%d %s" % (page_index,sheetName))
sheetName = delete_some_speicl(sheetName)
#save file
saveFileName = os.path.join(folderName,"%d %s.pdf" % (page_index,sheetName))
print "Add Page %d" % page_index
#print saveFileName
outputFile = file(saveFileName,"wb")
output.write(outputFile)
outputFile.close()
sel.TypeParagraph()
sel.Style = constants.wdStyleBodyText
sel.InlineShapes.AddOLEObject(ClassType="AcroExch.Document.11",FileName=saveFileName)
sel.InsertBreak(Type=constants.wdPageBreak)
input1.close()
doc.SaveAs(folderName+".doc")
print "Split success!"
print "please find them at " + folderName
print "create word document success!"
print "Location:" + folderName + ".doc"
except Exception,e:
print e
finally:
wordApp.Quit() if __name__ == '__main__':
if len(sys.argv) < 2:
print 'usage: %s filename' % os.path.basename(sys.argv[0])
sys.exit(1)
splitPdfToWord(sys.argv[1])
python 将pdf分页后插入至word中的更多相关文章
- 如何将代码优雅的插入到word中
介:写博客或者word时需要插入代码,但如何更优雅的将代码插入到word中呢? 反面教材如下: 技巧步骤1:插入表格,设置表格无边框: 技巧步骤2:使用Notepad++的高级功能: 大部分代码编辑器 ...
- mysql存储过程之遍历多表记录后插入第三方表中
自从学过存储过程后,就再也没有碰过存储过程,这是毕业后写的第一个存储过程. 因为项目里设备的种类比较多,分别存在不同的数据表中,java中对应不同的java bean对象,想要统一管理有点困难.最近正 ...
- (转)如何优雅的在 Microsoft word中插入代码
背景:最近项目需要自己编写文档,在文档中需要插入部分代码,记录下这个方法. 一.工具 方法1.打开这个网页PlanetB; 方法2.或者谷歌搜索syntax highlight code in wor ...
- 如何在 Microsoft word中插入代码
一.工具 方法1.打开这个网页PlanetB; 方法2.或者谷歌搜索syntax highlight code in word documents,检索结果的第一个.如下图: PS. 方法1和2打开的 ...
- Word中的代码怎样语法高亮
在平常我们粘贴代码到Word中的时候,经常会遇到代码粘贴到Word中后没有语法高亮,看着很乱很不友好,Word自带的样式---语法使用着也不尽人意, 网上有很多做法可以使得在插入在Word中的代码能够 ...
- 如何把word中的图片怎么导出来呢?
在办公使用word的过程中你可能经常会遇到这个问题:插入到word中的图片找不到导出来的方法,是不是很郁闷呢,别急,今天咱们研究一下把word中的图片导出来的方法(把"我的"变成你 ...
- 如何删除word中多余的空格和空行
去除word中多余的空格及空行 一.去掉表格和格式 为了版面的整齐,网页文档都是以表格的形式存在的,只是一般情况下表格的颜色被设为无色或表格宽度被设为0,所以我们在网页上看不到表格.另外,网 页文档中 ...
- Word中批量替换软回车
在平时工作中,有时候需要拷贝一些截取自网页上的文字,当选中后拷贝到Word中时,有时候在每行的结尾出现如下的符号,,这给后期文字的整理带来了很多不便,在此记录从网上获取的解决方法,以免遗忘和便于查找. ...
- Python | 实现pdf文件分页
不知道大家有没有遇到过这么一种情况,就比如一个pdf格式的电子书,我们经常浏览的是其中的一部分,而这电子书的页数很大,每当需要浏览时,就需要翻到对应的页码,就有点儿繁琐. 还有一些情况,比如,我们想分 ...
随机推荐
- 获取手机的gps定位
只要手机有GPS模块,可以用HTML5的Geolocation接口获取 在HTML5中,geolocation作为navigator的一个属性出现,它本身是一个对象,拥有三个方法: - getCurr ...
- 从svn服务器自动同步到另一台服务器
需求场景 A commit B post-commit C (workstation) --------------> (svn server) ---------------------> ...
- 学习笔记-动态树Link-Cut-Tree
--少年你有梦想吗? --少年你听说过安利吗? 安利一个集训队讲解:http://wenku.baidu.com/view/75906f160b4e767f5acfcedb 关于动态树问题,有多种方法 ...
- CSS设置技巧
一.单位和值 1.1 颜色值 在网页中的颜色设置是非常重要,有字体颜色(color).背景颜色(background-color).边框颜色(border)等,设置颜色的方法也有很多种: 1.英文命令 ...
- firefox(ff)下无法显示bootstrap图标问题的解决方案(转)
原文链接: http://www.th7.cn/web/html-css/201502/82548.shtml 后在网上搜到了解决方案,在此分享以供各位遇到问题的同好参考:在ff的地址栏中输入“abo ...
- php扩展redis
Redis安装整理(window平台) +php扩展redis 分类: Web开发2013-03-23 18:51 8258人阅读 评论(3) 收藏 举报 ...
- 在不借助其他工具的情况下破解Windows开机密码
文章:http://www.cnblogs.com/vforbox/p/4828855.html#!comments. 从该文章我们也可以得到一个快速启动某个程序的方法:将自己常用的程序命名为seth ...
- poj 1067 取石子游戏(威佐夫博奕(Wythoff Game))
这里不在详细介绍威佐夫博弈论 简单提一下 要先提出一个名词“奇异局势”,如果你面对奇异局势则必输 奇异局势前几项(0,0).(1,2).(3,5).(4,7).(6,10).(8,13).(9,15) ...
- Linux下SVN安装配置和使用中遇到的问题
两个命令: svn info :显示版本库信息,svn的下载url等. svn co https://xxxxx/xxx wodemulu (通过我的目录制定co的文件夹) svn st:显示 ...
- Java对文件及文件夹的操作
public class FileOperater { // 验证字符串是否为正确路径名的正则表达式 private static String matches = "[A-Za-z]:\\ ...