I would like to select a pdf file from file manager in android and convert it to text so text to speech can read it. I'm following this documentation from android developer site; however, this example is for opening a text file. I'm using PdfReader class/ library in order to open the file and convert to text. but I don't know how to integrate that with Uri.
Here's the code I need to convert from pdf to text using PdfReader
PdfReader pdfReader = new PdfReader(file.getPath());
stringParser = PdfTextExtractor.getTextFromPage(pdfReader, 1).trim();
pdfReader.close();
I'm calling file manager using intent so the user can select a pdf file
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
intent.setType("*/*");
startActivityForResult(intent, READ_REQUEST_CODE);
}
});
then I'm getting uri and opening file
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent resultData) {
if (requestCode == READ_REQUEST_CODE && resultCode == Activity.RESULT_OK) {
if(resultData != null) {
Uri uri = resultData.getData();
Toast.makeText(MainActivity.this, filePath , Toast.LENGTH_LONG).show();
readPdfFile(uri);
}
}
}
private String readTextFromUri(Uri uri) throws IOException {
StringBuilder stringBuilder = new StringBuilder();
try (InputStream inputStream =
getContentResolver().openInputStream(uri);
BufferedReader reader = new BufferedReader(
new InputStreamReader(Objects.requireNonNull(inputStream)))) {
String line;
while ((line = reader.readLine()) != null) {
stringBuilder.append(line);
}
}
return stringBuilder.toString();
}
public class SyncPdfTextExtractor {
// TODO: When you have your own Premium account credentials, put them down here:
private static final String CLIENT_ID = "FREE_TRIAL_ACCOUNT";
private static final String CLIENT_SECRET = "PUBLIC_SECRET";
private static final String ENDPOINT = "https://api.whatsmate.net/v1/pdf/extract?url=";
/**
* Entry Point
*/
public static void main(String[] args) throws Exception {
// TODO: Specify the URL of your small PDF document (less than 1MB and 10 pages)
// To extract text from bigger PDf document, you need to use the async method.
String url = "https://www.harvesthousepublishers.com/data/files/excerpts/9780736948487_exc.pdf";
SyncPdfTextExtractor.extractText(url);
}
/**
* Extracts the text from an online PDF document.
*/
public static void extractText(String pdfUrl) throws Exception {
URL url = new URL(ENDPOINT + pdfUrl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setDoOutput(true);
conn.setRequestMethod("GET");
conn.setRequestProperty("X-WM-CLIENT-ID", CLIENT_ID);
conn.setRequestProperty("X-WM-CLIENT-SECRET", CLIENT_SECRET);
int statusCode = conn.getResponseCode();
System.out.println("Status Code: " + statusCode);
InputStream is = null;
if (statusCode == 200) {
is = conn.getInputStream();
System.out.println("PDF text is shown below");
System.out.println("=======================");
} else {
is = conn.getErrorStream();
System.err.println("Something is wrong:");
}
BufferedReader br = new BufferedReader(new InputStreamReader(is));
String output;
while ((output = br.readLine()) != null) {
System.out.println(output);
}
conn.disconnect();
}
}
------------------------------------
Copying above code follow below Steps-
Specify the URL of your online PDF document on line 20.
Replace the Client ID and Secret on lines 10 and 11 if you have your own credentials.
use this
Gradle :-
implementation 'com.itextpdf:itextg:5.5.10'
try {
String parsedText="";
PdfReader reader = new PdfReader(yourPdfPath);
int n = reader.getNumberOfPages();
for (int i = 0; i <n ; i++) {
parsedText = parsedText+PdfTextExtractor.getTextFromPage(reader, i+1).trim()+"\n"; //Extracting the content from the different pages
}
System.out.println(parsedText);
reader.close();
} catch (Exception e) {
System.out.println(e);
}
Related
I can't read with Acrobat Reader a created file.pdf on my Android Studio (pdf is an exemple, I also need .jpg or .txt) because there is an error.
private void uriGetDocumentGedFindById(Integer id, String extension) throws Throwable {
String url = PreferencesFragment.DEFAULT_SERVER_URL_DOCUMENTGEDFINDBYID + id;
MyHttpClient client = new MyHttpClient(url);
URL url2 = new URL(url);
HttpURLConnection urlConnection = (HttpURLConnection) url2.openConnection();
responsUriGetDocumentGedFindById = client.getResponseHttpURLConnection(urlConnection);
String name = id.toString() + "." + extension;
saveFile(responsUriGetDocumentGedFindById, name, PreferencesFragment.DOCUMENTS_FOLDER);
}
public void saveFile(String json, String name, String path) throws IOException {
try {
FileWriter writer = new FileWriter(
new File(mContext.getFilesDir().toString() + path, name));
writer.write(json);
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
public String getResponseHttpURLConnection(HttpURLConnection urlConnection) {
StringBuffer response = null;
try {
BufferedReader in = new BufferedReader(
new InputStreamReader(urlConnection.getInputStream()));
String inputLine;
response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
} catch (IOException e) {
e.printStackTrace();
}
return response.toString();
}
I receive this from my back : via Postman on the left (this is functional, I can read the pdf), in my file.pdf (on Android Studio) on the right (there is an error with Acrobat Reader)
So first I can't read my file.pdf and second the file.pdf is bigger than the original whitout any additional information (original 200Ko and my file.pdf 400Ko) this is perhaps a clue...
My back :
#Override
public ResponseEntity<Resource> findByIdDocumentGed(Integer id) throws FileNotFoundException {
DocumentGed documentGed = documentGedService.findByIdDocumentGed(id);
InputStreamResource resource = null;
try {
Integer idFile = documentGed.getFichierCourant().getId();
String extensionFile = documentGed.getFichierCourant().getTypeFichier().getExtension();
File file = new File(nasIris + "/ged/import/" + idFile + "." + extensionFile);
resource = new InputStreamResource(new FileInputStream(file));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
if (resource == null) {
return new ResponseEntity<>(resource, new HttpHeaders(), HttpStatus.NOT_FOUND);
}
return new ResponseEntity<>(resource, new HttpHeaders(), HttpStatus.OK);
}
Have you tried to use FileOutputStream instead FileWriter ?
I'm trying to send data in Android Studio. I'm making a login function. So I need to send data to the Webserver. I already made a Webserver, but I can't because of this error:
Caused by: android.os.NetworkOnMainThreadException
I think that error is pointed at this line:
InputStream is = conn.getInputStream();
I've been struggling for 3 days. Please help.
public class MainActivity extends AppCompatActivity {
EditText id;
EditText pass;
String custid;
String password;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
id=(EditText)findViewById(R.id.idtext);
pass=(EditText)findViewById(R.id.passtext);
}
public void ButtonClick(View view){
custid=id.getText().toString();
password=pass.getText().toString();
Toast.makeText(this, "버튼접근."+custid+password, Toast.LENGTH_SHORT).show();
Properties prop = new Properties();
prop.setProperty("custid", custid);
prop.setProperty("password", password);
String encodedString = encodeString(prop);
URL url = null;
try {
url = new URL ("http://192.168.56.1:9999/SEBank/customer/login.action" + "?" + encodedString);
URLConnection conn = url.openConnection();
conn.setUseCaches(false);
InputStream is = conn.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(is));
char[] buff = new char[512];
int len = -1;
while( (len = br.read(buff)) != -1) {
System.out.print(new String(buff, 0, len));
}
br.close();
} catch (java.io.IOException e) {
e.printStackTrace();
}
}
public String encodeString(Properties params) {
StringBuffer sb = new StringBuffer(256);
Enumeration names = params.propertyNames();
while (names.hasMoreElements()) {
String name = (String) names.nextElement();
String value = params.getProperty(name);
sb.append(URLEncoder.encode(name) + "=" + URLEncoder.encode(value) );
if (names.hasMoreElements()) sb.append("&");
}
return sb.toString();
}
}
You can put this on your code
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
but I think the best solution is using AsyncTasks or Volley
If the error is "android.os.NetworkOnMainThreadException ...", try enclose your code with below snippet:
AsyncTask.execute(new Runnable() {
#Override
public void run() {
InputStream is = conn.getInputStream();
// other code
}
});
I am trying to send html file content to request parameter.
The problem area is on the server side, getting some extra characters.
<!Document....> the other side ?<!Document...>
Why this "?" mark comes.
Can any one help me to figure out.
Thanks in advance.
Finally I got solution of my problem
import java.io.*;
public class UTF8ToAnsiUtils {
// FEFF because this is the Unicode char represented by the UTF-8 byte order mark (EF BB BF).
public static final String UTF8_BOM = "\uFEFF";
public static void main(String args[]) {
try {
if (args.length != 2) {
System.out
.println("Usage : java UTF8ToAnsiUtils utf8file ansifile");
System.exit(1);
}
boolean firstLine = true;
FileInputStream fis = new FileInputStream(args[0]);
BufferedReader r = new BufferedReader(new InputStreamReader(fis,
"UTF8"));
FileOutputStream fos = new FileOutputStream(args[1]);
Writer w = new BufferedWriter(new OutputStreamWriter(fos, "Cp1252"));
for (String s = ""; (s = r.readLine()) != null;) {
if (firstLine) {
s = UTF8ToAnsiUtils.removeUTF8BOM(s);
firstLine = false;
}
w.write(s + System.getProperty("line.separator"));
w.flush();
}
w.close();
r.close();
System.exit(0);
}
catch (Exception e) {
e.printStackTrace();
System.exit(1);
}
}
private static String removeUTF8BOM(String s) {
if (s.startsWith(UTF8_BOM)) {
s = s.substring(1);
}
return s;
}
}
You will find more detail in this link..
http://www.rgagnon.com/javadetails/java-handle-utf8-file-with-bom.html
I am trying to get last 10 rows from file but not able to fetch.
i have two activities:
in the first, i want to write text from an EditText to a file.
in the second activity i try to read the stored data and write it to a textView
public class Date_Location extends Activity {
ImageView imageView;
EditText editTextDate, editTextLocation, editTextEdit;
private static final String TAG = Date_Location.class.getName();
private static final String FILENAME = "myFile.txt";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.date_location);
editTextDate = (EditText) findViewById(R.id.editText1);
editTextLocation = (EditText) findViewById(R.id.editText2);
editTextEdit = (EditText) findViewById(R.id.editText3);
imageView = (ImageView) findViewById(R.id.next);
}
public void goNext(View view) {
String Date = editTextDate.getText().toString();
String Location = editTextLocation.getText().toString();
String Comment = editTextEdit.getText().toString();
writeToFile(Date);
writeToFile(Location);
writeToFile(Comment);
Intent intent = new Intent(this, Detail_Data.class);
startActivity(intent);
Date_Location.this.finish();
}
private void writeToFile(String data) {
String newline = "\r\n";
try {
OutputStreamWriter oswName = new OutputStreamWriter(openFileOutput(
FILENAME, Context.MODE_APPEND));
oswName.write(newline);
oswName.write(data);
oswName.close();
} catch (IOException e) {
Log.e(TAG, "File write failed: " + e.toString());
}
}
}
And my second Activity is below
public class Detail_Data extends Activity {
TextView textView1;
ImageView imageView;
private static final String FILENAME = "myFile.txt";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.detail_data);
textView1 = (TextView) findViewById(R.id.textView1);
imageView = (ImageView) findViewById(R.id.imageView2);
String date = readFromFile();
textView1.setText(date);
}
private String readFromFile() {
String ret = "";
try {
InputStream inputStream = openFileInput(FILENAME);
ArrayList<String> bandWidth = new ArrayList<String>();
if (inputStream != null) {
InputStreamReader inputStreamReader = new InputStreamReader(
inputStream);
BufferedReader bufferedReader = new BufferedReader(
inputStreamReader);
String receiveString = "";
StringBuilder stringBuilder = new StringBuilder();
while ((receiveString = bufferedReader.readLine()) != null) {
stringBuilder.append(receiveString+'\n');
bandWidth.add(receiveString);
if (bandWidth.size() == 10)
bandWidth.remove(0);
}
ret = stringBuilder.toString();
inputStream.close();
}
} catch (FileNotFoundException e) {
Log.i("File not found", e.toString());
} catch (IOException e) {
Log.i("Can not read file:", e.toString());
}
return ret;
}
public void goNext(View view) {
imageView.setColorFilter(0xFFFF3D60, PorterDuff.Mode.MULTIPLY);
Intent intent = new Intent(this, Agreement.class);
startActivity(intent);
Detail_Data.this.finish();
}
}
please if any one have any idea then help me. I have tried with other solution too but then also i am not getting last 10 records. Instead of last 10 data i am getting all the records which is written in file.
Firstly, If you are writing file on SDcard, be sure that you have added the uses-permission tag in AndroidManifest.xml
<uses-permission Android:name="Android.permission.WRITE_EXTERNAL_STORAGE"></uses-permission>
Secondly, don't forget flush()
oswName.write(data);
oswName.flush();
oswName.close();
Then, there is something wrong with your readFromFile() method,
remove this line from while loop
stringBuilder.append(receiveString+'\n');
and add this right after the while loop
for(String str : bandWidth)
stringBuilder.append(str + "\n");
readFromFile() should be like following
private String readFromFile() {
String ret = "";
try {
InputStream inputStream = openFileInput(FILENAME);
ArrayList<String> bandWidth = new ArrayList<String>();
if (inputStream != null) {
InputStreamReader inputStreamReader = new InputStreamReader(
inputStream);
BufferedReader bufferedReader = new BufferedReader(
inputStreamReader);
String receiveString = "";
StringBuilder stringBuilder = new StringBuilder();
while ((receiveString = bufferedReader.readLine()) != null) {
bandWidth.add(receiveString);
if (bandWidth.size() == 10)
bandWidth.remove(0);
}
for(String str : bandWidth)
stringBuilder.append(str + "\n");
ret = stringBuilder.toString();
inputStream.close();
}
} catch (FileNotFoundException e) {
Log.i("File not found", e.toString());
} catch (IOException e) {
Log.i("Can not read file:", e.toString());
}
return ret;
}
After opening the input/output stream, use that methods:
import java.io.FileInputStream;
import java.io.FileOutputStream;
public class Files {
public static String readStringFile(FileInputStream fis) throws java.io.IOException {
StringBuffer fileContent = new StringBuffer("");
byte[] buffer = new byte[1024];
while (fis.read(buffer) != -1) {
fileContent.append(new String(buffer));
}
return fileContent.toString();
}
public static void writeStringFile(FileOutputStream fos, String text) throws java.io.IOException {
fos.write(text.getBytes());
}
}
First, create the FileInputStream or FileOutputStream with your desired file name and then call the methods above. Please notice that the methods only work for reading and writing strings.
You store each line to list and remove 0 position only if list size = 10
So as 1st step store all file in list:
Instead
while ((receiveString = bufferedReader.readLine()) != null) {
stringBuilder.append(receiveString+'\n');
bandWidth.add(receiveString);
if (bandWidth.size() == 10)
bandWidth.remove(0);
}
Write
while ((receiveString = bufferedReader.readLine()) != null) {
stringBuilder.append(receiveString+'\n');
bandWidth.add(receiveString);
}
After copy last 10 lines to new list.
For example if you have :
List<String> bandWidth = new ArrayList<String>(Arrays.asList("a1", "a2", "a3","a4", "a5", "a6","a7", "a8", "a9","a10", "a11", "a12"));
Than with subList:
List<String> bandWidth10rows= bandWidth.subList(bandWidth.size()-10, bandWidth.size());
It will copy last 10 list items to new list.
Totally it should be something like:
while ((receiveString = bufferedReader.readLine()) != null) {
stringBuilder.append(receiveString+'\n');
bandWidth.add(receiveString);
}
List<String> bandWidthLastTenRows= bandWidth.subList(bandWidth.size()-10, bandWidth.size());
I want to copy the pdf file from URL to and save the pdf file content in bitmap.
I have used following code but I am not getting the as it is content of pdf. It is giving something in different format.Please help me and tell me where I am wrong.
public class MyActivity extends ListActivity implements OnClickListener
{
Button addResumeFromUrlBtn;
EditText addResumeFromUrlTxt;
String resume;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.resumeselection);
addResumeFromUrlTxt = (EditText)findViewById(R.id.addResumeFromURLTxt);
addResumeFromUrlBtn = (Button)findViewById(R.id.addResumeFromURLBtn);
addResumeFromUrlBtn.setOnClickListener(this);
}
public String readPDF() throws Exception
{
BufferedReader in = null;
String page = "";
try {
HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet();
request.setURI(new URI("http://www.inkwelleditorial.com/pdfSample.pdf"));
HttpResponse response = client.execute(request);
in = new BufferedReader
(new InputStreamReader(response.getEntity().getContent()));
StringBuffer sb = new StringBuffer("");
String line = "";
String NL = System.getProperty("line.separator");
while ((line = in.readLine()) != null) {
sb.append(line + NL);
}
in.close();
page = sb.toString();
} finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {e.printStackTrace();}
}
}
return page;
}
public void onClick(View v)
{
if(v == addResumeFromUrlBtn)
{
try {
resume = readPDF();
} catch (Exception e)
{
e.printStackTrace();
}
RelativeLayout l = (RelativeLayout)findViewById(R.id.resumeRelativelayout);
TextView txt = new TextView(this);
txt.setLayoutParams(new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT));
txt.setDrawingCacheEnabled(true);
txt.setText(resume);
txt.measure(MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED),
MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED));
txt.layout(0, 0, txt.getMeasuredWidth(), txt.getMeasuredHeight());
txt.setDrawingCacheEnabled(false);
l.addView(txt);
}
}
}
Thanks
Monali
File file = new File(fileLocation);
if (file.exists()) {
Uri path = Uri.fromFile(file);
Intent intent = new Intent(Intent.ACTION_VIEW); //Set Intent action view pdf file
intent.setDataAndType(path, "application/pdf"); //Set data type
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
try {
startActivity(intent); //Start Activity
} catch (ActivityNotFoundException e) {
Toast.makeText(OpenPdf.this,
"No Application Available to View PDF",
Toast.LENGTH_SHORT).show();
}
}
This is the for display pdf
First of there is no support for pdf in Android so you need to open in some other app like adob or if you want to do it right way then need make the load lib like vudroid and apdfviewer .
apdfviewer is very good but there is no support how to compile source code, actually all lib work with c++ in backend so you need to install the ndk.
Vudroid is slow but you can compile easily.
I hope this will help you.