简体   繁体   中英

How to open pdf file using iText in Android?

I'm new in Android . I'm implementing PDF document using iText in Android . I want to read PDF document in my application. I don't have an idea how to access PDF doc in my app. I have created but when I run the application I get exception for FileNotFoundException and I also import a PDF file in SD card through DD-MS. But the PDF file does not open in Android. Here is my code:

import com.itextpdf.text.pdf.PdfReader;
import com.itextpdf.text.pdf.codec.Base64.InputStream;


public class MainActivity extends Activity 
{

    private static String FILE = "xyz.pdf";

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

    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        AssetManager assetManager = getAssets();
        InputStream istr = null;
        PdfReader reader = null;
        String str = null;
        int n = 0;
        try
        {
            istr =(InputStream) assetManager.open("xyz.pdf");

            reader=new PdfReader(istr);
            n=reader.getNumberOfPages();
            Log.e("n value:","-> " +n);
            str=reader.getPageContent(2).toString();
        }
        catch(Exception e)
        {
            e.printStackTrace();
        }
        TextView tv = (TextView) findViewById(R.id.textOne);
        tv.setText(str);

    }

}

As far as i know,iText is only for PDF creation, it doesn't contain viewer part.It is a parser, not a renderer. So you need to choose some another library to view pdf.But theare are some excellent code example in SO which you can view whether it meets your requirement..

You can try other solution rather than iText..
- Render a PDF file using Java on Android
- http://andpdf.svn.sourceforge.net/viewvc/andpdf/trunk/

And an excellent working code last of all..
- Example of code to implement a PDF reader

We can Extract data from iText. Here i am extracting text from PDFs file and showing on Edit-text :

String pat = data.getData().getPath();
File f = new File(pat);

static PdfReader read;
read = new PdfReader(new FileInputStream(f));

 PdfReaderContentParser parser;
parser = new PdfReaderContentParser(read);

StringWriter strw;
strw = new StringWriter();

TextExtractionStrategy stretegy;
stretegy = parser.processContent(j, new SimpleTextExtractionStrategy());

strw.write(stretegy.getResultantText());

String da = strw.toString();

edt1.setText(da);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM