前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >python中解析和生成pdf文件

python中解析和生成pdf文件

作者头像
py3study
发布2020-01-08 15:30:23
2.5K0
发布2020-01-08 15:30:23
举报
文章被收录于专栏:python3python3

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)位置,简单示例:

代码语言:javascript
复制
#!/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选项表示解析成的文件类型。

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2019-09-16 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档