PDF重构时文本定位异常问题求助(附相关代码)
PDF重构中的文本定位问题
我在重构PDF时遇到文本定位问题:已通过text stripper提取所有文本,能在新PDF中使用正确的字体和字号绘制文本,但无法将文本放置在正确位置。
相关示例图:
- 输入PDF示例图
- 输出PDF示例图
提取TextPosition数据的代码
protected void processTextPosition(TextPosition text) { textPositionPDGraphicsStatesMap.put(text, getGraphicsState()); PDGraphicsState state = getGraphicsState(); PDTextState textState = state.getTextState(); float fontSize = textState.getFontSize(); float horizontalScaling = textState.getHorizontalScaling() / 100f; float charSpacing = textState.getCharacterSpacing(); // 将文本状态参数转换为矩阵形式 Matrix parameters = new Matrix( fontSize * horizontalScaling, 0, // 0 0, fontSize, // 0 0, textState.getRise()); // 1 // 文本渲染矩阵(文本空间 -> 设备空间) Matrix ctm = state.getCurrentTransformationMatrix(); Matrix textRenderingMatrix = parameters.multiply(text.getTextMatrix()).multiply(ctm); TextPositionsInfo txtInfo = new TextPositionsInfo(); txtInfo.xDir = text.getXDirAdj(); txtInfo.yDir = text.getYDirAdj(); txtInfo.x = textRenderingMatrix.getTranslateX(); txtInfo.y = textRenderingMatrix.getTranslateY(); txtInfo.textMatrix = textRenderingMatrix; txtInfo.height= text.getHeightDir(); txtInfo.width = text.getWidthDirAdj(); txtInfo.unicode = text.getUnicode(); txtInfo.fontName = text.getFont().getFontDescriptor().getFontName(); txtInfo.fontSize = getActualFontSize(text, getGraphicsState()); pdfGraphicContent.textPositions.add(txtInfo); }
逐字符绘制文本到内容流的代码
private void addTextCharByChar(String string, List<TextPositionsInfo> textinfoList, TextBBoxinfo textBBoxinfo,PDPage page) throws IOException { PDResources res = page.getResources(); currentContentStream.beginText(); if (textBBoxinfo._ElementType.toLowerCase().equals("h2")) { beginMarkedConent(COSName.P); for(TextPositionsInfo textInfo : textinfoList) { PDFont font = getFont(res, textInfo.fontName); currentContentStream.setFont(font, textInfo.fontSize); Matrix _tm = textInfo.textMatrix; currentContentStream.newLineAtOffset(_tm.getTranslateX(), _tm.getTranslateY()); currentContentStream.setTextMatrix(_tm); currentContentStream.showText(textInfo.unicode); } currentContentStream.endMarkedContent(); addContentToCurrentSection(COSName.P, StandardStructureTypes.H2); }else if (textBBoxinfo._ElementType.toLowerCase().equals("h1")) { beginMarkedConent(COSName.P); for(TextPositionsInfo textInfo : textinfoList) { PDFont font = getFont(res, textInfo.fontName); currentContentStream.setFont(font, textInfo.fontSize); currentContentStream.newLineAtOffset(textInfo.textMatrix.getTranslateX(), textInfo.textMatrix.getTranslateY()); currentContentStream.setTextMatrix(textInfo.textMatrix); currentContentStream.showText(textInfo.unicode); } currentContentStream.endMarkedContent(); addContentToCurrentSection(COSName.P, StandardStructureTypes.H1); } currentContentStream.endText(); }
内容的提问来源于stack exchange,提问作者Nitish Kumar
相关产品推荐
相关产品推荐

