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

11 thoughts on “How to Generate a PDF in Xamarin Android

  1. Amalan, thanks for your post. It was very useful to me. Now I’m trying to use a class that is not present in iTextSharpLGPL: MakeSignature. It’s driving me crazy. I need to digitally sign a PDF on Android and I just can’t find a way to use the classic iTextSharp or JavaBinding to iText or whatever. Thanks anyway.

    1. You are welcome. I have not played with the signature module. But what I can suggest is getting the signature by showing a view consisting of a canvas, get the signature as a bitmap and render it with the PDF. That’s the possible solution i can think of at the moment.

      1. Hi.
        I solved the problem but I had to use a different approach:
        First I download the PDF from the web server so as to open it and see what the user is about to sign.
        Then I compute the bytes that will be the signature using a certifacate chosen by the user.
        After that I send the signature bytes to the server for it to make the merge.
        I took this architecture from Bruno Lowagie’s iText digital signatures e-book: http://pages.itextpdf.com/ebook-digital-signatures-for-pdf.html

        It was very hard to understand, because there are many posibilities for the architecture and some of them might not be legaly right in some countries.
        My advice is that you read the e-book.

        Good luck.

  2. @Amalan I trying to integrate iTextSharpLGPL in xamarin and able install it but while compiling getting following error.

    Error Exception while loading assemblies: System.IO.FileNotFoundException: Could not load assembly ‘System.Drawing, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a’. Perhaps it doesn’t exist in the Mono for Android profile?
    File name: ‘System.Drawing.dll’

  3. Interesting article, but I’d like to add my 2 cents. Actually Apitron PDF Kit is 30% cheaper if you buy it in their webstore and not in Xamarin store (because Xamarin takes a hefty 30% cut from component’s price), it’s the same API you can also use for developing desktop apps and one app license covers all platforms. And from personal experience I can say that it’s a real product with prompt support, worth the money we spent on it.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s