windows下Python实现将pdf文件转化为png格式图片的方法


Posted in Python onJuly 21, 2017

本文实例讲述了windows下Python实现将pdf文件转化为png格式图片的方法。分享给大家供大家参考,具体如下:

最近工作中需要把pdf文件转化为图片,想用Python来实现,于是在网上找啊找啊找啊找,找了半天,倒是找到一些代码。

1、第一个找到的代码,我试了一下好像是反了,只能实现把图片转为pdf,而不能把pdf转为图片。。。

参考链接:https://zhidao.baidu.com/question/745221795058982452.html

代码如下:

#!/usr/bin/env python
import os
import sys
from reportlab.lib.pagesizes import A4, landscape
from reportlab.pdfgen import canvas
f = sys.argv[1]
filename = ''.join(f.split('/')[-1:])[:-4]
f_jpg = filename+'.jpg'
print f_jpg
def conpdf(f_jpg):
 f_pdf = filename+'.pdf'
 (w, h) = landscape(A4)
 c = canvas.Canvas(f_pdf, pagesize = landscape(A4))
 c.drawImage(f, 0, 0, w, h)
 c.save()
 print "okkkkkkkk."
conpdf(f_jpg)

2、第二个是文章写的比较详细,可惜的是linux下的代码,所以仍然没用。

3、第三个文章指出有一个库PythonMagick可以实现这个功能,需要下载一个库 PythonMagick-0.9.10-cp27-none-win_amd64.whl 这个是64位的。

这里不得不说自己又犯了一个错误,因为自己从python官网上下载了一个python 2.7,以为是64位的版本,实际上是32位的版本,所以导致python的版本(32位)和下载的PythonMagick的版本(64位)不一致,弄到晚上12点多,总算了发现了这个问题。。。

4、然后,接下来继续用搜索引擎搜,找到很多stackoverflow的问题帖子,发现了2个代码,不过要先下载PyPDF2以及ghostscript模块。

先通过pip来安装 PyPDF2、PythonMagick、ghostscript 模块。

C:\Users\Administrator>pip install PyPDF2
Collecting PyPDF2
 Using cached PyPDF2-1.25.1.tar.gz
Installing collected packages: PyPDF2
 Running setup.py install for PyPDF2
Successfully installed PyPDF2-1.25.1
You are using pip version 7.1.2, however version 8.1.2 is available.
You should consider upgrading via the 'python -m pip install --upgrade pip' command.
C:\Users\Administrator>pip install C:\PythonMagick-0.9.10-cp27-none-win_amd64.whl
Processing c:\pythonmagick-0.9.10-cp27-none-win_amd64.whl
Installing collected packages: PythonMagick
Successfully installed PythonMagick-0.9.10
You are using pip version 7.1.2, however version 8.1.2 is available.
You should consider upgrading via the 'python -m pip install --upgrade pip' command.
C:\Users\Administrator>pip install ghostscript
Collecting ghostscript
 Downloading ghostscript-0.4.1.tar.bz2
Requirement already satisfied (use --upgrade to upgrade): setuptools in c:\python27\lib\site-packages (from ghostscript)
Installing collected packages: ghostscript
 Running setup.py install for ghostscript
Successfully installed ghostscript-0.4.1
You are using pip version 7.1.2, however version 8.1.2 is available.
You should consider upgrading via the 'python -m pip install --upgrade pip' command.

下面是代码

代码1:

import os
import ghostscript
from PyPDF2 import PdfFileReader, PdfFileWriter
from tempfile import NamedTemporaryFile
from PythonMagick import Image
reader = PdfFileReader(open("C:/deep.pdf", "rb"))
for page_num in xrange(reader.getNumPages()):
 writer = PdfFileWriter()
 writer.addPage(reader.getPage(page_num))
 temp = NamedTemporaryFile(prefix=str(page_num), suffix=".pdf", delete=False)
 writer.write(temp)
 print temp.name
 tempname = temp.name
 temp.close()
 im = Image(tempname)
 #im.density("3000") # DPI, for better quality
 #im.read(tempname)
 im.write("some_%d.png" % (page_num))
 os.remove(tempname)

代码2:

import sys
import PyPDF2
import PythonMagick
import ghostscript
pdffilename = "C:\deep.pdf"
pdf_im = PyPDF2.PdfFileReader(file(pdffilename, "rb"))
print '1'
npage = pdf_im.getNumPages()
print('Converting %d pages.' % npage)
for p in range(npage):
 im = PythonMagick.Image()
 im.density('300')
 im.read(pdffilename + '[' + str(p) +']')
 im.write('file_out-' + str(p)+ '.png')
 #print pdffilename + '[' + str(p) +']','file_out-' + str(p)+ '.png'

然后执行时都报错了,这个是 代码2 的报错信息:

Traceback (most recent call last):
 File "C:\c.py", line 15, in <module>
 im.read(pdffilename + '[' + str(p) +']')
