Converting to NotificationCompat breaks SetSmallIcon functionality? - xamarin

I've been having some trouble moving Notification to the Compat library version: In the main library, I used to just convert an icon to a bitmap (api 23 and up) and do SetSmallIcon(icon) to show a dynamic notification icon.
But the Compat version has only an int argument (I assume it is the resource ID), and I cannot find any information as to how to generate/convert/add my bitmap and/or icon in it.
The bitmap Is basically generated text converted into a bitmap via a canvas which show the most vital information.
My question is: Is there a way to make a class variable into a resource, or get its ID that works like a resoource ID, or some other hack that will allow me to actually add my bitmap that I create at runtime?

You can use this code. Refer the line where icon is being used
var notificationBuilder = new NotificationCompat.Builder(this)
.SetSmallIcon(Resource.Drawable.NotifIconSis).SetColor(Android.Graphics.Color.Rgb(33, 150, 243))
.SetContentTitle(user.Organization)
.SetSubText(user.ModuleName).SetStyle(new NotificationCompat.BigTextStyle().BigText(user.BodyText))
.SetContentText(user.BodyText)
.SetAutoCancel(true)
.SetContentIntent(pendingIntent)
.Build();
var notificationManager = NotificationManagerCompat.From(Application.Context);
//var notification = RingtoneManager.GetDefaultUri(RingtoneType.Notification);
//var mp = MediaPlayer.Create(ApplicationContext, notification);
//mp.Start();
//notificationManager.Notify(redomId, notificationBuilder);

Related

Can someone explain what are iTextEvents in ItextSharp?

Can someone explain what are iTextEvents in ItextSharp..
I have found a bunch of codes with its use but i dont get how they works..
Im asking you if anyone can explain me these:
OnOpenDocument
OnEndPage
OnCloseDocument
If you are looking to start using iText, then your question is obsolete. You are referring to a concept that was used in versions 5 and earlier of iText for .NET (we abandoned the name iTextSharp a long time ago). If you want to start using iText for .NET, you should start with version 7, not with iText 5 or earlier, because we stopped development on those versions. Any release we make now is nothing more than a maintenance release (maintenance releases don't contain new functionality, they have bug fixes that are meant for paying users who can't migrate to iText 7 immediately).
The name page events was misleading because those events were initially used to allow developers to execute code when a new page was created or finalized, but as the code grew organically, we also started to use the page event functionality for other things, such as: to add special behavior of a Chunk (OnGenericTag()) or to execute code before or after adding a Paragraph. That was an example of bad design.
We fixed this bad design in iText 7, where we introduced renderers and event handlers. See chapter 3 of the jump-start tutorial, entitled Using renderers and event handlers.
In iText 7, we can create an event handler such as:
protected internal class MyEventHandler : IEventHandler {
public virtual void HandleEvent(Event #event) {
PdfDocumentEvent docEvent = (PdfDocumentEvent)#event;
PdfDocument pdfDoc = docEvent.GetDocument();
PdfPage page = docEvent.GetPage();
int pageNumber = pdfDoc.GetPageNumber(page);
Rectangle pageSize = page.GetPageSize();
PdfCanvas pdfCanvas = new PdfCanvas(page.NewContentStreamBefore(), page.GetResources(), pdfDoc);
//Set background
Color limeColor = new DeviceCmyk(0.208f, 0, 0.584f, 0);
Color blueColor = new DeviceCmyk(0.445f, 0.0546f, 0, 0.0667f);
pdfCanvas.SaveState()
.SetFillColor(pageNumber % 2 == 1 ? limeColor : blueColor)
.Rectangle(pageSize.GetLeft(), pageSize.GetBottom(), pageSize.GetWidth(), pageSize.GetHeight())
.Fill()
.RestoreState();
//Add header and footer
pdfCanvas.BeginText()
.SetFontAndSize(C03E03_UFO.helvetica, 9)
.MoveText(pageSize.GetWidth() / 2 - 60, pageSize.GetTop() - 20)
.ShowText("THE TRUTH IS OUT THERE")
.MoveText(60, -pageSize.GetTop() + 30)
.ShowText(pageNumber.ToString())
.EndText();
//Add watermark
iText.Layout.Canvas canvas = new iText.Layout.Canvas(pdfCanvas, pdfDoc, page.GetPageSize());
canvas.SetProperty(Property.FONT_COLOR, Color.WHITE);
canvas.SetProperty(Property.FONT_SIZE, 60);
canvas.SetProperty(Property.FONT, C03E03_UFO.helveticaBold);
canvas.ShowTextAligned(new Paragraph("CONFIDENTIAL"), 298, 421, pdfDoc.GetPageNumber(page), TextAlignment.
CENTER, VerticalAlignment.MIDDLE, 45);
pdfCanvas.Release();
}
}
The event handler is introduced in the code like this:
PdfDocument pdf = new PdfDocument(new PdfWriter(dest));
pdf.AddEventHandler(PdfDocumentEvent.END_PAGE, new C03E03_UFO.MyEventHandler(this));
// Initialize document
Document document = new Document(pdf);
Paragraph p = new Paragraph("List of reported UFO sightings in 20th century").SetTextAlignment(TextAlignment
.CENTER).SetFont(helveticaBold).SetFontSize(14);
document.Add(p);
Table table = new Table(new float[] { 3, 5, 7, 4 });
table.SetWidth(UnitValue.CreatePercentValue(100));
StreamReader sr = File.OpenText(DATA);
String line = sr.ReadLine();
Process(table, line, helveticaBold, true);
while ((line = sr.ReadLine()) != null) {
Process(table, line, helvetica, false);
}
sr.Close();
document.Add(table);
document.Close();
This code adds a background, a watermark, a header, and a footer, as is shown in this figure:
Page events in "iTextSharp" had a similar purpose, but you shouldn't use them anymore. They are outdated. You should use iText 7 instead.
If you posted your question out of historical curiosity, you should search old questions on Stack Overflow, such as:
How can I add an image to all pages of my PDF?
itextsharp: How to generate a report with dynamic header in PDF using itextsharp?
Change the color of pdf pages alternatively using iText pdf in java
How to introduce multiple PdfPageEventHelper instances?
...

