赞
踩
正好在做这方面的工作,还是使用fitz,就可以获得字体的大小
具体思路是:现将pdf转换成html,在使用bs4解析html
具体代码如下:
pdf2html:将pdf转换成html,这一步在转换时,有时会丢失一些字体信息
pdf2list:调用pdf2html现将pdf转换成html,在使用BeautifulSoup对html进行解析。
import fitz from bs4 import BeautifulSoup from tqdm import tqdm
- def pdf2html(input_path):
- '''
- 将pdf转成html
- :param input_path:
- :return:
- '''
- doc = fitz.open(input_path)
- html_content = ''
- for page in tqdm(doc):
- html_content += page.get_text('html')
-
- # print('开始输出html文件')html_path
- # #html_content +="</body></html>"
- html_path = "d:/ann/input.html"
- with open(html_path, 'w', encoding='utf-8', newline='')as fp:
- fp.write(html_content)
- return html_content

- def decodestylestr(style_attrs, attr):
- '''
- 解析style
- :param style_attrs:
- :param attr:
- :return:
- '''
- attrvalue = ""
- styles = style_attrs.split(";")
- for sty in styles:
- k, v = sty.split(":")
- v = v.replace("pt", "")
- if k == attr:
- attrvalue = v
- return attrvalue
'运行
- def pdf2list(input_path):
- '''
- 按照p节点提取pdf文本,按照 [文本,left,top,[(fontname、fongsize,fontcolor),]] (fontname、fongsize,fontcolor)一个或多个存储。
- :param input_path:
- :return:
- '''
- html_content = pdf2html(input_path) # pdf转html
- bs_obj = BeautifulSoup(html_content, "html.parser")
-
- #读取P节点
- ptag = bs_obj.findAll("p")
- contents = []
- # 取P节点下文本以及其对应的left值和font-family和font-size的值。
- for p in ptag:
- ptext = p.text
- ptextnospace = ptext.replace(" ", "")
- #如果当前节点text为空,则下一个
- if len(ptextnospace) == 0: # 当前文本为空字符串
- continue
- else:
- pass
-
- '''
- 读取P节点下的style属性
- '''
- postioninfo=('','',)
- if 'style' in p.attrs:
- attributes = p.attrs['style']
- leftvalue = decodestylestr(attributes, "left")
- topvalue = decodestylestr(attributes, "top")
- postioninfo=(leftvalue,topvalue)
- else:
- postioninfo=('','',)
-
- pass
-
- '''
- 获取P节点下的span节点,并读取取style属性,主要包括字体名称、字体大小、字体颜色,是否加粗pdf2html没有提取到。如果有也应该获取
- pspans = p.find_all("span",recursive=False ) recursive=False只获取当前节点下的子节点,不循环其孙子及以下节点
- '''
- pspans = p.find_all("span")
- pspansstyles = []
-
- for pspan in pspans:
- pspantext = pspan.text
- pspantext=pspantext.replace(" ","")
- if len(pspantext) > 0:#当前span节点不为空。
- if 'style' in pspan.attrs:
- attributes = pspan.attrs['style']
- fontfamilyvalue = decodestylestr(attributes, "font-family")
- fontsizevalue = decodestylestr(attributes, "font-size")
- fontcolorvalue = decodestylestr(attributes, "color")
- pspansstyle = (fontfamilyvalue, fontsizevalue,fontcolorvalue)
- if pspansstyle in pspansstyles:#如果字体样式已经存在,则删除,在增加,保持最后的是字体的样子,后续判断要用到字体大小
- pspansstyles.remove(pspansstyle)
- pspansstyles.append(pspansstyle)
- else:
- pass
- ptextattrs = [ptext, postioninfo, pspansstyles]
- contents.append(ptextattrs)
- return contents

Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。