I made an Android application to view a pdf file extracted from a URL by integrating the pdfViewer library into my code. The first application downloads the file from the network to an external SD card, after which the application opens using the PdfViewer library. It works fine if the file size is small, but if the PDF file contains images and the size is larger, the loaded file size shown on sdcard is 0kb. Can someone help me why this is so?
The following is the 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;
f.write(buffer, 0, len);
}
f.close();
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
}
source
share