Using iTextSharp to generate pdf file in

One of the common requirement of web applications is to provide users a way to download some contents. In case of a report, almost all of the reporting tools have the export to pdf kind of function available.

But sometime, it is not a report that needs to be generated in pdf. But it could be simple web page or content of a page or sometimes a plain text needs to be generated in pdf format.

There are many third party tools are available for this task. We can import their API's in application and it takes care of all core function of creating pdf files. iTexSharp being one of the widely used and Open source (FREE) component, we are going to see how easily it can be used and range of features it provides

Code starting

I intend to cover other features of iTextSharp component. Focus of this article would be on simply creating a pdf file with different sources of text.

To start with, download iTextSharp dll from official page here iTexSharp is a c# version of original Java library iText. To demonstrate the use, i have created a sample web application in c# and added reference to iTextSharp.dll. I wanted to test using some other site's html page as a source to convert into pdf also, i would user entered string to convert into pdf. After creating couple of textboxes for input, I want to write code on button click event.

Before that, lets add few references in our code.

using System.IO;
using iTextSharp;
using iTextSharp.text.api;
using iTextSharp.text;
using iTextSharp.text.pdf;
using iTextSharp.text.html.simpleparser;

In button click event, create object of Document and PDFWriter

Document itextDoc = new Document();
PdfWriter pdfDoc = PdfWriter.GetInstance(itextDoc,Response.OutputStream);

At the end generated PDF file is going to be outputted to outputstream. The following code is just for reading other web page using WebClient and converting response into string reader (or reading text file into stringreader). You may want ignore this code if you are aware about how to do it.

 System.Net.WebClient webClient=new System.Net.WebClient(); 
 //passing url of local web page to read its html content
 Stream responseData = webClient.OpenRead("http://localhost:51951/Test/Default4.aspx");
 //converting stream into stream reader object
 StreamReader inputstream = new StreamReader(responseData);
 //If you want to read text from other source like plain text file or user input, ignore all above lines
 StringWriter sw = new StringWriter();
 HtmlTextWriter writer = new HtmlTextWriter(sw);
 //comment above line and uncomment below line if you wish to convert text file to pdf
 StringReader sr = new StringReader(sw.ToString());

Now that e have the source content, we need to parse the source content for valid HTML format and extract iTextSharp elements. The parsed elements will be returned into List of IElement. We will then need to loop through all elements and add them individually using Document object we just created. Below lines of code will do just that

List<IElement> elements =HTMLWorker.ParseToList(sr,null);  

  foreach (IElement el in elements)

Before adding elements using Document object, Open method is called on Document object and Close afterwards

Lets run the test. I already have another simple page running in another Visual studio instance. When viewed in browser, the page looks like this


From my sample application when I call this page using WebClient and generate the PDF file, it opens up as


Our basic task is completed. You might want to add little more stuff to generated PDF. Like adding header/footer, images, watermark etc. Most of these functionality available in ITextSharp. We will look at them in following articles. Please find complete code for this test below.

System.Net.WebClient webClient=new System.Net.WebClient(); 
 //passing url of local web page to read its html content
 Stream responseData = webClient.OpenRead("http://localhost:51951/Test/Default4.aspx");
 //converting stream into stream reader object
 StreamReader inputstream = new StreamReader(responseData);
 //If you want to read text from other source like plain text file or user input, ignore all above lines
 StringWriter sw = new StringWriter();
 HtmlTextWriter writer = new HtmlTextWriter(sw);
 //comment above line and uncomment below line if you wish to convert text file to pdf
 StringReader sr = new StringReader(sw.ToString());

 //Parse into IElement
 List<IElement> elements =HTMLWorker.ParseToList(sr,null);        
 //Open the Document
 //loop through all elements
 foreach (IElement el in elements)
     //add individual element to Document
 //Close the document
 //set the Response object
 Response.ContentType = "application/pdf";
 Response.AddHeader("content-disposition", "attachment;filename=TestPage.pdf");


Happy coding!

Happy 60th Birthday Bill Gates


The founder of Microsoft and wealthiest man in the world turns 60 years old today. William Henry Gates III was born October 28th, 1955 in Seattle, Washington where he still resides in his post Microsoft years.

He has much to celebrate as he turns 60. After leading Microsoft for decades it must be quite rewarding to see the company he founded grow in such a bold direction this year with a booming commercial cloud computing division, new category defining hardware that is leading the competition, and an incredibly fast adoption rate for Microsoft’s latest version of Windows.


