Nurlan Qasımov
Nurlan Qasımov

Reputation: 11

Find a given text position in PDF file

I have a pdf file and I want to find the position / get the height and width of the text on it. So far I am only able to give the position manually by myself, ideally I want to get this position. Here is my code below:

PdfReader pdfReader = new PdfReader("c:/users/qasimovn/desktop/0011E06210410008 __v3.pdf");

PdfStamper pdfStamper = new PdfStamper(pdfReader,
    new FileOutputStream("c:/users/qasimovn/desktop/newSened.pdf"));

Image image = mage.getInstance("c:/users/qasimovn/desktop/imza.jpg");

for (int i = 1; i <= pdfReader.getNumberOfPages(); i++) {

    PdfContentByte content = pdfStamper.getOverContent(i);
    image.setAbsolutePosition(400 f, 50 f);
    content.addImage(image);
}

Upvotes: 0

Views: 917

Answers (1)

Zhenya Prudnikov
Zhenya Prudnikov

Reputation: 94

TEXT 7 allows you to parse pdf files according to different strategies. Here is an example of how to find a TextRectangle using TextMarginFinder. The rest of the strategies are inherited from the EventListener.

    public static final String src
        = "./src/main/resources/pdfs/preface.pdf";
  
    PdfDocument pdfDoc = new PdfDocument(new PdfReader(src));
    TextMarginFinder strategy = new TextMarginFinder();
    PdfCanvasProcessor parser = new PdfCanvasProcessor(strategy);

    for (int i = 1; i <= pdfDoc.getNumberOfPages(); i++) {
        parser.processPageContent(pdfDoc.getPage(i));
        Rectangle textRectangle = strategy.getTextRectangle();
        float left = textRectangle.getLeft();
        float right = textRectangle.getRight();
        float width = textRectangle.getWidth();
      //float etc...
    }
    pdfDoc.close();

Upvotes: 2

Related Questions