Itext get field coordinates from existing pdf

2019-02-11 01:14发布

问题:

First of All, I'm not Java Developer:( I just need small programm, that will output to me coordinates of field by field name from existing pdf file, that I will type when I call my class from command line, something like this:

javac GetField.java
java GetField <myForm.pdf>, <myFieldName>

I'm using itext on my server. Now I'm trying to run simple code:

import com.itextpdf.text.*;
import com.itextpdf.text.pdf.*;
import java.io.*;
import java.util.*;
import java.awt.List;

class HelloWorld{
  public static void main(String[] args) throws IOException {
    PdfReader reader = new PdfReader("Noname.pdf");

    AcroFields fields = reader.getAcroFields();

    float[] positions = fields.getFieldPositions("Signature");
    System.out.println( positions );

  }
}

But I have error: "Type mismatch: cannot convert from List to float[]". When I replace

float[] positions = fields.getFieldPositions("Signature");
System.out.println( positions );

with

System.out.println( fields.getFieldPositions("Signature") );

I got result "[com.itextpdf.text.pdf.AcroFields$FieldPosition@36af35b1]", but I need float values. Can you help me please with this task?

回答1:

To completely solve the problem, I wrote this java class:

// GetSigPos.java 
import com.itextpdf.text.*;
import com.itextpdf.text.pdf.*;
import java.io.*;
//import java.util.*;
import java.util.List;
//import java.awt.List;

class GetSigPos {
  public static void main(String[] args) throws IOException {
    String pdfFile = args[0];
    PdfReader reader = new PdfReader(pdfFile);

    AcroFields fields = reader.getAcroFields();

    for(String signame : fields.getBlankSignatureNames()) {
      List<AcroFields.FieldPosition> positions = fields.getFieldPositions(signame);
      Rectangle rect = positions.get(0).position; // In points:
      float left   = rect.getLeft();
      float bTop   = rect.getTop();
      float width  = rect.getWidth();
      float height = rect.getHeight();

      int page = positions.get(0).page;
      Rectangle pageSize = reader.getPageSize(page);
      float pageHeight = pageSize.getTop();
      float top = pageHeight - bTop;

      System.out.print(signame + "::" + page + "::" + left + "::" + top + "::" + width + "::" + height + "\n");
    }
  }
}

Then I can run it in command line:

javac GetSigPos.java
java GetSigPos "MyForm.pdf"

Or in my php program I can execute them using this command:

exec('java -cp .:/usr/local/bin/pdfbox/itextpdf-5.4.4.jar:/usr/local/bin/pdfbox GetSigPos "'.$pdfName.'" 2>&1', $output);

echo '<pre>';
print_r($output);
echo '</pre>';

P.S. Don't forget to type CLASSPATH to your java! I'm using Centos 6:

vi /root/.bash_rofile

And type this:

export JAVA_HOME=/usr/lib/jvm/jre-1.5.0-gcj
export PATH=$PATH:$JAVA_HOME/bin
export CLASSPATH=.:/usr/local/bin/pdfbox/itextpdf-5.4.4.jar:/usr/local/bin/pdfbox


标签: java linux itext