How to extract text from image Android app

I am working on a feature for my Android app. I would like to read text from a picture then save that text in a database. Is using OCR the best way? Is there another way? Google suggests in its documentation that NDK should only be used if strictly necessary but what are the downfalls exactly?
Any help would be great.
you can use google vision library for convert image to text, it will give better output from image.
Add below library in build gradle:
compile 'com.google.android.gms:play-services-vision:10.0.0+'
TextRecognizer textRecognizer = new TextRecognizer.Builder(getApplicationContext()).build();
Frame imageFrame = new Frame.Builder()
.setBitmap(bitmap) // your image bitmap
.build();
String imageText = "";
SparseArray<TextBlock> textBlocks = textRecognizer.detect(imageFrame);
for (int i = 0; i < textBlocks.size(); i++) {
TextBlock textBlock = textBlocks.get(textBlocks.keyAt(i));
imageText = textBlock.getValue(); // return string
}
From this Simple example of OCRReader in Android tutorial you can read text from image and also you can scan for text using camera, using very simple code.
This library is developed using Mobile Vision Text API
For scan text from camera
OCRCapture.Builder(this)
.setUseFlash(true)
.setAutoFocus(true)
.buildWithRequestCode(CAMERA_SCAN_TEXT);
For extract text from image
String text = OCRCapture.Builder(this).getTextFromUri(pickedImage);
//You can also use getTextFromBitmap(Bitmap bitmap) or getTextFromImage(String imagePath) buplic APIs from OCRLibrary library.
Text from an image can be extracted using Firebase machine learning (ML) kit. There are two versions of the text recognition API, on-device API (free) and on-cloud API.
To use the API, first create BitMap of the image, which should be upright. Then create FirebaseVisionImage object passing the bitmap object.
FirebaseVisionImage image = FirebaseVisionImage.fromBitmap(bitmap);
Then create FirebaseVisionTextRecognizer object.
FirebaseVisionTextRecognizer textRecognizer = FirebaseVision.getInstance()
.getCloudTextRecognizer();
Then pass the FirebaseVisionImage object to processImage() method, add listeners to the resulting task and capture the extracted text in success callback method.
textRecognizer.processImage(image)
.addOnSuccessListener(new OnSuccessListener<FirebaseVisionText>() {
#Override
public void onSuccess(FirebaseVisionText firebaseVisionText) {
//process success
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
//process failure
}
});
For complete example which shows how to use Firebase ML text recognizer, see https://www.zoftino.com/extracting-text-from-images-android
There is a different option. You can upload your image to the server, OCR it from the server, then get the result.

Unity: Loading image from URL failed