But Gates isn’t nearly as involved in Microsoft now a days as he used to be. He formerly stepped down as CEO in 2000 when Steve Ballmer took the reins. He also left his position as Chairman of Microsoft in February of 2014 when Satya Nadella was appointed CEO. He spends a great deal of his time working on the Bill and Melinda Gates Foundation‘s projects, which has been identified as the wealthiest charitable foundation in the world. The foundation focuses on improving the lives and productivity of people around the world, and has gained much attention recently for its emphasis on eradicating common diseases in developing nations.

Gates still does help out at Microsoft as a Technology Advisor. Most notably Gates has been helping Nadella rethink some of the company’s strategies, particularly with reinventing Office. And it appears his contributions are still paying off for the company with news that the reinvention of Office as an SaaS offering, Office 365, overtook Google Apps for Work this year.

So happy birthday Mr. Gates! Hope you are having a productive celebration of reaching the huge milestone of 60, while the company you founded continues to reach its own previously unimagined milestones. If you want to follow more about Bill Gates work outside of his advisory role to Microsoft, you can learn more on his personal blog GatesNotes.

Microsoft's new Windows 10 build allows you to text from your PC, but it's the bug fixes that impress

Unfortunately, it requires an upgrade from Windows Phone 8.1 - again.

Microsoft launched build 10572 of Windows 10 Mobile to its insiders, together with a few nifty improvements on the messaging fronts. But, as before, you’ll still need to first downgrade to Windows Phone 8.1 to take advantage.

Microsoft did say, however, that this two-steps-back, one-step-ahead approach will soon stop, and users in the Windows Insider program will once again be able to upgrade from Windows 10 preview builds without having to downgrade first.

But the new build offers several intriguing new features, such as the ability to receive a notification on your Windows 10 PC that you’ve missed a call, and then to send a text via your PC’s Cortana assistant. The new build also boasts improvements to Skype and Skype messaging, improved Cortana tracking of movies and events, and the ability to book a car through Uber. Finally, the new build includes support for offline maps stored on the SD card as well as a new storage experience that’s shared with Windows 10 for the desktop.

And while they might not be classified as new features, some aspects, such as the phone displaying Notifications without first unlocking the device, and some Cortana power optimizations, should be a welcome update as the clock ticks toward a forthcoming release of Windows 10 for phones.

Why this matters: We’re still not quite sure when Windows 10 Mobile will launch, but we’re nearing the finish line. Being able to send texts from your PC to your Windows 10 phone isn’t something the Mac can do (according to the Macworld editors). It’s the laundry list of features, many of them substantial, that you should have your eye on.

Microsoft is getting serious about payments in Windows 10

Windows10-backgroundMicrosoft is looking to relaunch Windows Wallet, a mobile payments app that stores credit cards, coupons and membership information, to improve both the in-store payment experience and online payments with Windows devices, a top Microsoft executive said in a joint interview with The Verge and Recode.

"Windows is going to have a wallet concept. You’ve seen it on phones before. We’re going to continue to iterate it," Joe Belfiore, corporate VP of the company's operating systems group, said. "We’re going to think about the range of payment scenarios."

While Belfiore didn’t say when exactly a new wallet would launch, or whether it would utilize NFC or other payment technology, he cited Windows Hello, the company’s new facial recognition technology introduced with the Windows 10 operating system, as a good example of the "kind of technology we’ll build into devices for authentication to make… payments better." It’s likely that any kind of updated Windows Phone payments app would utilize NFC technology, the same tech Windows Wallet for Windows Phone 8.1 was said to use.

However, that app never really became a full-fledged payments app. Like Apple, Samsung, and any other tech company that has tried to launch a branded, fully useable mobile payments app, Microsoft is aware that getting into mobile payments has its challenges, especially in certain markets.

"[Mobile payments] is just one of these things that is a massive network of complexity," Belfiore said. "I think the biggest challenge is, What effect will cause enough of the right things to align that you’ll get a good experience with all the places that you want it to happen in? And that’s kind of a world problem."

.NET Core and ASP.NET Launches a Beta Bug Bounty Program

BugBountyProgramToday, with great excitement, we announce an introductory 3 month bug bounty program for .NET Core and ASP.NET, our new open source, cross platform runtime and web stack. The program encompasses the latest beta version, beta 8 and any subsequent beta or release candidates released during the program period.

We recognize that you, our customers, rely on our platforms and development tools to write your own software. The more secure we can make our frameworks the more secure your software can be. We take your trust seriously and this program is part of our investment in improving the security of our frameworks on all platforms. Starting a bounty program during our beta period allows us to address issues quickly and comprehensively. We are able to reward and recognize security researchers for their hard work and for any qualifying security bugs they report to us under the aegis of the program. This is the right thing for our customers and for the security researcher community.

