reading pdf from url using pdfViewer library in android app - android

I made an android app for viewing Pdf file fetched from URL by integrating pdfViewer library in my code.Firstly app downloading the file from web to external sd card then from there the app is getting opened with PdfViewer library.It is working fine if the file size is small but if the pdf file contains images and size is more , the downloaded file size shown in sdcard is 0kb.
Can someone help me out why this is so?
Following is java code :
public class MainActivity extends Activity {
static Context applicationContext;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
applicationContext = getApplicationContext();
String extStorageDirectory = Environment.getExternalStorageDirectory().toString();
File folder = new File(extStorageDirectory, "pdfDownloads");
folder.mkdir();
File file = new File(folder, "android.pdf");
try {
if(!file.exists()) {
file.createNewFile();
}
} catch (IOException e1) {
e1.printStackTrace();
}
boolean downloadFile = downloadFile("http://www.irs.gov/pub/irs-pdf/fw4.pdf", file);
if (file!=null && file.exists() && file.length() > 0){
Intent intent = new Intent(this, com.example.soniapdf.Second.class);
intent.putExtra(PdfViewerActivity.EXTRA_PDFFILENAME,
file.getAbsolutePath());
startActivity(intent);
}
}
public static boolean downloadFile(String fileUrl, File directory) {
try {
FileOutputStream f = new FileOutputStream(directory);
URL u = new URL(fileUrl);
HttpURLConnection c = (HttpURLConnection) u.openConnection();
c.setRequestMethod("GET");
c.setDoOutput(true);
c.connect();
InputStream in = c.getInputStream();
byte[] buffer = new byte[1024];
int len = 0;
//
int fileLength = c.getContentLength();
long total = 0;
//
Toast.makeText(applicationContext, "Downloading PDF...", 2000).show();
while ((len = in.read(buffer)) > 0) {
total += len;
//Toast.makeText(applicationContext, "Downloading PDF: remaining " + (fileLength / total )+ "%", 1).show();
f.write(buffer, 0, len);
}
f.close();
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
}

This is a way for showing PDF in android app that is embedding the PDF document to android webview using support from http://docs.google.com/viewer
pseudo
String doc="<iframe src='http://docs.google.com/viewer?url=+location to your PDF File+'
width='100%' height='100%'
style='border: none;'></iframe>";
a sample is is shown below
String doc="<iframe src='http://docs.google.com/viewer?url=http://www.iasted.org/conferences/formatting/presentations-tips.ppt&embedded=true'
width='100%' height='100%'
style='border: none;'></iframe>";
Code
WebView wv = (WebView)findViewById(R.id.webView);
wv.getSettings().setJavaScriptEnabled(true);
wv.getSettings().setPluginsEnabled(true);
wv.getSettings().setAllowFileAccess(true);
wv.loadUrl(doc);
//wv.loadData( doc, "text/html", "UTF-8");
and in manifest provide
<uses-permission android:name="android.permission.INTERNET"/>
SEE THIS ANSWER
EDIT
If your PDF document is accessible online, use the Google Docs Viewer to open your PDF in a WebView
REFER
wv.loadUrl("https://docs.google.com/gview?embedded=true&url=http://www.irs.gov/pub/irs-pdf/fw4.pdf");
Don't Know how Stable These are
Here is the list of the other open sources PDF readers running on the top of the Android
Android PDF Viewer
APDFViewer
droidreader
android-pdf
Please note that these and any other project derived from MuPDF is bound by the terms of GPL and may not be suitable for the commerical use.
The following is a list of SDKs suitable for commerical use:
PDFTron
Adobe
Qoppa
Radaee

Related

Android Download and Open PDF File from URL ending with .aspx

I am able to download and view from url ending with *.pdf with the below code
private static final int MEGABYTE = 1024 * 1024;
public static void downloadFile(String fileUrl, File directory){
try {
URL url = new URL(fileUrl);
HttpURLConnection urlConnection = (HttpURLConnection)url.openConnection();
//urlConnection.setRequestMethod("GET");
//urlConnection.setDoOutput(true);
urlConnection.connect();
InputStream inputStream = urlConnection.getInputStream();
FileOutputStream fileOutputStream = new FileOutputStream(directory);
int totalSize = urlConnection.getContentLength();
byte[] buffer = new byte[MEGABYTE];
int bufferLength = 0;
while((bufferLength = inputStream.read(buffer))>0 ){
fileOutputStream.write(buffer, 0, bufferLength);
}
fileOutputStream.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
but I have tried to download PDF file with url ending with .aspx as its generate PDF dynamically and its not working .
I have also tried to embed with webview with google doc url "http://docs.google.com/viewer?url="+URL but its also not working.
Can anyone help in this?
'.aspx' Is ASP.NET page that is actually web form.
Web forms are contained in files with a ".aspx" extension; these files
typically contain static (X)HTML markup or component markup.
So what you are loading is a simple HTML page rendered on server side. So you cannot use it to view PDF - in PDF viewer.
Instead of openning '.aspx' from file load this url into WebView - this will work only if there are no additional security on the site you are pointing to.
In case of Google Docs the link you are providing to the WebView should be sharing links like following:
https://drive.google.com/file/d/xx-xxxxxxxxxxxxxxx/view?usp=sharing
Where x's are part of hash. To get this link - click on Share option for the document and then get shareable link.
Before WebView reaches pdf document it could receive few redirects that potentially will be handled by Android itself. To avoid this you need to override WebViewClient#shouldOverrideUrlLoading like in following example:
mWebView.getSettings().setJavaScriptEnabled(true);
mWebView.setWebViewClient(new WebViewClient() {
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return false;
}
});
mWebView.loadUrl("https://drive.google.com/file/d/xx-xxxxxxxxxxxxxxx/view?usp=sharing");
Also you could get direct link to the file using sharable url you get above:
change this:
https://drive.google.com/file/d/xx-xxxxxxxxxxxxxxx/view?usp=sharing
to this:
https://drive.google.com/uc?export=download&id=xx-xxxxxxxxxxxxxxx
or to this:
https://docs.google.com/document/d/xx-xxxxxxxxxxxxxxx/export?format=pdf

Can't read PDF downloaded from server

I'm downloading a PDF from my server.
The server send me a HttpResponse with the InputStream of file's body.
I'm able to write it into a file but, when I try to read it with a PDF reader, it tells me that the file might be corrupted.
I've also noticed that the size of the PDF downloaded directly from web service is twice the size of the PDF downloaded via my application.
The code I use to download and write the PDF file is this:
String fileName = //FILENAME + ".pdf";
fileName = fileName.replaceAll("/", "_");
String extPath = Environment.getExternalStorageDirectory().toString();
String folderName = //FOLDERNAME;
try {
File folder = new File(extPath, folderName);
folder.mkdir();
File pdfFile = new File(folder, fileName);
pdfFile.createNewFile();
URL url = new URL(downloadURL);
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.connect();
InputStream inputStream = urlConnection.getInputStream();
FileOutputStream fileOutputStream = new FileOutputStream(pdfFile);
byte[] buffer = new byte[MEGABYTE];
int bufferLength;
while((bufferLength = inputStream.read(buffer))>0 ){
fileOutputStream.write(buffer, 0, bufferLength);
}
fileOutputStream.close();
Uri path = Uri.fromFile(pdfFile);
Intent pdfIntent = new Intent(Intent.ACTION_VIEW);
pdfIntent.setDataAndType(path, "application/pdf");
pdfIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
try {
startActivity(pdfIntent);
} catch (ActivityNotFoundException e) {
Toast.makeText(getApplicationContext(), "No Application available to view PDF", Toast.LENGTH_SHORT).show();
}
} catch (IOException e) {
e.printStackTrace();
}
//otherStuff
Where I go wrong?
I've also noticed that inside the Headers of HttpResponse contains Content-type:text/html. It shoudld be something like text/pdf?
Your Downloading code seems correct. Based on that and on your comment:
I've also noticed that the size of the PDF downloaded directly from web service is twice the size of the PDF downloaded via my application."
I would suggest checking your URL. It appears that you might be downloading an html page instead of the pdf. To verify you are downloading correctly, change the download directory as follows:
//Default download directory
String extPath = Environment.DIRECTORY_DOWNLOADS;
And check the directory (via the file system, e.g. mount the phone to your computer or a file manager app) for the downloaded content to verify it is a pdf.

Android: How do I download a file from a dynamic url webview

In my app I am using a webview to navigate through to a site, automatically fill in a web form using javascript then submit to obtain a link to a CSV export file.
The link looks like this: XYZ.com/TEST/index/getexport?id=130.
I'd like to download the file this URL points to, then when complete read it into a local database but I'm having trouble downloading the linked file.
If I simply try to open the URL in webview I get an error from the webpage telling me no such file exists.
If I use the Download Manager to download it myself, the source code is downloaded as an html file, not the associated .csv file.
I can open the url with an ACTION_VIEW intent and a browser (chrome) downloads the correct file, but this way I have no notification of when the download completes.
Any ideas of how to download my .CSV file?
To download a file from webview use this :
mWebView.setDownloadListener(new DownloadListener(){
public void onDownloadStart(String url, String userAgent, String contentDisposition, String mimetype, long contentLength){
Intent i = new Intent(Intent.ACTION_VIEW);
i.setData(Uri.parse(url));
startActivity(i);
}
});
Hope this helps.
You could resort to manually downloading the file from the url using an AsyncTask.
Here id the background part:
#Override
protected String doInBackground(Void... params) {
String filename = "inputAFileName";
HttpURLConnection c;
try {
URL url = new URL("http://someurl/" + filename);
c = (HttpURLConnection) url.openConnection();
c.setRequestMethod("GET");
c.setDoOutput(true);
c.connect();
} catch (IOException e1) {
return e1.getMessage();
}
File myFilesDir = new File(Environment
.getExternalStorageDirectory().getAbsolutePath()
+ "/Download");
File file = new File(myFilesDir, filename);
if (file.exists()) {
file.delete();
}
if ((myFilesDir.mkdirs() || myFilesDir.isDirectory())) {
try {
InputStream is = c.getInputStream();
FileOutputStream fos = new FileOutputStream(myFilesDir
+ "/" + filename);
byte[] buffer = new byte[1024];
int len1 = 0;
while ((len1 = is.read(buffer)) != -1) {
fos.write(buffer, 0, len1);
}
fos.close();
is.close();
} catch (Exception e) {
return e.getMessage();
}
if (file.exists()) {
return "File downloaded!";
} else {
Log.e(TAG, "file not found");
}
} else {
Log.e(TAG, "unable to create folder");
}
}
Perhaps it would make sense to refactor it so that the file is returned. Then you get the file as an argument in onPostExecute as soon as the download is complete.

Load the pdf file in app from assets

I have a PDF file stored in my assets. I want to load the PDF from my assets and read it in the app itself without using any 3rd party app to view.
I got the solution in this link. It works fine when selecting files from sdcard.
Following snippet might help you accessing files from asset folder and then open it:
private void ReadFromAssets()
{
AssetManager assetManager = getAssets();
InputStream in = null;
OutputStream out = null;
File file = new File(getFilesDir(), "file.pdf");
try
{
in = assetManager.open("file.pdf");
out = openFileOutput(file.getName(), Context.MODE_WORLD_READABLE);
copyFile(in, out);
in.close();
in = null;
out.flush();
out.close();
out = null;
} catch (Exception e)
{
Log.e("tag", e.getMessage());
}
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(
Uri.parse("file://" + getFilesDir() + "/file.pdf"),
"application/pdf");
startActivity(intent);
}
and copyFile method is as follows:
private void copyFile(InputStream in, OutputStream out) throws IOException
{
byte[] buffer = new byte[1024];
int read;
while ((read = in.read(buffer)) != -1)
{
out.write(buffer, 0, read);
}
}
EDIT
For that purpose you'll have to use an ecternal library. It's explained quite well in the link below:
Render a PDF file using Java on Android
Hope this will help you.
Its better if you can open it using a webview
WebView web = (WebView) findViewById(R.id.webView1);
web.loadUrl("file:///android_asset/yourpdf.pdf");
Hope it works.
Ooops just now I checked, the pdf cannot be loaded in the web view
Sorry

android webpages in webview

i want to store webpages inside the android project folder so that a user does nor needs a internet connection to view the webpages. i am using android webview. i am able to see the webpages with the HTTP protocol . My code is as below:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
WebView webview = (WebView) findViewById(R.id.webView1);
// webview.loadUrl("http://www.mysite.com/index.html");
webview.getSettings().setJavaScriptEnabled(true);
}
but i want to see the webpages offline. is there any way that webpages can be stored as resource in android project folder and view even without internet connection?
yes !
Put them in the /assets folder and access them like this :
webview.loadUrl("file:///android_asset/my_html_page.html");
This questions already have been answered : Webview load html from assets directory
store the webpage in your Asset folder and use
public File getfile(String filename) throws IOException {
// TODO Auto-generated method stub
String externalStorage_path =Environment.getExternalStorageDirectory().toString();
String state = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(state)){
File dir = new File(externalStorage_path + "/yourfilename");
dir.mkdir();
File mfile = new File(dir,filename);
if( mfile.exists()==true) return mfile;
else{
try{
InputStream myInput = mcontext.getAssets().open(filename);
String path =externalStorage_path+"/yourfilename";
OutputStream myOutput = new FileOutputStream (path);
byte[] buffer = new byte[1024];
int length;
try {
while((length = myInput.read(buffer))>0)
myOutput.write(buffer,0,length);
}catch(FileNotFoundException e){Log.d("error",""+ e.toString());
}finally{
myOutput.flush();
myOutput.close();
myInput.close();
}
}catch(IOException e){ }
File dir1 = new File(externalStorage_path + "/yourfilename");
dir1.mkdir();
File mfile1 = new File(dir,filename);
return mfile1;
}
}else if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)){
showToast("External storage has readonly access");
} else if (Environment.MEDIA_REMOVED.equals(state)) {
showToast("External storage not present");
} else if (Environment.MEDIA_UNMOUNTABLE.equals(state)){
showToast("External storage cannot be mounted. Sdcard problem");
}
this will write the file in your storage and can be share by another Application like Adobe to open. jUST called this method.

Categories

Resources