xps坐标提取算法
- 要解析一个xps文档,需要先对文件进行解压,并指向文档页(1.fpage这样子的)所在的目录listDir :
f = zipfile.ZipFile(xpsPath,'r')
f.extractall(xpsUnzipDir)
f.close()
coordinateDic = {"Resource": None,'Pages':[]}
pagesDir = os.path.join(xpsUnzipDir,r'Documents1Pages'.encode('gb18030'))
listDir = os.listdir(pagesDir)
- 接着定位到1.fpage文件的路径pageXmlPath,读取其内容到xmlContent:
xmlContent = fs.read()
fs.close()
- 然后获得xml树根:
pageXml = etree.XML(xmlContent)
- 继续找树根下的节点:
FixedPageChildren = pageXml.getchildren()
- 然后对这些节点分类:
分类思想:根据其标签是'Glyphs', 'Path'还是'Canvas'分三种情况处理:
- 'Canvas':继续找子节点子节点人可能为是'Glyphs', 'Path'还是'Canvas',分别将三种类型的节点存为列表的不同键的值tmpCanvasDic['GlyphsList'],tmpCanvasDic['PathList'],tmpCanvasDic['CanvasList'],然后将tmpCanvasDic作为xmlDic['Canvas'+str(i)]
- ** 'Glyphs'**:将此类节点直接存在xmlDic['GlyphsList']里
- ** 'Path' **:将此类节点直接存在xmlDic['PathList']
线提取
1. Dic['Canvas'+str(i)]里有线
for key in xmlDic.keys():
if 'Canvas' in key: #处理含有Canvas父节点的情况
canvasRenderTransformMatrix = xmlDic[key]['RenderTransform']
canvasRootClip = xmlDic[key]['Clip'] #限定渲染区域,超出区域的不会显示,暂时不处理该限定
addHLineToPage(pageDic,xmlDic[key]['PathList'],canvasRenderTransformMatrix)
addVLineToPage(pageDic, xmlDic[key]['PathList'], canvasRenderTransformMatrix)
** 其中,addHLineToPage()函数是提取水平线的,addVLineToPage()提取竖线**
内层canvas里可能还有线,也要提取
for childCanvas in xmlDic[key]['CanvasList']: #第二层canvas
childCanvasRenderTransformMatrix = [float(it) for it in childCanvas.attrib['RenderTransform'].split(',')] if childCanvas.attrib.has_key('RenderTransform') else [1,0,0,1,0,0]
childCanvasChildren = childCanvas.getchildren()
childCanvasPathList = []
for child in childCanvasChildren:
if 'Path' in child.tag:
childCanvasPathList.append(child)
addHLineToPage(pageDic,childCanvasPathList,childCanvasRenderTransformMatrix,canvasRenderTransformMatrix)
addVLineToPage(pageDic, childCanvasPathList, childCanvasRenderTransformMatrix,
canvasRenderTransformMatrix)
2. xmlDic.keys()里key 为 'PathList'的,也是线
addHLineToPage(pageDic,xmlDic[key],canvasRenderTransformMatrix)
addVLineToPage(pageDic,xmlDic[key],canvasRenderTransformMatrix)
glyph提取
1. Dic['Canvas'+str(i)]里
for glyph in xmlDic[key]['GlyphsList']:
extractGlyphs(glyph,pageDic)
xmlDic.keys()里key 为 'GlyphsList'的
extractGlyphs(glyph,pageDic)
- 然后合并x坐标相等的竖线,合并y坐标相等的横线
- 然后组成页
coordinateDic['Pages'].append(pageDic)
若果要提取表格内的数据,则需要加如下功能:
dataDic={'Resource': coordinateDic['Resource'], 'Pages': coordinateDic['Pages']}
dataDic=Test.getInTableTextCoodinate(dataDic,'xps')
coordinateDic['Pages']=dataDic['Pages']
- 其中,Test.getInTableTextCoodinate(dataDic,'xps')函数就是返回的表格数据
接下来由段组成行,得到中间格式信息。