PDFBox получает ограничивающую рамку текстовых результатов неправильного размераJAVA

Программисты JAVA общаются здесь
Ответить Пред. темаСлед. тема
Anonymous
 PDFBox получает ограничивающую рамку текстовых результатов неправильного размера

Сообщение Anonymous »

Я хочу использовать PDFBox, чтобы получить тексты из PDF-файла с их ограничивающими рамками. Мне удалось собрать здесь код, который делает почти это, но, как вы можете видеть, полученные мной ограничивающие рамки (нарисованные синим цветом) имеют неправильный размер, как если бы я выбрал тексты. Где в моем коде расчеты могли пойти не так?

Код: Выделить всё

class CustomPDFTextStripper : PDFTextStripper() {

@Throws(IOException::class)
override fun writeString(text: String, textPositions: List) {
// Initialize bounding box coordinates
val wordSeparator = wordSeparator
val word: MutableList = ArrayList()

// Get the page height to correctly adjust the Y-coordinates
val page = document.getPage(0)
val pageHeight = page.mediaBox.height

for (text in textPositions) {
val thisChar = text.unicode
if (thisChar != null && thisChar.isNotEmpty()) {
if (thisChar != wordSeparator) {
word.add(text)
} else if (word.isNotEmpty()) {
printWord(word, pageHeight)
word.clear()
}
}
}
if (word.isNotEmpty()) {
printWord(word, pageHeight)
}
}

@Throws(IOException::class)
fun printWord(word: List, pageHeight: Float) {
if (word.isEmpty()) return

// Create a bounding box for the word
var boundingBox: Rectangle2D? = null
for (text in word) {
val box = Rectangle2D.Float(text.xDirAdj, pageHeight - text.yDirAdj - text.heightDir, text.widthDirAdj, text.heightDir)
if (boundingBox == null) {
boundingBox = box
} else {
boundingBox.add(box)
}
}

// Draw the bounding box
val page = document.getPage(0) // Assumes drawing on the first page
PDPageContentStream(document, page, PDPageContentStream.AppendMode.APPEND, true, true).use { contentStream ->
contentStream.setStrokingColor(Color.BLUE)
contentStream.setLineWidth(1f)
if (boundingBox != null) {
contentStream.addRect(boundingBox.x.toFloat(), boundingBox.y.toFloat()+boundingBox.height.toFloat(), boundingBox.width.toFloat(), boundingBox.height.toFloat())
contentStream.stroke()
}
}

// Print word and bounding box details
val builder = StringBuilder()
for (text in word) {
builder.append(text.unicode)
}
println("${builder.toString()} [(X=${boundingBox!!.x}, Y=${boundingBox.y}) height=${boundingBox.height} width=${boundingBox.width}]")
}
Результат:
[img]https://i.sstatic .net/MaUoZpBW.png[/img]


Подробнее здесь: https://stackoverflow.com/questions/787 ... rrect-size
Реклама
Ответить Пред. темаСлед. тема

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

  • Похожие темы
    Ответы
    Просмотры
    Последнее сообщение

Вернуться в «JAVA»