@@ -269,27 +269,44 @@ object PdfExporter {
269269 bounds : RectF ,
270270 pageHeight : Float ,
271271 ) {
272- val pdfX = item.x - bounds.left
273- val pdfY = pageHeight - (item.y - bounds.top)
272+ val lines = item.text.split(' \n ' )
273+ val lineCount = lines.size.coerceAtLeast(1 )
274+
275+ val totalWidth = item.width
276+ val totalHeight = item.height
277+ val fontSize = (totalHeight / lineCount).coerceAtLeast(1f )
278+
279+ val font = PDType1Font .HELVETICA
274280
275281 var textStarted = false
276282 try {
277283 stream.beginText()
278284 textStarted = true
279285 stream.setRenderingMode(RenderingMode .NEITHER )
280-
281- val font = PDType1Font .HELVETICA
282- // Heuristic font size based on height
283- val fontSize = item.height.coerceIn(8f , 24f )
284286 stream.setFont(font, fontSize)
285287
286- // PDF text origin is bottom-left. RecognizedTextData x,y is top-left.
287- stream.newLineAtOffset(pdfX, pdfY - fontSize)
288+ for (i in lines.indices) {
289+ val lineText = lines[i].filter { it.code in 32 .. 126 || it.code in 160 .. 255 }
290+ if (lineText.isEmpty()) continue
288291
289- // Clean text for PDF compatibility
290- val safeText = item.text.filter { it.code in 32 .. 126 || it.code in 160 .. 255 }
291- if (safeText.isNotEmpty()) {
292- stream.showText(safeText)
292+ val linePdfX = item.x - bounds.left
293+ // PDF coordinates are bottom-up. Baseline of line 'i' is:
294+ // pageHeight - topOffset - (i + 1) * fontSize
295+ val linePdfY = pageHeight - (item.y - bounds.top) - (i + 1 ) * fontSize
296+
297+ // stringWidth is in 1/1000 units of the font size
298+ val naturalWidth = font.getStringWidth(lineText) / 1000f * fontSize
299+
300+ if (naturalWidth > 0 ) {
301+ val hScale = totalWidth / naturalWidth
302+ // Apply horizontal scaling and absolute translation
303+ stream.setTextMatrix(Matrix (hScale, 0f , 0f , 1f , linePdfX, linePdfY))
304+ } else {
305+ // Absolute translation without scaling
306+ stream.setTextMatrix(Matrix (1f , 0f , 0f , 1f , linePdfX, linePdfY))
307+ }
308+
309+ stream.showText(lineText)
293310 }
294311 } catch (e: Exception ) {
295312 Logger .w(" PdfExporter" , " Failed to add recognized text layer: ${e.message} " )
0 commit comments