I am trying to create a custom keyboard and use "SoftKeyboard" sample in android SDK for it. I did few modifications with that sample and created my custom keyboard. I can use this custome keyboard with default Messaging app of my Android device.
Now I want to click a button in my custom keyboard and add an image when I type a SMS. I noticed that there is String Builder in "SoftKeyBoard.java" class (private StringBuilder mComposing = new StringBuilder()) and it is appended chars when we type letters using keyboard.
I tried to append an image of my SD card like below,
String imageDataString = "";
String path = Environment.getExternalStorageDirectory().toString() + "/SamplePictures/";
File file = new File(path, "myimage.jpg");
try {
FileInputStream imageInFile = new FileInputStream(file);
byte imageData[] = new byte[(int) file.length()];
imageInFile.read(imageData);
// Converting Image byte array into Base64 String
imageDataString = encodeImage(imageData);
imageInFile.close();
} catch (FileNotFoundException e) {
System.out.println("Image not found" + e);
} catch (IOException ioe) {
System.out.println("Exception while reading the Image " + ioe);
}
and I appended "imageDataString" to String builder like below,
mComposing.append(imageDataString);
But I got so many characters, not an image.
Is it possible to insert an image when I type SMS using my keyboard?
Updated : I used ImageSpan and Spannable with following code.
SpannableStringBuilder ssb = new SpannableStringBuilder( "Here's a my picture " );
Bitmap smiley = BitmapFactory.decodeResource( getResources(), R.drawable.bitmap );
ssb.setSpan( new ImageSpan( smiley ), 16, 17,Spannable.SPAN_INCLUSIVE_INCLUSIVE );
mComposing.append(ssb);
But it displays only "Here's a my picture" and no image. I created a sample separate app with an EditText and set above "ssb" variable as the text of that EditText. Then it displays well the image. But it doesn't work with Messaging app. If I can set the Messaging app EditText, I guess I can set the image.
Is there any way to access and update the Edit text of Messaging app?
Thanks in Advance..!!
I think what you want to do is use an ImageSpan added to a Spannable, a solution which is already described here. After pressing the image button on your keyboard, you'll fire of a method that should update the editText by taking the existing text from it, adding an ImageSpan containing your image and setting that back to the editText.
Related
I try to generate a pdf with com.itextpdf in android / java. Basically, (text) chat messages shall be transferred to the pdf for archiving the chat.
Using com.itextpdf works fine for text only messages using the font included in com.itextpdf. Unfortunately, emojis are not covered by these fonts and therefore will not be included in the pdf file.
For including emojis a sample is given here. Following the sample code I am not able to generate a pdf file with emojis displaying. I tried different fonts like noto_emoji_regular.ttf or noto_color_emoji_compat.ttf. Some fonts end in a completely white pdf, some in funny signs like in this
screen shot.
This is my code:
public File createPdfDoc() {
final String font_path = "assets/noto_emoji_regular.ttf";
// test strings
String html = new String("<!DOCTYPE html>\n" +
"<html>\n" +
"<body>\n" +
"<span style='font-size:100px;'>π</span>\n" +
"<p>I will display π</p>\n" +
"<p>I will display π test π
</p>\n" +
"</body>\n" +
"</html>");
String s = "\"title\":\"πΊTEST title value π\",\"text\":\"π TEST text value.\"";
File pdfFile = null;
try {
String exportPath = new ExportProvider(weakContext.get()).getExportDirPath() + File.separator
+ generateDocTitle();
PdfWriter pdfWriter = new PdfWriter(exportPath);
PdfDocument pdf = new PdfDocument(pdfWriter);
// testing text 2 pdf
Document doc = new Document(pdf);
Paragraph p = new Paragraph();
PdfFont emoji_font = PdfFontFactory.createFont(FONT_ACCESS); //Create Pdf Font with Emoji glyphs
p.setFont(emoji_font); //add font to Paragraph
p.setFontSize(15);
p.add(new Text(String.format("Here are some emojis: %s %s", 0x1F600, encodeCodepoint(0x1F604)))); //encode unicode values
doc.add(p); //add Paragraph to document
doc.close();
/*
// testing html 2 pdf
ConverterProperties cprop = new ConverterProperties();//ConverterProperties will be used to add the FontProvider to the Converter.
FontProvider provider = new FontProvider();//The FontProvider will hold our emoji font
provider.addStandardPdfFonts();
provider.addFont("/font/noto_emoji_regular.ttf", PdfEncodings.IDENTITY_H);
cprop.setFontProvider(provider);//add provider to properties
HtmlConverter.convertToPdf(new ByteArrayInputStream(html.getBytes()), pdf, cprop);//Include ConverterProperties as argument for the #convertToPdf() method.
pdf.close();
*/
pdfFile = new File(exportPath);
} catch (IOException e) {
e.printStackTrace();
}
return pdfFile;
}
Can you give me any hint what I have to do for displaying text and emojis?
EDIT: The goal it to export chat messages including emojis to a pdf document. Any alternative idea how to do that is very welcome.
I am working on a pdf editor.
I have made my changes on pdf files with OpenPDF core that is based on iText
And I am viewing the Pdf file with AndroidPdfViewer
My problems are:
Adding new annotations like text or tags or icons into an existing pdf file. ( SOLVED )
Show new changes right after annotations added into pdf file.( SOLVED )
Convert user click into Pdf file coordinates to add new annotation based on user clicked location.
Get click event on added annotations and read meta data that added into that annotation , for ex: read tag hash id that sets on icon annotation. ( SOLVED )
Remove added annotation from PDF File.
Any help appreciated
UPDATE
========================================================================
Solution 1: Adding annotations
Here is my code snippet for adding icon annotation into existing pdf file.
public static void addWatermark(Context context, String filePath) throws FileNotFoundException, IOException {
// get file and FileOutputStream
if (filePath == null || filePath.isEmpty())
throw new FileNotFoundException();
File file = new File(filePath);
if (!file.exists())
throw new FileNotFoundException();
try {
// inout stream from file
InputStream inputStream = new FileInputStream(file);
// we create a reader for a certain document
PdfReader reader = new PdfReader(inputStream);
// get page file number count
int pageNumbers = reader.getNumberOfPages();
// we create a stamper that will copy the document to a new file
PdfStamper stamp = new PdfStamper(reader, new FileOutputStream(file));
// adding content to each page
int i = 0;
PdfContentByte under;
// get watermark icon
Image img = Image.getInstance(PublicFunction.getByteFromDrawable(context, R.drawable.ic_chat));
img.setAnnotation(new Annotation("tag", "gd871394bh2c3r", 0, 0, 0, 0));
img.setAbsolutePosition(230, 190);
img.scaleAbsolute(50, 50);
while (i < pageNumbers) {
i++;
// watermark under the existing page
under = stamp.getUnderContent(i);
under.addImage(img);
}
// closing PdfStamper will generate the new PDF file
stamp.close();
} catch (Exception de) {
de.printStackTrace();
}
}
}
Solution 2: Show new changes
Here is my code snippet for refreshing the view after adding annotation, I have added this into AndroidPdfViewer core classes.
public void refresh(int currPage) {
currentPage = currPage;
if (!hasSize) {
waitingDocumentConfigurator = this;
return;
}
PDFView.this.recycle();
PDFView.this.callbacks.setOnLoadComplete(onLoadCompleteListener);
PDFView.this.callbacks.setOnError(onErrorListener);
PDFView.this.callbacks.setOnDraw(onDrawListener);
PDFView.this.callbacks.setOnDrawAll(onDrawAllListener);
PDFView.this.callbacks.setOnPageChange(onPageChangeListener);
PDFView.this.callbacks.setOnPageScroll(onPageScrollListener);
PDFView.this.callbacks.setOnRender(onRenderListener);
PDFView.this.callbacks.setOnTap(onTapListener);
PDFView.this.callbacks.setOnLongPress(onLongPressListener);
PDFView.this.callbacks.setOnPageError(onPageErrorListener);
PDFView.this.callbacks.setLinkHandler(linkHandler);
if (pageNumbers != null) {
PDFView.this.load(documentSource, password, pageNumbers);
} else {
PDFView.this.load(documentSource, password);
}
}
Solution 4: Click on object in pdf
I have create annotations and set it to added image object, AndroidPdfViewer has an event handler, here is the example
#Override
public void handleLinkEvent(LinkTapEvent event) {
// do your stuff here
}
I will add other new solutions into my question, as update parts.
Here is my code snippet for adding text into pdf file,
Your code does not add text into an existing pdf file. It creates a new PDF, adds text to it, and appends this new PDF to the existing file presumably already containing a PDF. The result is one file containing two PDFs.
Concatenating two files of the same type only seldom results in a valid file of that type. This does works for some textual formats (plain text, csv, ...) but hardly ever for binary formats, in particular not for PDFs.
Thus, your viewer gets to show a file which is invalid as a PDF, so your viewer could simply have displayed an error and quit. But PDF viewers are notorious for trying to repair the files they are given, each viewer in its own way. Thus, depending on the viewer you could also see either only the original file, only the new file, a combination of both, an empty file, or some other repair result.
So your observation,
but this will replace with all of the Pdf file, not just inserting into it
is not surprising but may well differ from viewer to viewer.
To actually change an existing file with OpenPDF (or any iText version before 6 or other library forked from such a version) you should read the existing PDF using a PdfReader, manipulate that reader in a PdfStamper, and close that stamper.
For example:
PdfReader reader = new PdfReader("original.pdf");
PdfStamper stamper = new PdfStamper(reader, new FileOutputStream("original-stamped.pdf"));
PdfContentByte cb = stamper.getOverContent(1);
cb.beginText();
cb.setTextMatrix(100, 400);
cb.showText("Text at position 100,400.");
cb.endText();
stamper.close();
reader.close();
In particular take care to use different file names here. After closing the stamper and the reader you can delete the original PDF and replace it with the stamped version.
If it is not desired to have a second file, you can alternatively initialize the PdfStamper with a ByteArrayOutputStream and after closing the stamper and the reader replace the contents of the original file with those of the ByteArrayOutputStream.
I want to convert text to docx format in android app .I want to know how I could achieve the same.
I tried directly converting from text to docx first.
I tried implementing Apache POI and Aspose library but I didn't find my solution. Aspose library on runtime gave error of "Duplicate API ", I checked Aspose forum it is not resolved yet .I tried whatever it is told.
I tried implementing text to pdf it is done.
Now I want to know how to convert from pdf to docx?
Can anybody help with proper functioning details to achieve this task ? or any other suggestion so that text to docx can be converted?
// Below code is for converting directly from text to docx .
// This is using Apache POI but it is not importing classes after adding library
private void docxFormat()
{
XWPFDocument xwpfDocument = new XWPFDocument();
FileOutputStream fileOutputStream = null;
try {
fileOutputStream = new FileOutputStream(new File("yourfilepath/filename.docx"));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
for(String s:lines) {
XWPFParagraph xwpfParagraph = xwpfDocument.createParagraph();
XWPFRun xwpfRun = xwpfParagraph.createRun();
xwpfRun.setText(s);
}
xwpfDocument.write(fileOutputStream);
fileOutputStream.close();
}
// Anybody any suggestion for converting text to docx
You can easily convert a Text file to Word formats such as DOC, DOCX, RTF and to many other formats (PDF, XPS, HTML etc) by using the following Aspose.Words for Android via Java API's code:
try
{
String licString = Environment.getExternalStorageDirectory().getAbsolutePath() + "/Aspose.Words.Android.lic";
String inputPath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/input.txt";
String outputPath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/output.docx";
com.aspose.words.License lic = new com.aspose.words.License();
lic.setLicense(licString, this);
com.aspose.words.Document doc = new com.aspose.words.Document(inputPath);
doc.save(outputPath);
}
catch (Exception e)
{
e.printStackTrace();
}
Hope, this helps. I work with Aspose as Developer Evangelist.
Im interested in running some custom analytics on my interactions with contacts on my phone.
Some things I would like to see are:
How many times was this contact called
How long did the conversation last
How many missed calls from this contact
How many answered calls from this contact
What time and date was an sms sent
What was its message content
What time and date was an sms received
What was its message content
If it was mms can i get the picture some how
Ill use a third party api for facial recognition and nudity checks (was it a nude, selfie, meme)
Is there a way to simply export this data into a xml or csv file? (How would I save pictures?)
My goal here is to make an app using some sort of android java sdk. Then using the app, ill upload to my web server and use php to do the analytics.
Where do i look to start getting the information i want to analyze?
Try to look at these links:
PhoneStateListener
TelephonyManager
Read SMS
ContentResolver
To export your pictures from mms use a filestream and a bitmap:
private void GetMmsAttachment(String _id, String _data)
{
Uri partURI = Uri.parse("content://mms/part/" + _id );
String filePath = "/sdcard/photo.jpg";
InputStream is = null;
OutputStream picFile = null;
Bitmap bitmap = null;
try {
is = getContentResolver().openInputStream(partURI);
bitmap = BitmapFactory.decodeStream(is);
picFile = new FileOutputStream(filePath);
bitmap.compress(Bitmap.CompressFormat.JPEG, 50, picFile);
picFile.flush();
picFile.close();
}
catch (Exception e)
{
e.printStackTrace();
//throw new MmsException(e);
}
}
Also for photo Identification I recommend you use IBM Watson,.If the photo has text use Google Tesseract to extract the text.
I have to print the entire text of a text field into a picture. The reason is: I have to exchange messages with unsupported UTF-8 characters between Android and other web clients. By unsupported UTF-8 characters I mean missing fonts in Android (see this topic here ). I tried to use the direct way
Bitmap b;
EditText editText = (EditText) findViewById(R.id.editText);
editText.buildDrawingCache();
b = editText.getDrawingCache();
editText.destroyDrawingCache();
which works like a charm until I have multiple lines: The solution captures only the text which is visible to the user instead of the complete text inside of a long text field (scrollbars!).
I also tried another workaround by generating a picture from a stackoverflow answer. This prints the entire text but does not respect text formatting like newlines. But I don't want to handle all the stuff by myself.
I am forced to use Android 4.3 and earlier versions.
Is there smart way to capture text into pictures? If not:
Is it possible to modify the code above to get it work as expected?
After searching for another 24 hours for a solution I ran into this solution for a Webview. The trick is
generate another View to hold the content to avoid the marker for EditText on the lower edge of view which will be also printed into the picture
copy the Bitmap to avoid problems with software renderer after destroyDrawingCache() when trying to use Bitmap.compress().
Here is the code:
EditText editText = (EditText) findViewById(R.id.editText);
TextView textView = new TextView(this.getApplicationContext());
textView.setTypeface(editText.getTypeface());
textView.setText(editText.getText());
textView.measure(
View.MeasureSpec.makeMeasureSpec(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED),
View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED));
textView.layout(0, 0, textView.getMeasuredWidth(), textView.getMeasuredHeight());
textView.setDrawingCacheEnabled(true);
textView.buildDrawingCache();
Bitmap b = textView.getDrawingCache().copy(Bitmap.Config.ARGB_8888, false);
textView.destroyDrawingCache();
try{
String path = Environment.getExternalStorageDirectory().toString() + "/picture.png";
OutputStream outputStream = new FileOutputStream(new File(path));
b.compress(Bitmap.CompressFormat.PNG, 0, outputStream);
outputStream.flush();
outputStream.close();
} catch (Exception e) {
e.printStackTrace();
}