I am loading image from script to texture from URL. It is loading successfully, but the image is not reflecting on the texture.
How can I fix this?
you should UV unwrapped your model(that you want to put your image on it as a texture) you save the uv and then import it to unity then you can apply texture to it , here is tutorial that will show you how to do it in blender
Alright, if I'm gathering from the image correctly, it looks like you're using NGUI. If so, then you don't use Mesh Renderer. It's been a little bit since I used NGUI, but you need a reference to the game object or to the UITexture component that is on the game object. So I'll provide some code samples below for both scenarios. But you don't use a mesh renderer unless you're wrapping the texture around a 3D model. If this is for the UITexture then you would attach the image on there.
Game Object Reference:
imageObject.GetComponent<UITexture>().mainTexture = textureToUse;
UITexture Reference:
uiTextureReference.mainTexture = textureToUse;
I think that is what you were looking for, otherwise you need to do unwrapping and what not.
It is very easy if you are using NGUI.
Create a UITexture.
Refer it in you class either by declaring it public variable of getting it at runtime.
Import MiniJSON class that is easily available on internet. (Do not hesitate if you failed to find MiniJSON.Json, it could be MiniJSON.Deserialize or only Json.Deseiralize)
Following is the code snippet to get Facebook Display Picture with User_API_ID
string myImageUrl = "https://graph.facebook.com/"+API_ID+"/picture?type=large&redirect=0";
WWW myImageGraphRequest = new WWW(myImageUrl);
yield return myImageGraphRequest;
if (!string.IsNullOrEmpty(myImageGraphRequest.error))
Debug.Log("Could not fetch own User Image due to: " + myImageGraphRequest.error);
else
{
var myImageData = MiniJSON.Json.Deserialize (myImageGraphRequest.text) as Dictionary<string, object>;
var myImageLinkWithData = myImageData["data"] as Dictionary<string, object>;
string myImageLink = (string)myImageLinkWithData["url"];
WWW myImageRequest = new WWW(myImageLink);
yield return myImageRequest;
if (!string.IsNullOrEmpty(myImageRequest.error))
Debug.Log("Could not get user facebook image: " + myImageRequest.error);
else
{
userDP.mainTexture = myImageRequest.texture;
}
}
userDP is your UITexture.

Custom live tile rendering issue on Windows Phone (7/8)

In my Windows Phone app's main page, users can click a button to do some stuff and that will trigger the live tile to update.
The problem I am having is, if the user clicks the button and then hit the phone's Back button really quickly, the live tile sometimes will not render properly. This issue rarely happens, but it does happen and when it happens it just looks bad...
The way I implement the live tile is, create a user control that looks exactly the same as the live tile and then save it to isolated storage. Then retrieve it and store it in a FliptileData object. Finally I call the Update method on the ShellTile. Please see the following piece of code to demonstrate the process.
// the function that saves the user control to isolated storage
public Uri SaveJpegToIsolatedStorage(FrameworkElement tile, string suffix, int tileWidth = 336, int tileHeight = 336)
{
var bmp = new WriteableBitmap(tileWidth, tileHeight);
// Force the content to layout itself properly
tile.Measure(new Size(tileWidth, tileHeight));
tile.Arrange(new Rect(0, 0, tileWidth, tileHeight));
bmp.Render(tile, null);
bmp.Invalidate();
// Obtain the virtual store for the application
IsolatedStorageFile myStore = IsolatedStorageFile.GetUserStoreForApplication();
using (IsolatedStorageFileStream fileStream = new IsolatedStorageFileStream(IsolatedStorageFileName + suffix, FileMode.Create, myStore))
{
try
{
bmp.SaveJpeg(fileStream, tileWidth, tileHeight, 0, 100);
}
catch (Exception)
{
return null;
}
}
return new Uri("isostore:/" + IsolatedStorageFileName + suffix, UriKind.Absolute);
}
// save the user control to isolated storage and prepare the FlipTileData object
wideFrontTileImage = SaveJpegToIsolatedStorage((UserControl)this.WideFrontTile, "_wide_front", 691);
var flipTileData = new FlipTileData();
flipTileData.WideBackgroundImage = wideFrontTileImage;
return flipTileData;
// update the live tile
var shellTile = ShellTile.ActiveTiles.FirstOrDefault();
shellTile.Update(customTile.GetFlipTileData(data.UndoneMemosCount == "0" && data.TotalMemosCount == "0"));
I think the reason that's causing all this is, when the user clicks the Back button too quickly, the OS terminates all the processes running within the app and the rendering wasn't done at that time. I'm thinking if there's a way to know when the rendering is finished, so I can cancel the Back button and wait until it's finished then manually exit the app. But I simply dunno how...
Any help on this one will be greatly appreciated!
I have ran into similar issue in my WP8 app. The problem was that I was updating my Tile in ApplicationDeactivated event handler. The thing is you should not update your tiles there, but rather in your MainPage.OnNavigatedFrom override. Once I changed this, it works just fine.

