java – 使用PDFbox确定文档中单词的坐标
|
我正在使用PDFbox来提取PDF文档中的单词/字符串的坐标,并且迄今已经成功地确定了单个字符的位置.这是迄今为止的代码,从PDFbox doc: package printtextlocations;
import java.io.*;
import org.apache.pdfbox.exceptions.InvalidPasswordException;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPage;
import org.apache.pdfbox.pdmodel.common.PDStream;
import org.apache.pdfbox.util.PDFTextStripper;
import org.apache.pdfbox.util.TextPosition;
import java.io.IOException;
import java.util.List;
public class PrintTextLocations extends PDFTextStripper {
public PrintTextLocations() throws IOException {
super.setSortByPosition(true);
}
public static void main(String[] args) throws Exception {
PDDocument document = null;
try {
File input = new File("C:pathtoPDF.pdf");
document = PDDocument.load(input);
if (document.isEncrypted()) {
try {
document.decrypt("");
} catch (InvalidPasswordException e) {
System.err.println("Error: Document is encrypted with a password.");
System.exit(1);
}
}
PrintTextLocations printer = new PrintTextLocations();
List allPages = document.getDocumentCatalog().getAllPages();
for (int i = 0; i < allPages.size(); i++) {
PDPage page = (PDPage) allPages.get(i);
System.out.println("Processing page: " + i);
PDStream contents = page.getContents();
if (contents != null) {
printer.processStream(page,page.findResources(),page.getContents().getStream());
}
}
} finally {
if (document != null) {
document.close();
}
}
}
/**
* @param text The text to be processed
*/
@Override /* this is questionable,not sure if needed... */
protected void processTextPosition(TextPosition text) {
System.out.println("String[" + text.getXDirAdj() + ","
+ text.getYDirAdj() + " fs=" + text.getFontSize() + " xscale="
+ text.getXScale() + " height=" + text.getHeightDir() + " space="
+ text.getWidthOfSpace() + " width="
+ text.getWidthDirAdj() + "]" + text.getCharacter());
}
}
这产生一系列包含每个字符的位置的行,包括空格,如下所示: String[202.5604,41.880127 fs=1.0 xscale=13.98 height=9.68814 space=3.8864403 width=9.324661]P ‘P’是字符.我在PDFbox中找不到一个功能来查找单词,而且我对Java不够熟悉,即使空格也包含在内,可以将这些字符准确地连接到单词中进行搜索.有没有人处于类似的状况,如果是这样呢?我真的只需要单词中第一个字符的坐标,以便零件简化,但是我将如何匹配一个字符串与这种输出是超出我的. 解决方法PDFBox中没有功能可以自动提取字词.我目前正在提取数据,将其收集到块中,这是我的过程:>我提取文档的所有字符(称为字形)并将其存储在列表中. 我把这个方法应用到我的工作,它的工作很好. (编辑:鄂州站长网) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
