python中解析和生成pdf文件

python中可以对pdf文件进行解析和生成,分别需要安装pdfminer/pdfminer3k和reportlab文件库。

一、pdf文件的解析

pdfminer安装文件路径,分别使用于python2.0/3.0版本:

https://pypi.python.org/pypi/pdfminer/

https://pypi.python.org/pypi/pdfminer3k/

参考文档位于:

http://euske.github.io/pdfminer/programming.html,文档说明了各个模块之间大体的关系,不是很深入理解。而在安装源文件下的tools目录,提供了一些简单集成好的文件,如pdf2txt.py,可以使用其来解析pdf文件,生成txt文本。解析pdf变为txt最大的缺点是图片无法显示,且表格格式等都不再存在。

二、pdf文件的生成

reportlab安装文件:

https://pypi.python.org/pypi/reportlab

reprotlab使用方式的文档地址:

http://www.reportlab.com/

下载reportlab-userguide.pdf参考文档

http://www.reportlab.com/documentation/

类库实现说明

https://sourcecodebrowser.com/python-reportlab/2.5/classreportlab_1_1platypus_1_1flowables_1_1_image.html

pdf的生成类似坐标系上画图的形式,左下角为坐标系(0,0)位置,简单示例:

#!/usr/bin/python  # -*- coding: utf-8 -*-  from reportlab.pdfgen import canvas  from reportlab.platypus.tables import Table, TableStyle  from reportlab.lib.units import inch  from reportlab.platypus import Paragraph,Frame  from reportlab.lib.pagesizes import letter, A4  from reportlab.platypus import Image as platImage  from PIL import Image  from reportlab.lib import colors  from reportlab.pdfbase.ttfonts import TTFont  from reportlab.pdfbase import pdfmetrics  #支持中文,需要下载相应的文泉驿中文字体  pdfmetrics.registerFont(TTFont('hei', 'hei.TTF'))  import testSubFun  testSubFun.testSubFunc('first')  #设置页面大小  c = canvas.Canvas('测试.pdf',pagesize=A4)  xlength,ylength = A4  print('width:%d high:%d'%(xlength,ylength))  #c.line(1,1,ylength/2,ylength)  #设置文字类型及字号  c.setFont('hei',20)  #生成一个table表格  atable = [[1,2,3,4],[5,6,7,8]]  t = Table(atable,50,20)  t.setStyle(TableStyle([('ALIGN',(0,0),(3,1),'CENTER'),                         ('INNERGRID',(0,0),(-1,-1),0.25,colors.black),                         ('BOX',(0,0),(-1,-1),0.25,colors.black)]))  textOb = c.beginText(1,ylength-10)  indexVlaue = 0  while(indexVlaue < ylength):      textStr = '''test 中文写入测试中文写入测试中文写入测试中文写入测试%d'''%indexVlaue      #print('nextline,nextline%d'%indexVlaue)      textOb.textLine(textStr)      indexVlaue = indexVlaue + 1      break  c.drawText(textOb)  #简单的图片载入  imageValue = 'test.png'  c.drawImage(imageValue,97,97,300,300)  c.drawImage('test.png',50,50,50,50)  t.split(0,0)  t.drawOn(c,100,1)  c.showPage()  #换页的方式不同的showPage  c.drawString(0,0,'helloword')  c.showPage()  c.save()

注:查询文件路径

可以通过__file__属性,查看文件目录,在相应目录下读取源文件来了解模块如何使用。

>>> import pdfminer

>>> print(pdfminer.__file__)

pdf2txt.py的简单使用方法

python pdf2txt.py -t text -o test.txt test.pdf,其中test.pdf为输入文件,test.txt为输出文件名,-t选项表示解析成的文件类型。