Tag Archives: library

How to Generate a PDF in Xamarin Android

It may sound simple, but when it comes to Xamarin, all the problems starts to emerge. So basically Xamarin does not provide any special class for PDF generation.

Failed Solution 1
So we were let alone to use the Android PDFDocument class. Which Unlike in the Native Android did not work. Actually it was giving me a White and blank document. When searching for the Xamarin Documentation what I found was the Xamarin documentation having the Android Reference Code which is very disappointing (Link to Documentation)

Here is the Code snippet for it(I may have made a mistake here, let me know if you guys found a solution for using PDFDocument class )

private String sdCardPathforPDF;
private String filePath;
private FileStream stream;

sdCardPathforPDF = Environment.ExternalStorageDirectory.AbsolutePath;
filePath = Path.Combine(sdCardPathforPDF, "MyPDF/test5.pdf");
stream = new FileStream(filePath, FileMode.Create);

tView = new TextView(context);
tView.SetTextColor(Color.ParseColor(resource.GetString(Resource.Color.black)));
tView.Text = "Hello";
tView.SetHeight(50);
tView.SetWidth(50);

var document = new PdfDocument();
var pageInfo = new PdfDocument.PageInfo.Builder(612, 792, 1).Create();

var page = document.StartPage(pageInfo);
tView.Draw(page.Canvas);
document.FinishPage(page);

document.WriteTo(stream);

stream.Close();
document.Close();

Toast.MakeText(context, "PDF Generated", ToastLength.Short).Show();

Failed Solution 2
Then I searched for a plugin or a 3rd party library, ohhh my god, I found some expensive plugins

Capture

Who would love to buy a plugin for 1600 usd??? Apitron and XFINIUM are some of them

Failed Solution 3
I found some Free open source libraries for Android, so I thought of  Java Bind it, but when i tried to Java Bind them, but I ended up getting lots of errors that i cannot fix it unless I am the developer of that library. So I dropped that Idea as well.

Failed Solution 4
Then after the disappointment of JavaBind, I came across an article saying that the iText library has been published for .Net in the name of iTextSharp. But when I added that Nuget Package I came across an error saying that

System.IO.FileNotFoundException: Could not load assembly 'System.Drawing, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a'. Perhaps it doesn't exist in the Mono for Android profile?

so It says there is an assembly called System.Drawing dll is missing. I tried to manually add it but it did not work. When I researched on it, it said that Mono for Android(Xamarin Android Framework) does not include that ‘dll’ I dont know how come a popular ‘dll’ got missed out of their framework.

At last a solution that Worked
So with all of the frustration I had, I did not give up on finding a solution till i came across problem where a guy has used ‘iTextSharp’ in Xamarin Android and its working. But he did not mention or reply my question in that thread. So I thought of giving a final look at the Nuget Manager. This time just like the previous time I searched for ‘iTextSharp’ but this time I went through each and every result the list showed.
And Hoooray I found It the one I am searching for, some one has made a nuget of ‘iTextSharp’ for Xamarin, its called “Xam.iTextSharpLGPL”

XamiTextSharp

And this worked like a Magic. And this library has more functionality than the default PDFDocument.
This library is based on iTextSharp 4.1.6  which means licensed under LGPL. Free to use and it is an Open source library.
Open source project can be found in Bit Bucket : https://bitbucket.org/smarongiu/xam.itextsharplgpl

So this is the Basic code of Writing a Simple PDF Doc

System.IO.FileStream fs = new FileStream(Server.MapPath("pdf") + "\\" + "First PDF document.pdf", FileMode.Create)

// Create an instance of the document class which represents the PDF document itself.
Document document = new Document(PageSize.A4, 25, 25, 30, 30);
// Create an instance to the PDF file by creating an instance of the PDF Writer class, using the document and the filestrem in the constructor.

PdfWriter writer = PdfWriter.GetInstance(document, fs);

Before we can write to the document, we need to open it.

// Open the document to enable you to write to the document

document.Open();

// Add a simple and well known phrase to the document in a flow layout manner

document.Add(new Paragraph("Hello World!"));

// Close the document

document.Close();
// Close the writer instance

writer.Close();
// Always close open file handles explicitly
fs.Close();

I grabbed this quick code snippet from Micke Blomquist

Hope this article will help people like me in future…!
See ya…!

Advertisements

Android Proguard a General Idea

What is Proguard on android and what does it do?

ProGuard is a tool that comes with the Android SDK. It  shrinks, optimizes, and obfuscates your code by removing unused code and renaming classes, fields, and methods with semantically obscure names. The result is a smaller sized .apk file that is more difficult to reverse engineer. Because ProGuard makes your application harder to reverse engineer, it is important that you use it when your application utilizes features that are sensitive to security.

How to enable it? And is it recommended?

ProGuard is integrated into the Android build system. And to enable it you just have to find the “project.properties” file in your android project and have to uncomment the line which sets the path for the ProGuard. Also Proguard slows the app building sequence.
So you do not have to invoke it manually. ProGuard runs only when you build your application in release mode, so you do not have to wait longer time when debugging the app. Having ProGuard run is completely optional, but highly recommended.

So is that all that we have to do to enable and use ProGuard?

Yes that’s the basic, and it only does the Shrinking, but there are 2 more functions that give more advantages in increasing the security and management of the build.
They are Obfuscation and Repackaging.

So what is Obfuscation and how does it Work

With tools available to extract the contents of APK’s, deodex, and read the class files, it’s important to obfuscate to protect the proprietary aspects of your codebase.

ProGuard generates a mapping file that allows you to map the stack traces of obfuscated code to actual methods. Basically it replaces the methods in meaning full name to something unguessable like a work or letter.

Original Code

public Data(int id, int result, String message) {
       mId = id;
       mResult = result;
       mMessage = message;
    }

Obfuscated Code

public a(int paramInt1, int paramInt2, String paramString)
    {
       this.a = paramInt1;
       this.b = paramInt2;
       this.c = paramString;
   }

 Hope you got an idea on how it works

So what is Repackaging?

Repackaging allows ProGuard to take externals jars and class files and move them to a single container with a common java package location.

For those of you building libraries, repackaging is extremely helpful if you choose to show a simple interface to third party developers while keeping a maintainable and well structured project hierarchy in the source repository. This can also be useful in organizing lower level packages while exposing well defined interfaces!

 Optimizing

There is another function of Proguard which Optimizes the code, where you can specify which part of the code, which type of code needs to be Optimized.  However, there are known incompatibility issues with various Dalvik versions.
But It is good to know this feature, which can be used without issues using some other tools.

Reference : http://www.crashlytics.com/blog/mastering-proguard-for-building-lightweight-android-code/, http://developer.android.com/tools/help/proguard.html