I am trying to extract text from a pdf and want to also include images.
Those images I am getting from pdfbox page object.
Now what I have in mind is using base64converter.
After searching the net I found that I could use The below code to do it
public static String imgToBase64String(final BufferedImage img, final String formatName) {
final ByteArrayOutputStream os = new ByteArrayOutputStream();
try {
ImageIO.write(img, formatName, os);
return Base64.getEncoder().encodeToString(os.toByteArray());
} catch (final IOException ioe) {
return "";
}
}
The problem With the below code is that in react-native.android dose not include BufferedImage , ImageIO or Base64 in its SDK
How am I going to do this? Are there any alternative way in doing this?
Here is the complete code below incase
import com.facebook.react.bridge.NativeModule;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.bridge.ReactContext;
import com.facebook.react.bridge.ReactContextBaseJavaModule;
import com.facebook.react.bridge.ReactMethod;
import java.util.Map;
import java.util.HashMap;
import com.facebook.react.bridge.Promise;
import com.viliussutkus89.android.pdf2htmlex.pdf2htmlEX;
import java.io.File;
import java.io.FileNotFoundException; // Import this class to handle errors
import java.util.Scanner; // Import the Scanner class to read text files
import com.tom_roush.pdfbox.pdmodel.PDDocument;
import com.tom_roush.pdfbox.pdmodel.PDDocumentInformation;
import com.tom_roush.pdfbox.pdmodel.PDDocumentCatalog;
import com.tom_roush.pdfbox.pdmodel.PDPage;
import com.tom_roush.pdfbox.PDXObject;
import com.tom_roush.pdfbox.COSName;
import com.tom_roush.pdfbox.pdmodel.PDResources;
import com.tom_roush.pdfbox.pdmodel.PDPageContentStream;
import com.tom_roush.pdfbox.pdmodel.encryption.AccessPermission;
import com.tom_roush.pdfbox.pdmodel.encryption.StandardProtectionPolicy;
import com.tom_roush.pdfbox.pdmodel.font.PDFont;
import com.tom_roush.pdfbox.pdmodel.font.PDType1Font;
import com.tom_roush.pdfbox.pdmodel.graphics.image.JPEGFactory;
import com.tom_roush.pdfbox.pdmodel.graphics.image.LosslessFactory;
import com.tom_roush.pdfbox.pdmodel.graphics.image.PDImageXObject;
import com.tom_roush.pdfbox.pdmodel.interactive.form.PDAcroForm;
import com.tom_roush.pdfbox.pdmodel.interactive.form.PDCheckBox;
import com.tom_roush.pdfbox.pdmodel.interactive.form.PDComboBox;
import com.tom_roush.pdfbox.pdmodel.interactive.form.PDField;
import com.tom_roush.pdfbox.pdmodel.interactive.form.PDListBox;
import com.tom_roush.pdfbox.pdmodel.interactive.form.PDRadioButton;
import com.tom_roush.pdfbox.pdmodel.interactive.form.PDTextField;
import com.tom_roush.pdfbox.rendering.ImageType;
import com.tom_roush.pdfbox.rendering.PDFRenderer;
import com.tom_roush.pdfbox.text.PDFTextStripper;
import com.tom_roush.pdfbox.android.PDFBoxResourceLoader;
import com.facebook.react.bridge.WritableMap;
import com.facebook.react.bridge.WritableArray;
import com.facebook.react.bridge.WritableNativeArray;
import com.facebook.react.bridge.Arguments;
// below Import are not found in the SDK
import java.io.ByteArrayOutputStream;
import java.awt.image.BufferedImage;
import javax.imageio.ImageIO;
import java.util.Base64;
import java.util.UUID;
public class PdfToHtmlModule extends ReactContextBaseJavaModule {
// add to CalendarModule.java
#Override
public String getName() {
return "PdfToHtmlModule";
}
private ReactApplicationContext appContext;
PdfToHtmlModule(ReactApplicationContext context) {
super(context);
appContext = context;
PDFBoxResourceLoader.init(appContext.getApplicationContext());
}
public static String imgToBase64String(final BufferedImage img, final String formatName) {
final ByteArrayOutputStream os = new ByteArrayOutputStream();
try {
ImageIO.write(img, formatName, os);
return Base64.getEncoder().encodeToString(os.toByteArray());
} catch (final IOException ioe) {
return "";
}
}
#ReactMethod
public void getCompleteTextFromPdf(String pdfFilePath, Promise promise) {
try {
String pdfText = "";
File file = new File(pdfFilePath);
WritableMap params = this.getPDFInfo(file);
WritableArray array = new WritableNativeArray();
PDDocument pddoc = PDDocument.load(file);
if (pddoc.isEncrypted()) {
pddoc.setAllSecurityToBeRemoved(true);
}
for (int i = 0; i < pddoc.getNumberOfPages(); i++) {
PDFTextStripper pdfstripper = new PDFTextStripper();
pdfstripper.setStartPage(i);
pdfstripper.setEndPage(i);
pdfText = pdfstripper.getText(pddoc);
PDPage page = pddoc.getPage(i);
PDResources rs = page.getResources();
for (COSName cosObj : rs.getXObjectNames()) {
PDXObject obj = rs.getXObject(cosObj);
if (obj instanceof PDImageXObject) {
// this doe not work yet
String base64String = PdfToHtmlModule.imgToBase64String(((PDImageXObject) obj).getImage(), "png");
if (base64String != "")
array.pushString("data:image/png;" + base64String);
}
}
array.pushString(pdfText);
}
pddoc.close();
params.putArray("chapters", array);
promise.resolve(params);
} catch (Exception e) {
promise.reject(e.getMessage());
}
}
}
Related
I'm having trouble getting data from OpenSubtitles api. I have looked at many examples for java and python. Below is the class I'm trying to use to authenticate with OpenSubtitles api. After that I want to make request that will return a list of items I can pass to my recyclerview.
package com.shivito.subreader;
import android.app.DownloadManager;
import android.os.Build;
import android.os.Handler;
import android.util.Log;
import androidx.annotation.RequiresApi;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.Base64;
import java.util.Map;
import javax.net.ssl.HttpsURLConnection;
public class OpensubsRequest {
static String username;
static String password;
static String language;
static String useragent;
#RequiresApi(api = Build.VERSION_CODES.O)
public static void makerequest(){
Thread thread = new Thread() {
#Override
public void run() {
try {
Log.d("here","nope");
URL Opensubs = new URL("https://api.opensubtitles.org/xml-rpc");
URL url = new URL("https", "api.opensubtitles.org", 443, "/xml-rpc");
URLConnection uc = Opensubs.openConnection();
Log.d("working",uc.toString());
uc.addRequestProperty("username",username);
uc.addRequestProperty("password",password);
uc.addRequestProperty("language",language);
uc.addRequestProperty("useragent",useragent);
uc.connect();
Log.d("anythingnow", String.valueOf(uc.getAllowUserInteraction()));
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
};
thread.start();
}
}
Okay so in the above class I am trying to send my login information to the api then I try to check if it was successful by reading the response from(uc.getAllowUserInteraction()). Up to this point it always says false. Of course I'm likely not doing this right and I hope someone can point me in the right direction. Thank you!!
I'm making OTP based registrations how do I validate my OTP number please help.
here are 2 scripts
1 is a validation activity
2 is an async task running ok http req
3 there is one more activity which takes a user phone number and sends OTP SMS
which is working fine
I just wanna check if OTP on my edit text matches with message user received
package com.example.test2;
import android.content.Intent;
import android.os.AsyncTask;
import android.widget.Toast;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
class Verifyotp extends AsyncTask<String, Void, Void> {
public static String string;
#Override
protected Void doInBackground(String... strings) {
OkHttpClient client = new OkHttpClient().newBuilder()
.build();
MediaType mediaType = MediaType.parse("text/plain");
RequestBody body = new MultipartBody.Builder().setType(MultipartBody.FORM)
.addFormDataPart("mobile_no", MainActivity.phoneNo)
.addFormDataPart("otp", OTP_activity.OTP)
.build();
Request request = new Request.Builder()
.url("http://127.0.0.1:8000/api/verifyotp")
.method("POST", body)
.addHeader("Accept", "application/json")
.build();
try {
Response response = client.newCall(request).execute();
string = response.body().string();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}
package com.example.test2;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import java.util.Objects;
public class OTP_activity extends AppCompatActivity {
public static String OTP;
TextView mssg;
EditText ED;
Button ver;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_otp_activity);
mssg = (TextView) findViewById(R.id.txtmssg);
ver = (Button) findViewById(R.id.verify);
ED = (EditText)findViewById(R.id.otp);
mssg.setText("We have sent you an SMS on " + MainActivity.phoneNo + " with 4 digit verification code.");
ver.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
OTP = ED.getText().toString();
Verifyotp chk= new Verifyotp();
chk.execute();
int i = Verifyotp.string.length();
if (i < 20){
Toast.makeText(getApplicationContext(),
"please try again.", Toast.LENGTH_LONG).show();
}
else {
Intent in = new Intent(OTP_activity.this, Home_Acivity.class);
startActivity(in);
}
}
});
}
}
Any help is appreciated
You Could Use Firebase OTP Authentication For This Work.
I am working on an application that would send an image with 2 strings but I am not as experienced in this field so i was lost for the last day or two trying to figure this out as i started with a script but didn't work for me
here is the part of script that i worked on which has a bit PHP behind and just show an image in my activity once it's chosen form the gallery with a bit of logic that i understood but didn't really work for me
that's my java code :
package com.example.tuteur;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.AsyncTask;
import android.provider.MediaStore;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Base64;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import java.io.ByteArrayOutputStream;
import java.util.ArrayList;
public class ajouter_photo extends AppCompatActivity implements View.OnClickListener {
ImageView upload_img;
EditText img_text;
EditText img_titre;
Button img_but;
private static final int result_load_img = 1;
private static final String server = "http://192.168.1.3/pfe/saveImg.php";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_ajouter_photo);
upload_img=findViewById(R.id.photo_upload);
img_but=findViewById(R.id.upload_button);
img_text=findViewById(R.id.upload_text_corps);
img_titre=findViewById(R.id.upload_text_title);
upload_img.setOnClickListener(this);
img_but.setOnClickListener(this);
}
#Override
public void onClick(View v) {
switch (v.getId())
{
case(R.id.photo_upload):
Intent galleryIntent = new Intent(Intent.ACTION_PICK,MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(galleryIntent,result_load_img);
break;
case(R.id.upload_button):
Bitmap image =((BitmapDrawable) upload_img.getDrawable()).getBitmap();
new uploadimg(img_text.getText().toString(),image,img_titre.getText().toString());
break;
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if( requestCode==result_load_img && resultCode==RESULT_OK && data != null){
Uri selectedimg = data.getData();
upload_img.setImageURI(selectedimg);
}
}
private class uploadimg extends AsyncTask<Void , Void , Void> {
String text;
Bitmap image;
String titre;
public uploadimg(String text, Bitmap image,String titre) {
this.text = text;
this.image = image;
this.titre=titre;
}
#Override
protected Void doInBackground(Void ... params) {
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
image.compress(Bitmap.CompressFormat.JPEG, 100,byteArrayOutputStream);
String encodedImage = Base64.encodeToString(byteArrayOutputStream.toByteArray(),Base64.DEFAULT);
ArrayList<NameValuePair> dataToSend = new ArrayList<>();
dataToSend.add(new BasicNameValuePair("text",text));
dataToSend.add(new BasicNameValuePair("image",encodedImage));
dataToSend.add(new BasicNameValuePair("titre",titre));
HttpParams httpRequest = getHttpRequestParams();
HttpClient client = new DefaultHttpClient(httpRequest);
HttpPost post =new HttpPost(server);
try {
post.setEntity(new UrlEncodedFormEntity(dataToSend));
client.execute(post);
}
catch(Exception e)
{
Toast.makeText(getApplicationContext(),"erreur" , Toast.LENGTH_SHORT).show();
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
Toast.makeText(getApplicationContext(),"L'image est envoyé",Toast.LENGTH_SHORT).show();
}
}
private HttpParams getHttpRequestParams()
{
HttpParams httpRequestParams = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpRequestParams,1000*30);
HttpConnectionParams.setSoTimeout(httpRequestParams,1000*30);
return httpRequestParams;
}
}
and this is my PHP which just store my image in the server not a data base it was test before I would try with blob
<?php
$name = $_POST["text"];
$image=$_POST["image"];
$decodedImage = base64_decode("$image");
file_put_contents("pictures". $name . ".PNG" , $decodedImage);
?>
Why can not I upload files to the server? When I used Log.d to print to the log screen, it reported an error can not connect to 192.168.10.2:8080 although I have asked for permission to the Internet and read the internal memory of the device.
APIUtils.java
import android.provider.ContactsContract;
public class APIUtils {
public static final String Base_Url = "http://192.168.10.2:8080/Quanlysinhvien/";
public static DataClient getData(){
return RetrofitClient.getClient(Base_Url).create(DataClient.class);
}
}
DataClient.java
import okhttp3.MultipartBody;
import retrofit2.Call;
import retrofit2.http.Multipart;
import retrofit2.http.POST;
import retrofit2.http.Part;
public interface DataClient {
#Multipart
#POST("uploadhinhanh.php")
Call<String> UploadPhot(#Part MultipartBody.Part phto);
}
RetrofitClient.java
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import java.util.concurrent.TimeUnit;
import okhttp3.OkHttpClient;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
public class RetrofitClient {
private static Retrofit retrofit = null;
public static Retrofit getClient(String baseurl){
OkHttpClient builder = new OkHttpClient.Builder()
.readTimeout(5000, TimeUnit.MILLISECONDS)
.writeTimeout(5000, TimeUnit.MILLISECONDS)
.connectTimeout(10000, TimeUnit.MILLISECONDS)
.retryOnConnectionFailure(true)
.build();
Gson gson = new GsonBuilder().setLenient().create();
retrofit = new Retrofit.Builder()
.baseUrl(baseurl)
.client(builder)
.addConverterFactory(GsonConverterFactory.create())
.build();
return retrofit;
}
}
DangKyActivity.java
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.provider.MediaStore;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import com.example.nhutkhanh.demoretrofit2.Retrofit2.APIUtils;
import com.example.nhutkhanh.demoretrofit2.Retrofit2.DataClient;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.InputStream;
import okhttp3.Call;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;
import retrofit2.Callback;
import retrofit2.Response;
public class DangKyActivity extends AppCompatActivity {
ImageView imgdangky;
EditText edtUsername, edtPassword;
Button btnhuy, btnxacnhan;
int Request_Code_Image = 123;
String realpath = "";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_dang_ky);
anhxa();
imgdangky.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(Intent.ACTION_PICK);
intent.setType("image/*");
startActivityForResult(intent, Request_Code_Image);
}
});
btnxacnhan.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
File file = new File(realpath);
String file_path = file.getAbsolutePath();
String[] mangtenfile = file_path.split("\\.");
file_path = mangtenfile[0] + System.currentTimeMillis() + "." + mangtenfile[1];
RequestBody requestBody = RequestBody.create(MediaType.parse("multipart/from-data"), file);
MultipartBody.Part body = MultipartBody.Part.createFormData("uploaded_file", file_path, requestBody);
DataClient dataClient = APIUtils.getData();
retrofit2.Call<String> callback = dataClient.UploadPhot(body);
callback.enqueue(new Callback<String>() {
#Override
public void onResponse(retrofit2.Call<String> call, Response<String> response) {
if(response != null){
String message = response.body();
Log.d("AAA", message);
}
}
#Override
public void onFailure(retrofit2.Call<String> call, Throwable t) {
Log.d("BBB", "Lỗi " + t.getMessage());
}
});
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if(requestCode == Request_Code_Image && resultCode == RESULT_OK && data != null){
Uri uri = data.getData();
realpath = getRealPathFromURI(uri);
try {
InputStream inputStream = getContentResolver().openInputStream(uri);
Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
imgdangky.setImageBitmap(bitmap);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
super.onActivityResult(requestCode, resultCode, data);
}
public String getRealPathFromURI (Uri contentUri) {
String path = null;
String[] proj = { MediaStore.MediaColumns.DATA };
Cursor cursor = getContentResolver().query(contentUri, proj, null, null, null);
if (cursor.moveToFirst()) {
int column_index = cursor.getColumnIndexOrThrow(MediaStore.MediaColumns.DATA);
path = cursor.getString(column_index);
}
cursor.close();
return path;
}
private void anhxa() {
imgdangky = (ImageView)findViewById(R.id.imageViewDK);
edtPassword = (EditText)findViewById(R.id.editTextDKMK);
edtUsername = (EditText)findViewById(R.id.editTextDKTK);
btnhuy = (Button)findViewById(R.id.buttonHuy);
btnxacnhan = (Button)findViewById(R.id.buttonXacNhan);
}
}
MainActivity.java
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
I am creating an widget to access the events stored in a google calendar.
Target : Android 2.1
I have included following external jar :
google-collect-1.0-rc1.jar jsr305.jar
gdata-calendar-2.0.jar,
gdata-calendar-meta-2.0.jar,
gdata-client-1.0.jar,
gdata-client-meta-1.0.jar,
gdata-core-1.0.jar
I get the following exception :
com.google.gdata.util.ParseException : org.xml.sax
here is my code: HelloWidget.java
package de.thesmile.android.widget2;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.util.ArrayList;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProvider;
import android.content.Context;
import android.util.Log;
import android.widget.RemoteViews;
import com.google.gdata.client.calendar.*;
import com.google.gdata.data.*;
import de.thesmile.android.widget2.R;
public class HelloWidget extends AppWidgetProvider {
int number =0;
public String gooleres()
{
String result=new String("Unable to login into your account");
// Create a CalenderService and authenticate
try
{
URL feedUrl = new URL("https://www.google.com/calendar/feeds/default/private/full");
CalendarQuery myQuery = new CalendarQuery(feedUrl);
myQuery.setMinimumStartTime(DateTime.parseDateTime("2011-03-01T00:00:00"));
myQuery.setMaximumStartTime(DateTime.parseDateTime("2011-03-06T23:59:59"));
CalendarService myService = new CalendarService("wqewq");
myService.setUserCredentials("sunnycool333#gmail.com", "XXXXXX");
//Send the request and receive the response:
Feed resultFeed = myService.query(myQuery, Feed.class);
for (int i = 0; i < resultFeed.getEntries().size(); i++) {
Entry entry = resultFeed.getEntries().get(i);
result= entry.getTitle().getPlainText().toString();
}
}
catch(Exception e)
{
result="Exception raised "+e.toString();
}
return result;
}
#Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager,
int[] appWidgetIds) {
for (int appWidgetId : appWidgetIds) {
RemoteViews views = new RemoteViews(context.getPackageName(),R.layout.main);
views.setTextViewText(R.id.widget_textview, gooleres());
appWidgetManager.updateAppWidget(appWidgetId, views);
}
}
}
The code seems to be proper because when I try to put the same code as simple java file then I do get the output..
the simple java file I created looks something like this and it gives proper output..
public static void main(String[] args) {
// TODO Auto-generated method stub
// Create a CalenderService and authenticate
try
{
URL feedUrl = new URL("https://www.google.com/calendar/feeds/default/private/full");
CalendarQuery myQuery = new CalendarQuery(feedUrl);
myQuery.setMinimumStartTime(DateTime.parseDateTime("2011-03-01T00:00:00"));
myQuery.setMaximumStartTime(DateTime.parseDateTime("2011-03-08T23:59:59"));
CalendarService myService = new CalendarService("exampleCo-exampleApp-1");
myService.setUserCredentials("sunnycool333#gmail.com", "ytrfvgb$");
// Send the request and receive the response:
Feed resultFeed = myService.query(myQuery, Feed.class);
for (int i = 0; i < resultFeed.getEntries().size(); i++) {
Entry entry = resultFeed.getEntries().get(i);
System.out.println(Integer.toString(i)+entry.getTitle().getPlainText().toString());
}
}
catch (Exception e) {
// TODO: handle exception
System.out.println(e.toString());
}
}
gdata api is not supported fully by android..
so have to move to google java client library :(