看了https://cloud.tencent.com/developer/ask/sof/1162044,需要获得pdf文件的段落的字体大小。
正好在做这方面的工作,还是使用fitz,就可以获得字体的大小
具体思路是:现将pdf转换成html,在使用bs4解析html
具体代码如下:
pdf2html:将pdf转换成html,这一步在转换时,有时会丢失一些字体信息
pdf2list:调用pdf2html现将pdf转换成html,在使用BeautifulSoup对html进行解析。
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
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。
扫码关注腾讯云开发者
领取腾讯云代金券
Copyright © 2013 - 2025 Tencent Cloud. All Rights Reserved. 腾讯云 版权所有
深圳市腾讯计算机系统有限公司 ICP备案/许可证号:粤B2-20090059 深公网安备号 44030502008569
腾讯云计算(北京)有限责任公司 京ICP证150476号 | 京ICP备11018762号 | 京公网安备号11010802020287
Copyright © 2013 - 2025 Tencent Cloud.
All Rights Reserved. 腾讯云 版权所有