RuntimeError: pythonw.exe: PostscriptDelegateFailed `C:\DEEP.pdf': No such file or directory @ error/pdf.c/ReadPDFImage/713

总是在上面的     im.read(pdffilename + '[' + str(p) +']') 这一行报错。

于是,根据报错的信息在网上查,但是没查到什么有用的信息,但是感觉应该和GhostScript有关,于是在网上去查安装包,找到一个在github上的下载连接,但是点进去的时候显示无法下载。

最后,在csdn的下载中找到了 这个文件:GhostScript_Windows_9.15_win32_win64,安装了64位版本,之后,再次运行上面的代码,都能用了。

不过代码2需要做如下修改,不然还是会报 No such file or directory @ error/pdf.c/ReadPDFImage/713 错误:

#代码2
import sys
import PyPDF2
import PythonMagick
import ghostscript
pdffilename = "C:\deep.pdf"
pdf_im = PyPDF2.PdfFileReader(file(pdffilename, "rb"))
print '1'
npage = pdf_im.getNumPages()
print('Converting %d pages.' % npage)
for p in range(npage):
 im = PythonMagick.Image(pdffilename + '[' + str(p) +']')
 im.density('300')
 #im.read(pdffilename + '[' + str(p) +']')
 im.write('file_out-' + str(p)+ '.png')
 #print pdffilename + '[' + str(p) +']','file_out-' + str(p)+ '.png'

这次有个很深刻的体会,就是解决这个问题过程中,大部分时间都是用在查资料、验证资格资料是否有用上了,搜索资料的能力很重要。

而在实际搜索资料的过程中,国内关于PythonMagick的文章太少了,搜索出来的大部分有帮助的文章都是国外的,但是这些国外的帖子文章,也没有解决我的问题或者是给出有用的线索,最后还是通过自己的思考,解决了问题。

希望本文所述对大家Python程序设计有所帮助。

Python 相关文章推荐
使用Python脚本将文字转换为图片的实例分享
Aug 29 Python
python Flask实现restful api service
Dec 04 Python
学习和使用python的13个理由
Jul 30 Python
Python 日期的转换及计算的具体使用详解
Jan 16 Python
在PyTorch中使用标签平滑正则化的问题
Apr 03 Python
通过python调用adb命令对App进行性能测试方式
Apr 23 Python
基于PyQT实现区分左键双击和单击
May 19 Python
打印tensorflow恢复模型中所有变量与操作节点方式
May 26 Python
详解Django关于StreamingHttpResponse与FileResponse文件下载的最优方法
Jan 07 Python
python pygame 愤怒的小鸟游戏示例代码
Feb 25 Python
正确的理解和使用Django信号(Signals)
Apr 14 Python
python 远程执行命令的详细代码
Feb 15 Python
python僵尸进程产生的原因
Jul 21 #Python
python下载图片实现方法(超简单)
Jul 21 #Python
Python基于Pymssql模块实现连接SQL Server数据库的方法详解
Jul 20 #Python
Python使用内置json模块解析json格式数据的方法
Jul 20 #Python
Python轻量级ORM框架Peewee访问sqlite数据库的方法详解
Jul 20 #Python
Python函数式编程
Jul 20 #Python
python 换位密码算法的实例详解
Jul 19 #Python
You might like
B2K与车机的中波PK
2021/03/02 无线电
Apache2中实现多网站域名绑定的实现方法
2011/06/01 PHP
PHP设计模式之命令模式的深入解析
2013/06/13 PHP
thinkphp3查询mssql数据库乱码解决方法分享
2014/02/11 PHP
PHP和Mysql中转UTF8编码问题汇总
2015/10/10 PHP
PHP中时间加减函数strtotime用法分析
2017/04/26 PHP
JavaScript中的对象化编程
2008/01/16 Javascript
jquery 选择器部分整理
2009/10/28 Javascript
键盘KeyCode值列表汇总
2013/11/26 Javascript
jquery简单实现鼠标经过导航条改变背景图
2013/12/17 Javascript
借助JavaScript脚本判断浏览器Flash Player信息的方法
2014/07/09 Javascript
JavaScript使用ActiveXObject访问Access和SQL Server数据库
2015/04/02 Javascript
浅析函数声明和函数表达式——函数声明的声明提前
2016/05/03 Javascript
浅谈EasyUI常用控件的禁用方法
2016/11/09 Javascript
修改ligerui 默认确认按钮的方法
2016/12/27 Javascript
javascript阻止事件冒泡和浏览器的默认行为
2017/01/21 Javascript
js图片上传的封装代码
2017/08/01 Javascript
bootstrap table实现x-editable的行单元格编辑及解决数据Empty和支持多样式问题
2017/08/10 Javascript
了解JavaScript函数中的默认参数
2019/05/30 Javascript
vue相同路由跳转强制刷新该路由组件操作
2020/08/05 Javascript
python使用wmi模块获取windows下硬盘信息的方法
2015/05/15 Python
Python读写文件方法总结
2015/06/09 Python
Python 将pdf转成图片的方法
2018/04/23 Python
两个元祖T1=('a', 'b'),T2=('c', 'd')使用匿名函数将其转变成[{'a': 'c'},{'b': 'd'}]的几种方法
2019/03/05 Python
Python imageio读取视频并进行编解码详解
2019/12/10 Python
使用html2canvas实现将html内容写入到canvas中生成图片
2020/01/03 HTML / CSS
关于webview适配H5上传照片或者视频文件的方法
2020/11/04 HTML / CSS
EGO Shoes美国/加拿大:英国时髦鞋类品牌
2018/08/04 全球购物
一份全面的PHP面试问题考卷
2012/07/15 面试题
专营店会计助理岗位职责
2013/11/29 职场文书
团购业务员岗位职责
2014/03/15 职场文书
歌颂党的演讲稿
2014/09/10 职场文书
干部四风问题整改措施思想汇报
2014/10/13 职场文书
2015年先进个人自荐书
2015/03/24 职场文书
观看安全警示教育片心得体会
2016/01/15 职场文书
Python爬虫:从m3u8文件里提取小视频的正确操作
2021/05/14 Python