The bounty includes all supported platforms .NET Core and ASP.NET runs on; Windows, Linux and OS X. However with the first eligible release, beta 8, we are excluding the networking stack on Linux and OS X. In later beta and RC releases, once our cross platform networking stack matches the stability and security it has on Windows, we'll include it within the program. When this happens we'll update the bounty terms and conditions and make a blog post on this blog. The ASP.NET web site has instructions on how to install beta 8 on Windows, Linux and OS X. Windows researchers can use Visual Studio 2015, including the free Visual Studio 2015 Community Edition, after following the instructions to update the web tooling. The source for .NET Core can be found on GitHub at The source for ASP.NET v5 can be found on GitHub at

We encourage you to read the program terms and FAQs before beginning your research or reporting a vulnerability. We would also like to applaud and issue a hearty and grateful thanks to everyone in the community who has reported issues in .NET and ASP.NET in the past. We look forward to rewarding you in the future as we take .NET and ASP.NET cross platform.

Windows 10: Extensions for Edge to arrive with Redstone in 2016


Microsoft Edge is an interesting browser, simply because it’s missing a rather hefty amount of vital features for people to want to make the switch from Chrome or Firefox. One feature that should have been there on day one but wasn’t, are extensions. Extensions are one of the main reasons people aren’t switching over to Edge, and now it appears users waiting to make the switch are going to have to wait a little longer.

Microsoft initially stated that extensions for Edge would arrive with an update “later this year”, but according to my contacts, there are no other feature updates after Threshold 2 that are scheduled for the end of this year. Extensions are yet to show up in the main development branch for Threshold 2 as well, and Microsoft still hasn’t started asking developers to port their extensions from other web browsers. With only two weeks left before Threshold 2 RTMs, there’s simply no time for Microsoft to ready extensions for Edge. So Instead, I hear Microsoft is planning to rollout the feature in 2016 with Redstone in the summer.

Insiders will likely get to mess with extensions before the summer however, as the Insider Program will likely begin receiving new Redstone builds way before RTM is released to the public. Microsoft will want developers and insiders to test (and develop) extensions within Edge, so when the update launches consumers will already have a number of extensions available for the browser. For those who don’t know, Microsoft is working on a bridge to allow extensions developed for Chrome to be easily ported to Edge with little to no code changes, much like the Project Astoria bridge.

Microsoft Connect (); // 2015 Developer Event Set for November 18-19


Microsoft is a developer company, so there’s nothing we love more than connecting with developers to share our latest tools, technologies and plans for the future. I therefore invite you to set your calendar November 18-19 for Connect (); // 2015 – when Microsoft hosts its premier fall developer event, streamed live from New York City to developers around the world.

Keynotes and technical sessions will feature news, demos and insights that illustrate how developers are working with Microsoft to capitalize on their evolving roles with powerful and flexible tools that embrace today’s open environments to target Android, iOS, Linux, Windows and more.

This year’s event will demonstrate the tremendous progress we’ve made on the journey toward a new Microsoft for developers that began last year with the announcements of a cross-platform .NET for Linux and OSX available as open source and the new Visual Studio Community edition for targeting nearly every major device and OS, available for free.

Connect(); will feature a marquee lineup of speakers joining Scott Guthrie to talk code, including; Brian Harry, Scott Hanselman, Amanda Silver, Anders Hejlsberg and Beth Massi alongside many of the customers, partners and industry luminaries who are leading the shift toward mobile first, cloud first computing scenarios.

We encourage you to save the date and tune in November 18th and 19th. Additional details on the event and broadcast event can be found at

Microsoft taps open source LLVM compiler for cross-platform .Net


Does it make sense to build something from scratch when there's a perfectly good solution available - especially if it's open source? Once upon a time, Microsoft's default was to build its own rather than use someone else's work; now, the reverse is becoming true.

Consider the LLILC project. Rather than reinvent the wheel, Microsoft's new compiler for its CoreCLR .Net runtime leverages an existing cross-platform compiler framework: LLVM. Now six months into the project, its maintainers -- a foundation comprised largely but not exclusively of folks from Microsoft -- reports "great progress" with LLILC, but also "much still to do."

LLILC is currently capable of performing just-in-time compilation ("jitting") of "all the [.Net] methods in some fairly complex scenarios." How complex? "Roslyn is a C# compiler written entirely in C#," the dev team states, "and LLILC can jit Roslyn compiling itself."

LLILC isn't yet replacing CoreCLR's original jitting mechanism; instead, the LLILC and CoreCLR jit engines run side by side. If the first one encounters something it can't handle, it's handed off to the second engine, which allows the compilation pipeline to continue running. Full garbage collection and proper exception handling support are two features lined up for the next phase of work.

