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
Related
I store my html page in asset folder and insert it to my sqlite.
i store my html page as text in sqlite.
Anyone know how to load my html page into webview?
i've tried to add some code, and not working
if (info.size() != 0) {
lu.setText(info.get(2));
WebView wb = (WebView) findViewById(R.id.mywebview);
wb.loadDataWithBaseURL("file:///android_asset/"+lu,"text/html","UTF-8",null);
}
You question already has well elaborated answers here on SO Webview load html from assets directory... I believe one of the answers should solve your problem... Hope that helps gudluck.
what is lu?, should it be a comma instead of +?
In any case, the method loadDataWithBaseURL takes 5 arguments:
base, data, mimetype, encoding, historyUrl
E.g:
wbHelp.loadDataWithBaseURL("file:///android_asset/",
readAssetFileAsString("index.html"),
"text/html",
"UTF-8",
null);
readAssetFileAsString is as follows:
private String readAssetFileAsString(String sourceHtmlLocation)
{
InputStream is;
try
{
is = getContext().getAssets().open(sourceHtmlLocation);
int size = is.available();
byte[] buffer = new byte[size];
is.read(buffer);
is.close();
return new String(buffer, "UTF-8");
}
catch(IOException e)
{
e.printStackTrace();
}
return "";
}
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.
I am an iOS developer but have been tasked with updating our company's android apps also (so I have little android experience) The android app currently loads PDFs from raw and then displays them in another pdf reader application also installed on the android... however I would like to instead get the pdf's from the internet.
this is the code being using to show the pdf stored locally.
if (mExternalStorageAvailable==true && mExternalStorageWriteable==true)
{
// Create a path where we will place our private file on external
// storage.
Context context1 = getApplicationContext();
File file = new File(context1.getExternalFilesDir(null).toString() + "/pdf.pdf");
URL url = new URL("https://myurl/pdf.pdf");
URLConnection urlConnection = url.openConnection();
InputStream in = new BufferedInputStream(urlConnection.getInputStream());
OutputStream os = new FileOutputStream(file);
try {
byte[] data = new byte[in.available()];
in.read(data);
os.write(data);
Uri path = Uri.fromFile(file);
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(path, "application/pdf");
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
} catch (IOException e) {
// Unable to create file, likely because external storage is
// not currently mounted.
Log.w("ExternalStorage", "Error writing " + file, e);
Context context2 = getApplicationContext();
CharSequence text1 = "PDF File NOT Saved";
int duration1 = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(context2, text1, duration1);
toast.show();
} finally {
in.close();
os.close();
}
}
Eventually the pdf's will come from a website and the website will require an HTML post request sent to it before the PDF can be downloaded. I think I will be able to figure out the HTML post, but for now how can I download a PDF from the internet and have it display. I tried changing the URI to point to the location but that didn't work, or I structured it incorrectly.
Also keep in mind for security reasons I do not want to display this using google viewer and a webview
You just need to read from a distant server. I'd try something like:
URL url = new URL("http://www.mydomain.com/slug");
URLConnection urlConnection = url.openConnection();
InputStream in = new BufferedInputStream(urlConnection.getInputStream());
try {
readStream(in); // Process your pdf
} finally {
in.close();
}
You may also want to checkout the AndroidHttpClient class to make http requests directly (GET or POST in your application).
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
I am right now working on an app which works as a book-stack,where user can read books of their choice,now what i am doing is,displaying the html pages that i've made,in a web-view in my application.
Now this application works only if the user has full time internet connection on his phone.
What exactly i want is when they first open the application,they would need internet connection and then the app should be able to download that page and store it in local database so the user can read it later on without having any internet connect.
So is there any possible way to download the html page and store it in local database so user can use the app even if he is not connected to internet?
I can post my code here if needed be.
Any smallest tip or help would be really great as i am stuck here since long now:(
EDIT 1:
So i successfully downloaded the HTLM page from the website,but now the problem that i am facing is,that i cannot see any of the images of the downloaded html. What can be a proper solution for this?
Here what's the mean of "Local Database"?
Preferred way is download your pages in either Internal Storage(/<data/data/<application_package_name>) (by default on non rooted device is private to your application) or on External Storage(public access). Then refer the pages from that storage area when user device has not a internet connection (offline mode).
Update: 1
To store those pages, you can use simple File read/write operation in Android.
For example:
String FILENAME = "hello_file";
String string = "hello world!";
FileOutputStream fos = openFileOutput(FILENAME, Context.MODE_PRIVATE);
fos.write(string.getBytes());
fos.close();
This example store file hello_file in your application's internal storage directory.
Update: 2 Download Web-Content
HttpClient httpClient = new DefaultHttpClient();
HttpContext localContext = new BasicHttpContext();
HttpGet httpGet = new HttpGet("http://www.xxxx.com");
HttpResponse response = httpClient.execute(httpGet, localContext);
String result = "";
BufferedReader reader = new BufferedReader(
new InputStreamReader(
response.getEntity().getContent()
)
);
String line = null;
while ((line = reader.readLine()) != null){
result += line + "\n";
}
// Now you have the whole HTML loaded on the result variable
So write result variable in File, using my update 1 code. Simple.. :-)
Don't forget to add these two permission in your android application's manifest file.
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.INTERNET"></uses-permission>
Code snippet for downloading web page. Check the comments in the code. Just provide the link ie www.mytestpage.com/story1.htm as downloadlink to the function
void Download(String downloadlink,int choice)
{
try {
String USERAGENT;
if(choice==0)
{
USERAGENT ="Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10_5_7; en-us) AppleWebKit/530.17 (KHTML, like Gecko) Version/4.0 Safari/530.17";
}
else
{
USERAGENT ="Mozilla/5.0 (Linux; U; Android 2.1-update1; en-us; ADR6300 Build/ERE27) AppleWebKit/530.17 (KHTML, like Gecko) Version/4.0 Mobile Safari/530.17";
}
URL url = new URL(downloadlink);
//create the new connection
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
//set up some things on the connection
urlConnection.setRequestProperty("User-Agent", USERAGENT); //if you are not sure of user agent just set choice=0
urlConnection.setRequestMethod("GET");
urlConnection.setDoOutput(true);
urlConnection.connect();
//set the path where we want to save the file
File SDCardRoot = Environment.getExternalStorageDirectory();
File dir = new File (SDCardRoot.getAbsolutePath() + "/yourfolder");
if(!dir.exists())
{
dir.mkdirs();
}
File file = new File(dir, "filename"); //any name abc.html
//this will be used to write the downloaded data into the file we created
FileOutputStream fileOutput = new FileOutputStream(file);
//this will be used in reading the data from the internet
InputStream inputStream = urlConnection.getInputStream();
//this is the total size of the file
int totalSize = urlConnection.getContentLength();
//variable to store total downloaded bytes
int downloadedSize = 0;
//create a buffer...
byte[] buffer = new byte[1024];
int bufferLength = 0; //used to store a temporary size of the buffer
//write the contents to the file
while ( (bufferLength = inputStream.read(buffer)) > 0 ) {
fileOutput.write(buffer, 0, bufferLength);
}
//close the output stream when done
fileOutput.close();
inputStream.close();
urlConnection.disconnect();
//catch some possible errors...
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}