I have wrote this code for download pdf from url and file url is this-
String fileURL= "http://www.vivekananda.net/PDFBooks/History_of_India.pdf";
Code this
public static void 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.getResponseCode();
c.connect();
InputStream in = c.getInputStream();
byte[] buffer = new byte[1024];
int len1 = 0;
while ((len1 = in.read(buffer)) > 0) {
f.write(buffer, 0, len1);
}
f.close();
} catch (Exception e) {
e.printStackTrace();
}
}
but this shows file not found exception with response code 405.I dont know why this happened.Please help..!!
This is my code where i had create file in sd card-
Code this
public void createPdfFile(){
String extStorageDirectory = Environment.getExternalStorageDirectory()
.toString();
File folder = new File(extStorageDirectory, "pdf");
folder.mkdir();
file = new File(folder, "storrage_data.pdf");
try {
file.createNewFile();
} catch (IOException e1) {
e1.printStackTrace();
}
}`
After this i am calling download method in thread like this from onResume(); beacuse from onCreate it will give error "Network On Main Thread".where i am wrong now i don't konw :(
Code this
public void downloadFile(){
new Thread(new Runnable() {
#Override
public void run() {
Downloader.DownloadFile(url, file);
showPdf();
}
}).start();
}
The possible reason is the folder in which you want to does not exist. First check if it exist. Create it if not. Then create fileoutputstream and write to it.
I suggest you use the DownloadManager. There are too many problems that can arise during download to handle all of them yourself. Just think of temporary loss of connectivity in the middle of download...
Below is some code I pulled out of my app and slightly modified to get rid of parts you don't need.
public void downloadAndOpenPdf(String url,final File file) {
if(!file.isFile()) {
DownloadManager dm = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
DownloadManager.Request req = new DownloadManager.Request(Uri.parse(url));
req.setDestinationUri(Uri.fromFile(file));
req.setTitle("Some title");
BroadcastReceiver receiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
unregisterReceiver(this);
if (file.exists()) {
openPdfDocument(file);
}
}
};
registerReceiver(receiver, new IntentFilter(
DownloadManager.ACTION_DOWNLOAD_COMPLETE));
dm.enqueue(req);
Toast.makeText(this, "Download started", Toast.LENGTH_SHORT).show();
}
else {
openPdfDocument(file);
}
}
public boolean openPdfDocument(File file) {
Intent target = new Intent(Intent.ACTION_VIEW);
target.setDataAndType(Uri.fromFile(file), "application/pdf");
target.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
try {
startActivity(target);
return true;
} catch (ActivityNotFoundException e) {
Toast.makeText(this,"No PDF reader found",Toast.LENGTH_LONG).show();
return false;
}
}
Your code is correct. Now you need to download your pdf file to External storage or wherever you want to download and save it.
Delete this code and try again.
//c.setRequestMethod("GET");
//c.setDoOutput(true);
//c.getResponseCode();
//c.connect();
I think URL.openConnection() has description of connection already, so c.connect() isn't necessary.
Related
I have webview which we have php application loaded. the application lists item which the user selects. when a list is selected. it does a redirect with a file path from the server which is captured using the below code.
1.get the file name and extension from the url and use it too create a new file which we will use it for writing outputstream to it.
2. call the downloadFile() method to read the file
3. call the ShoWeDrawings() passing the filename to use it to read the file and pass it to open it using intent action_view with another app.
public boolean shouldOverrideUrlLoading(WebView view, String url) {
// This is my web site, so do not override; let my WebView load the page
if(url.contains("Files") ) {
String filename = url.substring(url.lastIndexOf('/') +1);
String extStorageDirectory = getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS) + "/EASM";
File folder = new File(extStorageDirectory);
if (!folder.exists()) {
folder.mkdir();
}
File file = new File(folder, filename);
try {
file.createNewFile();
} catch (IOException e1) {
e1.printStackTrace();
}
Downloader.DownloadFile( url,file);
ShoWeDrawings(filename);
return true;
}
return false;
}
download class
public class Downloader {
private static Context context;
// public Context context ;
public static void 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(false);
c.setConnectTimeout(10000);
c.setReadTimeout(10000);
c.connect();
int status = c.getResponseCode();
// InputStream in = c.getErrorStream();
InputStream in = c.getInputStream();
// c.getErrorStream();
byte[] buffer = new byte[4096];
int len1 = 0;
while ((len1 = in.read(buffer)) > 0) {
f.write(buffer, 0, len1);
}
f.close();
in.close();
// Toast.makeText(context.getApplicationContext(), "A new file is downloaded successfully", Toast.LENGTH_SHORT).show();
}
catch (Exception e) {
e.printStackTrace();
}
}
}
ShoWeDrawings method
private void ShoWeDrawings(String filename) {
File file = new File( getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS)+"/EASM/"+filename);
// Uri uri = Uri.fromFile(file);
try {
Intent mIntent = new Intent(Intent.ACTION_VIEW);
// mIntent.putExtra(DocumentsContract.EXTRA_INITIAL_URI, Uri.fromFile(file));
// mIntent.putExtra(Intent.EXTRA_STREAM,Uri.fromFile(file));
mIntent.setDataAndType(Uri.fromFile(file), "application/octet-stream");
mIntent.setPackage("com.solidworks.eDrawingsAndroid");
mIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
// Intent.createChooser(mIntent, "Choose Application");
startActivity(mIntent);
}
catch (Exception e)
{
e.printStackTrace();
}
}
now the problem comes with the opening of the file using the targeted app. i get a toast error message. Im not sure if its due to permissions or its the app that has problems. By the way i have upgraded to android 11 and i cant even view data/ folder on the tablet. i can only see the files via pc. The error message that im getting is - filename:error copying file to documents folder see picture below.
I tried to change the code and restarting the tablet thinking it might have been the updates that i pushed.
I have tried out many ways like using async task and default download manager, but, I ended with downloading a file (I believe that it is downloading file. php instead of the requireddownload.pdf file), which is not the required file. However the name and extension of downloaded file is the requrieddownload.pdf.
Thankyou in advance.
First step declaring persmissions in AndroidManifest.xml
<uses-permission android:name="android.permission.INTERNET"></uses-permission>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"></uses-permission>
Create a downloader class
public class Downloader {
public static void 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 len1 = 0;
while ((len1 = in.read(buffer)) > 0) {
f.write(buffer, 0, len1);
}
f.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
Finally creating an activity which downloads the PDF file from internet,
public class PDFFromServerActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
String extStorageDirectory = Environment.getExternalStorageDirectory()
.toString();
File folder = new File(extStorageDirectory, "pdf");
folder.mkdir();
File file = new File(folder, "Read.pdf");
try {
file.createNewFile();
} catch (IOException e1) {
e1.printStackTrace();
}
Downloader.DownloadFile("http://www.nmu.ac.in/ejournals/aspx/courselist.pdf", file);
showPdf();
}
public void showPdf()
{
File file = new File(Environment.getExternalStorageDirectory()+"/pdf/Read.pdf");
PackageManager packageManager = getPackageManager();
Intent testIntent = new Intent(Intent.ACTION_VIEW);
testIntent.setType("application/pdf");
List list = packageManager.queryIntentActivities(testIntent, PackageManager.MATCH_DEFAULT_ONLY);
Intent intent = new Intent();
intent.setAction(Intent.ACTION_VIEW);
Uri uri = Uri.fromFile(file);
intent.setDataAndType(uri, "application/pdf");
startActivity(intent);
}
}
So I'm trying to download a PDF file using HttpURLConnection and I think I've done everything right with the input- and outputstreams, yet when I open the downloaded PDF file (using the built in File Manager in Android and/or ADB), or just inspect it by transferring it to OS X, it's completely empty and the size shows 0 bytes.
The site I'm trying to download the PDF from is:
http://www.pdf995.com/samples/pdf.pdf
Here's my code
public static void DownloadFile(final String fileURL, final File directory) {
Thread thread = new Thread(new Runnable(){
#Override
public void run() {
try {
try {
FileOutputStream f = new FileOutputStream(directory);
URL u = new URL(fileURL);
c = (HttpURLConnection) u.openConnection();
c.setRequestMethod("GET");
//c.setRequestProperty("Content-Type", "application/pdf");
//c.setDoOutput(true);
c.connect();
Log.d("debugz", Integer.toString(c.getContentLength()));
InputStream in = c.getInputStream();
byte[] buffer = new byte[1024];
int len1 = 0;
while ((len1 = in.read(buffer)) > 0) {
f.write(buffer, 0, len1);
}
f.flush();
f.getFD().sync();
f.close();
} catch (Exception e) {
e.printStackTrace();
}
} catch (Exception e) {
e.printStackTrace();
}
}
});
thread.start();
}
public static String getPDF(String pdfurl) {
String extStorageDirectory = Environment.getExternalStorageDirectory()
.toString();
File folder = new File(extStorageDirectory, "schematisktscheman");
folder.mkdir();
File file = new File(folder, "schemainfo.pdf");
try {
file.createNewFile();
} catch (IOException e1) {
e1.printStackTrace();
}
DownloadFile(pdfurl, file);
return null; //added return
}
In my main activity:
SchedulePdfProcessor.getPDF("http://www.pdf995.com/samples/pdf.pdf");
sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.parse("file://" + Environment.getExternalStorageDirectory() + "/schematisktscheman/schemainfo.pdf")));
EDIT: I ran the network code on the main thread, which threw an exception. Now creating a new thread for the downloading and it gets the example PDF (http://www.pdf995.com/samples/pdf.pdf) and puts its content in the file all fine.
Thanks to #greenapps!
First, replace:
f.close();
with:
f.flush();
f.getFD().sync();
f.close();
This ensures everything is written to disk before continuing.
Then, you need to use MediaScannerConnection and scanFile() to get the MediaStore to know about the updated file.
I ran the network code on the main thread, which threw an exception. Now creating a new thread for the downloading and it gets the example PDF (http://www.pdf995.com/samples/pdf.pdf) and puts its content in the file all fine.
Thread thread = new Thread(new Runnable(){
#Override
public void run() {
try {
try {
FileOutputStream f = new FileOutputStream(directory);
URL u = new URL(fileURL);
c = (HttpURLConnection) u.openConnection();
c.setRequestMethod("GET");
//c.setRequestProperty("Content-Type", "application/pdf");
//c.setDoOutput(true);
c.connect();
Log.d("debugz", Integer.toString(c.getContentLength()));
InputStream in = c.getInputStream();
byte[] buffer = new byte[1024];
int len1 = 0;
while ((len1 = in.read(buffer)) > 0) {
f.write(buffer, 0, len1);
}
f.flush();
f.getFD().sync();
f.close();
} catch (Exception e) {
e.printStackTrace();
}
} catch (Exception e) {
e.printStackTrace();
}
}
});
thread.start();
I am trying to display pdf file in android webview by calling amazon url. But it only shows white screen.Nothing to load.
When i use url other then amazon it shows pdf file in webview.
I have also tried this:
http://docs.google.com/gview?embedded=true&url=" + MYURL
I have also tried under write url as well: And works well.
http://www.durgasoft.com/Android%20Interview%20Questions.pdf
If any one have any suggestion please guide me.
Here is my code for your reference:
webView.getSettings().setJavaScriptEnabled(true);
webView.getSettings().setPluginState(PluginState.ON);
String url = Common.getPdfFromAmazon("52f3761d290c4.pdf");
webView.loadUrl(url);
Android Menifest.xml also give Internet Permission:
**<uses-permission android:name="android.permission.INTERNET" />**
i can also try this "http://docs.google.com/gview?embedded=true&url=" + url ;
Thank you.
For displaying a PDF from amazon web service you need to first download and store the PDF to your device and then open it through PDF reader/viewer application available on your device.
1>> Call DownloadFileAsync() to invoke download process and pass your amazon web service url.
new DownloadFileAsync().execute(url);
2>> Do the download PDF process in AsyncTask.
class DownloadFileAsync extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected String doInBackground(final String... aurl) {
try {
String extStorageDirectory = Environment.getExternalStorageDirectory().toString();
File dir = new File(extStorageDirectory, "pdf");
if(dir.exists()==false) {
dir.mkdirs();
}
File directory = new File(dir, "original.pdf");
try {
if(!directory.exists())
directory.createNewFile();
} catch (IOException e1) {
e1.printStackTrace();
}
URL url = new URL(aurl[0]);
URLConnection conexion = url.openConnection();
int lenghtOfFile = conexion.getContentLength();
conexion.connect();
conexion.setReadTimeout(10000);
conexion.setConnectTimeout(15000); // millis
FileOutputStream f = new FileOutputStream(directory);
InputStream in = conexion.getInputStream();
byte[] buffer = new byte[1024];
int len1 = 0;
while ((len1 = in.read(buffer)) > 0) {
f.write(buffer, 0, len1);
}
f.flush();
f.close();
in.close();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String unused) {
}
}
3>> Call showPdfFromSdCard() after downloading pdf.
public static void showPdfFromSdCard(Context ctx) {
File file = new File(Environment.getExternalStorageDirectory() + "/pdf/original.pdf");
PackageManager packageManager = ctx.getPackageManager();
Intent testIntent = new Intent(Intent.ACTION_VIEW);
testIntent.setType("application/pdf");
List list = packageManager.queryIntentActivities(testIntent, PackageManager.MATCH_DEFAULT_ONLY);
Intent intent = new Intent();
intent.setAction(Intent.ACTION_VIEW);
Uri uri = Uri.fromFile(file);
intent.setDataAndType(uri, "application/pdf");
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
try {
ctx.startActivity(intent);
} catch (ActivityNotFoundException e) {
Toast.makeText(ctx,
"No Application Available to View PDF",
Toast.LENGTH_SHORT).show();
}
}
4>> Call deletePdfFromSdcard() in your onResume()
public static void deletePdfFromSdcard(){
File file = new File(Environment.getExternalStorageDirectory()+"/pdf/original.pdf");
boolean pdfDelete = file.delete();
}
You need to add the internet permission to your manifest file outside of the application tag.
<uses-permission android:name="android.permission.INTERNET" />
after 2 day research no solution find for that so i try to first download PDF file from Amazon web service and store into the SD-Card then open PDF File Here My Code
Note:- This solution is only try for Show PDF in Web view From Amazon web Service.
from other web service try this Code:-
WebView webview=(WebView)findviewbyid(R.id.Webview);
String MyURL= "this is your PDF URL";
String url = "http://docs.google.com/gview?embedded=true&url=" + MyURL;
Log.i(TAG, "Opening PDF: " + url);
webView.getSettings().setJavaScriptEnabled(true);
webView.loadUrl(url);
----------------------------------------------------------------------------------------------> For Amazon Web Service Please Try This code
1>> Download PDF from Amazon WebService
public static void 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.connect();
InputStream in = c.getInputStream();
byte[] buffer = new byte[1024];
int len1 = 0;
while ((len1 = in.read(buffer)) > 0) {
f.write(buffer, 0, len1);
}
f.close();
} catch (Exception e) {
e.printStackTrace();
}
}
2>> Show PDF From SD-Card
public static void showPdfFromSdCard(Context ctx)
{
File file = new File(Environment.getExternalStorageDirectory()+"/pdf/MyPdf.pdf");
PackageManager packageManager = ctx.getPackageManager();
Intent testIntent = new Intent(Intent.ACTION_VIEW);
testIntent.setType("application/pdf");
List list = packageManager.queryIntentActivities(testIntent, PackageManager.MATCH_DEFAULT_ONLY);
Intent intent = new Intent();
intent.setAction(Intent.ACTION_VIEW);
Uri uri = Uri.fromFile(file);
intent.setDataAndType(uri, "application/pdf");
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
try {
ctx.startActivity(intent);
}
catch (ActivityNotFoundException e) {
Toast.makeText(ctx,
"No Application Available to View PDF",
Toast.LENGTH_SHORT).show();
}
After Download PDF showPdfFromSdCard Method called.
After show PDF you Delete PDF file From SD-card
Here Code for Delete PDF From SD-Card
public static void deletePdfFromSdcard(){
File file = new File(Environment.getExternalStorageDirectory()+"/pdf/MyPdf.pdf");
boolean pdfDelete = file.delete();
}
I will do some modification in #Monika Moon code,
if you don't want to save the File in the device, the process explained above is too long as well as required FileProvider to open the pdf in external pdf viewer.
so for the better solution please follow the below steps.
Step 1:
please add this library to your gradle file.
AndroidPdfViewer
Step 2:
add this in your XML view->
<com.github.barteksc.pdfviewer.PDFView
android:id="#+id/pdfView"
android:layout_width="match_parent"
android:layout_height="match_parent"
/>
Step 3:
PDFView pdfView;
InputStream inputStream;
pdfView=findViewById(R.id.pdfView);
class DownloadFileAsync extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
if (mProgressDialog!=null)
{
Utils.cancelProgressDialog(mProgressDialog);
}
mProgressDialog = Utils.showProgressDialog(DocumentViewActivity.this);
super.onPreExecute();
}
#Override
protected String doInBackground(final String... aurl) {
try {
URL url = new URL(aurl[0]);
URLConnection conexion = url.openConnection();
conexion.connect();
conexion.setReadTimeout(20000);
conexion.setConnectTimeout(25000); // millis
inputStream = conexion.getInputStream();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String unused) {
if (inputStream != null) {
pdfView.fromStream(inputStream)
.defaultPage(0)
.password(null)
.scrollHandle(null)
.enableAntialiasing(true)
.scrollHandle(new DefaultScrollHandle(DocumentViewActivity.this))
.spacing(0)
.onLoad(new OnLoadCompleteListener() {
#Override
public void loadComplete(int nbPages) {
Utils.cancelProgressDialog(mProgressDialog);
}
})
.load();
}else {
Utils.cancelProgressDialog(mProgressDialog);
}
}
}
#Override
protected void onDestroy() {
if (inputStream!=null)
{
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
super.onDestroy();
}
Final Step : call new DownloadFileAsync().execute(url);
I have made an app in which i am successfully downloading pdf files from internet by URL. And sotre them to the app's internal storage with making a folder app_Pdf. But now I want to open that file with third party app like adobe pdf viewer...ect. I have tried so many way, i have goggling much for this issue. I have also read about making first content provider and serve pdf file by this questing : How to open a PDF stored in Internal Memory but i get the error : invalid path....
Please any buddy help me to solve this issue. It will be good if give me some working code
Thank you very much in advance.....
This is how i download and store file in internal memory :
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
downloadFile("http://www.testdemo.net/testdemo/test/test/test.pdf");
}
public boolean downloadFile(String path)
{
try
{
URL url = new URL(path);
URLConnection ucon = url.openConnection();
ucon.setReadTimeout(5000);
ucon.setConnectTimeout(10000);
InputStream is = ucon.getInputStream();
BufferedInputStream inStream = new BufferedInputStream(is, 1024 * 5);
File file = new File(getDir("Pdf", Context.MODE_WORLD_READABLE) + "/yourfile.pdf");
if (file.exists())
{
file.delete();
}
file.createNewFile();
FileOutputStream outStream = new FileOutputStream(file);
byte[] buff = new byte[5 * 1024];
int len;
while ((len = inStream.read(buff)) != -1)
{
outStream.write(buff, 0, len);
}
outStream.flush();
outStream.close();
inStream.close();
}
catch (Exception e)
{
e.printStackTrace();
return false;
}
return true;
}
}
and this is how i tried to view pdf from internal storage :
File file = new File(getDir("Pdf", Context.MODE_PRIVATE) + "/yourfile.pdf");
Uri internal = Uri.fromFile(file);
viewPdf(internal);
private void viewPdf(Uri file) {
Intent intent;
intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(file, "application/pdf");
try {
startActivity(intent);
} catch (ActivityNotFoundException e) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("No Application Found");
builder.setMessage("Download one from Android Market?");
builder.setPositiveButton("Yes, Please",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Intent marketIntent = new Intent(Intent.ACTION_VIEW);
marketIntent.setData(Uri.parse("market://details?id=com.adobe.reader"));
startActivity(marketIntent);
}
});
builder.setNegativeButton("No, Thanks", null);
builder.create().show();
Log.v("","Exception : "+e);
}
Please help me....