矩形在什么尺寸和方向上
PDFTextStripperByArea
的功能addRegion(String regionName, Rectangle2D rect)
。
换句话说,矩形R从哪里开始,它有多大(原点值的尺寸,矩形的尺寸)以及它的走向(图中蓝色箭头的方向),如果new Rectangle(10,10,100,100)
作为第二个给出范围?
矩形在什么尺寸和方向上
PDFTextStripperByArea
的功能addRegion(String regionName, Rectangle2D rect)
。
换句话说,矩形R从哪里开始,它有多大(原点值的尺寸,矩形的尺寸)以及它的走向(图中蓝色箭头的方向),如果new Rectangle(10,10,100,100)
作为第二个给出范围?
new Rectangle(10,10,100,100)
表示矩形的左上角位于 (10, 10) 位置,因此距离 PDF 文档的左侧和顶部 10 个单位。这里的“单位”是 1 pt = 1/72 英寸。
第一个 100 表示矩形的宽度,第二个表示矩形的高度。综上所述,右图是第一张。
我编写了这段代码来提取作为函数参数给出的页面的某些区域:
Rectangle2D region = new Rectangle2D.Double(x, y, width, height);
String regionName = "region";
PDFTextStripperByArea stripper;
stripper = new PDFTextStripperByArea();
stripper.addRegion(regionName, region);
stripper.extractRegions(page);
因此,x 和 y 是 Rectangle 左上角的绝对坐标,然后您指定它的宽度和高度。page 是作为此函数的参数给出的 PDPage 变量。
正在考虑做这样的事情,所以我想我会传递我发现的东西。
这是使用 itext 创建我的原始 pdf 的代码。
import com.lowagie.text.Document
import com.lowagie.text.Paragraph
import com.lowagie.text.pdf.PdfWriter
class SimplePdfCreator {
void createFrom(String path) {
Document d = new Document()
try {
PdfWriter writer = PdfWriter.getInstance(d, new FileOutputStream(path))
d.open()
d.add(new Paragraph("This is a test."))
d.close()
} catch (Exception e) {
e.printStackTrace()
}
}
}
如果你打开 pdf,你会在左上角看到文本。这是显示您正在寻找的测试。
@Test
void createFrom_using_pdf_box_to_extract_text_targeted_extraction() {
new SimplePdfCreator().createFrom("myFileLocation")
def doc = PDDocument.load("myFileLocation")
Rectangle2D.Double d = new Rectangle2D.Double(0, 0, 120, 100)
def stripper = new PDFTextStripperByArea()
def pages = doc.getDocumentCatalog().allPages
stripper.addRegion("myRegion", d)
stripper.extractRegions(pages[0])
assert stripper.getTextForRegion("myRegion").contains("This is a test.")
}
位置 (0, 0) 是文档的左上角。宽度和高度是向下和向右。我能够将范围缩小到 (35, 52, 120, 3) 并且仍然可以通过测试。
所有代码都是用 groovy 编写的。
Code in java using PDFBox.
public String fetchTextByRegion(String path, String filename, int pageNumber) throws IOException {
File file = new File(path + filename);
PDDocument document = PDDocument.load(file);
//Rectangle2D region = new Rectangle2D.Double(x,y,width,height);
Rectangle2D region = new Rectangle2D.Double(0, 100, 550, 700);
String regionName = "region";
PDFTextStripperByArea stripper;
PDPage page = document.getPage(pageNumber + 1);
stripper = new PDFTextStripperByArea();
stripper.addRegion(regionName, region);
stripper.extractRegions(page);
String text = stripper.getTextForRegion(regionName);
return text;
}