How to read a pdf using itext library in android

2019-07-03 06:43发布

问题:

I am a newbie in android world. I tired to create a android project using eclipse IDE, in which i tried reading a pdf file with the help of itext library. This pgm is not showing any output.Please tell me how to correct the code,so that i can extract the text from pdf file stored in Assets folder in the project.

The program code is given as :

public class hello extends Activity {
    /** Called when the activity is first created. */
    public static final String LOG_TAG="Fifth";
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        AssetManager assetManager =getAssets();
        InputStream istr = null;
        PdfReader reader=null;
        String str=null;
        int n=0;
        try {
            istr =(InputStream) assetManager.open("FirstPdf");


             reader=new PdfReader(istr);
             n=reader.getNumberOfPages();
            Log.v(LOG_TAG,"n value:" +n);
         str=reader.getPageContent(2).toString();
        }
        catch (Exception e)
        {
            e.printStackTrace();
        } 

        TextView tv = new TextView(this);
        tv.setText(n);
        setContentView(tv);
    }
}

Regards Thomas

回答1:

Short Answser

Not Supported!

Long Answer

Android's runtime isn't quite JME. iText was never ported to JME in the first place.

Having said that, there are a couple iText->Android ports floating around. But this has only been done by a few Knowledgeable Individuals who have ripped out large portions so they wouldn't have to port Everything to a subset-of-a-subset-plus-some-other-stuff that is the Android Runtime.

I understand that a port of iText Proper (the whole thing) is In The Works, but have no idea if it'll ever go anywhere, or when folks will be able to get their hands on it.



回答2:

try this

public class readPDF extends Activity {

/** Called when the activity is first created. */

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    AssetManager assetManager =getAssets();
    InputStream istr = null;
    PdfReader reader=null;
    String str=null;
    int n=0;
    try {
        istr = this.getResources().openRawResource(R.raw.internals);

         reader=new PdfReader(istr);
         n=reader.getNumberOfPages();
         System.out.println("String"+str);
        Log.v("LOG:","n value:" +n);
     str=reader.getPageContent(2).toString();

    }
    catch (Exception e)
    {
        e.printStackTrace();
    } 

    TextView tv = (TextView)findViewById(R.id.hellotxt);
    tv.setText(String.valueOf(n));

}

}



标签: android itext