The .Net Foundation, the project's official maintainer, features team members and contributors from far and wide - GitHub and the Debian Mono group have advisers on board, for instance -- but is composed mainly of folks from Microsoft and is being used to sponsor a technology Microsoft itself invented. That said, those working on LLILC are shaping their contributions to fit LLVM, rather than trying to rework LLVM to fit LLILC's needs.

"Our intention has always been to upstream as quickly as possible," the project team writes. "We're still working on making good at that intention, but so far the number of changes we’ve had to make are fairly modest."

Write C#. Run JavaScript.


Open Source C# to JavaScript Compiler and Frameworks. Run Your App On Any Device Using JavaScript.

Use Bridge.NET to build platform independent applications for mobile, web and desktop. Run on iOS, Windows, Mac, Linux and billions of other devices with JavaScript support. Compile your C# code into native JavaScript and deploy on Billions of devices.

Try it on or fork it on GitHub


In my previsious post (How do I get a Unique Identifier for a Device within Windows 10 Universal?) I talked about how getting a unique Id for a device. I’ve found another way.

In the registry there is an unique ID generated during Windows installation and it won't change until you reinstall Windows. You can find such ID in HKLM/Software/Microsoft/Cryptography, it's a string named MachineGuid.

If you can identify a component you're pretty sure that won't change (motherboard for example) you may use a simple WMI query to get its serial number but you should always provide a fallback because many many MBs returns a fake S/N (and virtual machines may returns always the same one). What's the proper solution...well it depends on what you have to do with that ID. Identify the user? Check for license? Encrypt data? Each of these has a different "best practice" for ID.

Get an unique ID for the device
If you have to identify a particular device (regardless to the user) you have many options, what I'd prefer to do is to generate an ID using only stable data (S/N from motherboard and BIOS, for example). This won't help you if he/she completely renew its hardware but it should be stable enough (but you have to define what is enough in your case). You may even use the S/N of the primary disk (with portable devices it's pretty stable and you may even use it in combination with other serial numbers to build your own ID). You can get this informations through WMI or (if you're targeting WinRT) through specific bytes of the ASHWID structure.

Encrypt data
In this case you have to think when data may be unrecoverable. If with a small hardware change your users won't be able to read their previous files well, they'll be unhappy. In this case I would suggest to use the MachineGuid, unless they reinstall the OS they wouldn't have to worry (but do them a favor and provide a way to read back that GUID somewhere). If you're sure you're targeting a portable device like a phone or a tablet then disk serial number (or CPU ID, if available, or MB or BIOS) may be appropriate too (because it's pretty uncommon they'll change).

I would use a combination of many (stable) IDs. As for an unique identifier for the device you can't be sure nothing will change. In the past MAC address was vastly used for this but mobile devices changed these rules (because it's easy to turn off a NIC). You can still use them but you have to put extra care (and code) to manage that situation. Again a combination of multiple IDs (chosen carefully) can help you to minimize customers effort when they change their hw/sw setup. In this case a good compromise could be the OS serial number (not the MachineGuid). If they install a new OS then they have to update your license too (but I would use it combined with something else to be sure they won't use the same OS copy on multiple computers or virtual machines).

Note about virtual machines
If you have to target VMs too then things become more complicated. In theory an user can create multiple copies of the same VM with exactly the same hardare and software configuration. If this is an issue and if you can't address this properly (for example using a network check) I would suggest you don't support them at all (just quit if you detect a VM).

/// Here is a code example that filters form ASHWID the hardware modules
/// that are unlikely to be changed (CPU id, size of memory, serial number of the disk device and bios)
public string GetDeviceID()
    // get the hardware Profile id and convert it to byte Array
    var hardwareToken = Windows.System.Profile.HardwareIdentification.GetPackageSpecificToken(null);

    byte[] byteArray = null;
    Windows.Security.Cryptography.CryptographicBuffer.CopyToByteArray(hardwareToken.Id, out byteArray);

    var deviceSerial = "";
    var offset = 0;

    // we filter the hardware modules that are unlikely to be changed, and aggregate them to a string.
    while (offset < hardwareToken.Id.Length)
        // CPU ID of the processor || Size of the memory || Serial number of the disk device || BIOS
        if ((byteArray[offset] == 1 || byteArray[offset] == 2 || byteArray[offset] == 3 || byteArray[offset] == 9) && byteArray[offset + 1] == 0)
            for (var i = 0; i < 4; i++)
                deviceSerial += byteArray[offset + i].ToString();
        offset += 4;

    return deviceSerial;


Happy coding!



Planet Xamarin

Planet Xamarin


<<  April 2018  >>

View posts in large calendar

Month List