How can I insert an image with iTextSharp in an existing PDF?

I have an existing PDF and I can use FdFWriter to input to text boxes. It works well. Now I have an image. I have read the documentation and looked at many examples but they all create new documents and insert an image. I want to take an existing PDF and insert an image into either an image field or as the icon image of a button. I have tried but it corrupts the document.
I need to be able to take an existing document and put an image on it. I do not want to open, read, replace, and delete the original. This original changes and the name "original" only means the source file in this context. There are many PDF files like this that need an image.
Thank you for any help.
Edit - I am very thankful for the code below. It works great, but the problem for me is that the existing PDF has digital signatures on it. When the document is copied like this (into result.pdf) those signatures, while still present, have a different byte count or other item that is corrupted. This means the signatures, while they show up on result.pdf, have an icon next to them that state "invalid signature."
In case it matters I am using a Topaz signature pad to create my signatures, which has it's own security. Merely copying the PDF will not corrupt it but the process below will.
I am trying to put the image on the existing document, not a copy of it, which in this case matters.
Also, by signature, I mean handwritten, not pin numbers.
Thank you again.
EDIT - Can PdfSignatureAppearance be used for this?
EDIT - I seem to be able to do it with:
var stamper = new PdfStamper(reader, outputPdfStream,'1',true);
If you want to change the contents of an existing PDF file and add extra content such as watermarks, pagenumbers, extra headers, PdfStamper is the object you need. I have successfully used the following code to insert an image into an existing pdf file to a given absolute position:
using System.IO;
using iTextSharp.text;
using iTextSharp.text.pdf;
class Program
{
static void Main(string[] args)
{
using (Stream inputPdfStream = new FileStream("input.pdf", FileMode.Open, FileAccess.Read, FileShare.Read))
using (Stream inputImageStream = new FileStream("some_image.jpg", FileMode.Open, FileAccess.Read, FileShare.Read))
using (Stream outputPdfStream = new FileStream("result.pdf", FileMode.Create, FileAccess.Write, FileShare.None))
{
var reader = new PdfReader(inputPdfStream);
var stamper = new PdfStamper(reader, outputPdfStream);
var pdfContentByte = stamper.GetOverContent(1);
Image image = Image.GetInstance(inputImageStream);
image.SetAbsolutePosition(100, 100);
pdfContentByte.AddImage(image);
stamper.Close();
}
}
}
When you insert the image you have the possibility to resize it. You can take a look at transformation matrix in the iTextSharp documentation.
Here is a similar example whichi inserts an image on the page using the stamper:
Gmane iTex Mailing List Post
I could solve my problem by simply adding following lines to my signing code to add image
var image = iTextSharp.text.Image.GetInstance(#"C:\Users\sushil\Documents\sansign.jpg");
appearance.Acro6Layers = true;
appearance.SignatureGraphic = image;
appearance.SignatureRenderingMode = PdfSignatureAppearance.RenderingMode.GRAPHIC_AND_DESCRIPTION;
As I was signing document with visible digital signature , now I can have both image and digital signature properties side by side
in the .net core6 that uses DDD try this declare class in Infrastructure Layer
using System.IO;
using iTextSharp.text;
using iTextSharp.text.pdf;
public async Task<string> SignatureToPdf(string pathPdfFile, string
pathSignatureImage, string pathOutputName)
{
var webRootPath = hostingEnvironment.ContentRootPath;
if (!File.Exists(Path.Combine(webRootPath, pathPdfFile))) return
null;
await using Stream inputPdfStream =
new FileStream(Path.Combine(webRootPath, pathPdfFile),
FileMode.Open, FileAccess.Read, FileShare.Read);
await using Stream inputImageStream =
new FileStream(Path.Combine(webRootPath, pathSignatureImage), FileMode.Open, FileAccess.Read, FileShare.Read);
await using Stream outputPdfStream =
new FileStream(Path.Combine(webRootPath, pathOutputName),
FileMode.Create, FileAccess.Write, FileShare.None);
var reader = new PdfReader(inputPdfStream);
var stamper = new PdfStamper(reader, outputPdfStream);
var pdfContentByte = stamper.GetOverContent(1);
var image = Image.GetInstance(inputImageStream);
image.SetAbsolutePosition(100, 100);
pdfContentByte.AddImage(image);
stamper.Close();
return "ok";
}
pdftk can do this. It's not a library but you can easily call it from your code as a .exe.
See stamp and background commands:
http://www.pdflabs.com/docs/pdftk-man-page/
ref: How to do mail merge on top of a PDF?

Resources