Hello everyone ! In this post I'm gonna show, how we can programmatically generate PDF files in our WinRT applications. This a typical requirement in applications like Shopping App, Inventory Management, Banking System etc.. where we may want to generate an invoice for our customers or generate a pdf to show a mini-statement in any banking or finance app and print it.
iTextSharp to the rescue !
iText is a PDF library that allows you to CREATE, ADAPT, INSPECT and MAINTAIN documents in the Portable Document Format (PDF)
Generate documents and reports based on data from an XML file or a database.
I've found a lot of stuff which demonstrates the use of iTextSharp in ASP.NET applications but very few on the modern WinRT apps.
Hence, I decided to make one of my own and provide some help to you fellow developers.
Enough said ! Let's directly dive into the code and see a working sample.
1. Install iTextSharp library for Nuget Packages.
iTextSharp to the rescue !
iText is a PDF library that allows you to CREATE, ADAPT, INSPECT and MAINTAIN documents in the Portable Document Format (PDF)
Generate documents and reports based on data from an XML file or a database.
I've found a lot of stuff which demonstrates the use of iTextSharp in ASP.NET applications but very few on the modern WinRT apps.
Hence, I decided to make one of my own and provide some help to you fellow developers.
Enough said ! Let's directly dive into the code and see a working sample.
1. Install iTextSharp library for Nuget Packages.
2. Next, I create a method to generate a random string to a give a name to the StorageFile object and avoid collisions on every create.
public string RandomString(int length)
{
const string chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
var random = new Random();
return new string(Enumerable.Repeat(chars, length)
.Select(s => s[random.Next(s.Length)]).ToArray()) + ".pdf";
}
3. Create methods for formatting the text that is going to be added to the tableview.private static void AddCellToHeader(PdfPTable tableLayout, string cellText)
{
tableLayout.AddCell(new PdfPCell(new Phrase(cellText, new Font(Font.FontFamily.TIMES_ROMAN, 10,1, iTextSharp.text.BaseColor.BLACK)))
{ HorizontalAlignment = Element.ALIGN_CENTER,
Padding = 5,
BackgroundColor = new BaseColor(255, 255, 255)
});
}
private static void AddCellToBody(PdfPTable tableLayout, string cellText)
{
tableLayout.AddCell(new PdfPCell(new Phrase(cellText, new Font(Font.FontFamily.TIMES_ROMAN, 10, 1, iTextSharp.text.BaseColor.BLACK)))
{
HorizontalAlignment = Element.ALIGN_CENTER,
Padding = 5,
BackgroundColor = new BaseColor(255, 255, 255)
});
}
4.Add the following code to generate the pdf file.(In this sample I've demonstrated an example of Mini Statement used in a banking app.)
protected override async void OnNavigatedTo(NavigationEventArgs e)
{
try
{
string path = RandomString(5);
var storageFolder = Windows.Storage.ApplicationData.Current.LocalFolder;
var file = await storageFolder.CreateFileAsync(path, CreationCollisionOption.ReplaceExisting);
if (file != null)
{
await FileIO.WriteTextAsync(file, string.Empty);
}
sampleFile = await storageFolder.GetFileAsync(path);
var stream = await sampleFile.OpenAsync(Windows.Storage.FileAccessMode.ReadWrite);
Document document = new Document(PageSize.A4, 25, 25, 30, 30);
PdfWriter writer = PdfWriter.GetInstance(document, stream.AsStream());
document.Open();
document.Add(new Paragraph("Mini Statement"));
document.Add(new Chunk("\n")); // to all line breaks
document.Add(new Chunk("\n"));
PdfPTable tableLayout = new PdfPTable(4);
float[] headers = { 60, 60, 60, 60 };
tableLayout.SetWidths(headers);
tableLayout.HorizontalAlignment = Element.ALIGN_LEFT;
tableLayout.WidthPercentage = 80;
//Add header
AddCellToHeader(tableLayout, "Sr no.");
AddCellToHeader(tableLayout, "Transaction Type");
AddCellToHeader(tableLayout, "Date");
AddCellToHeader(tableLayout, "Amount");
AddCellToBody(tableLayout, "1.");
AddCellToBody(tableLayout, "Cash Withdrawal");
AddCellToBody(tableLayout, "April 24, 2015");
AddCellToBody(tableLayout, "2500");
AddCellToBody(tableLayout, "2.");
AddCellToBody(tableLayout, "Cash Deposit");
AddCellToBody(tableLayout, "July 7, 2015");
AddCellToBody(tableLayout, "3500");
AddCellToBody(tableLayout, "3.");
AddCellToBody(tableLayout, "Funds Transfer");
AddCellToBody(tableLayout, "October 20, 2015");
AddCellToBody(tableLayout, "930");
AddCellToBody(tableLayout, "4.");
AddCellToBody(tableLayout, "NEFT Transfer");
AddCellToBody(tableLayout, "November 5, 2015");
AddCellToBody(tableLayout, "10,000");
AddCellToBody(tableLayout, "5.");
AddCellToBody(tableLayout, "Cash Withdrawal");
AddCellToBody(tableLayout, "April 24, 2015");
AddCellToBody(tableLayout, "2500");
AddCellToBody(tableLayout, "6.");
AddCellToBody(tableLayout, "Cash Deposit");
AddCellToBody(tableLayout, "July 7, 2015");
AddCellToBody(tableLayout, "3500");
AddCellToBody(tableLayout, "7.");
AddCellToBody(tableLayout, "Funds Transfer");
AddCellToBody(tableLayout, "October 20, 2015");
AddCellToBody(tableLayout, "930");
AddCellToBody(tableLayout, "8.");
AddCellToBody(tableLayout, "NEFT Transfer");
AddCellToBody(tableLayout, "November 5, 2015");
AddCellToBody(tableLayout, "10,000");
AddCellToBody(tableLayout, "9.");
AddCellToBody(tableLayout, "NEFT Transfer");
AddCellToBody(tableLayout, "November 5, 2015");
AddCellToBody(tableLayout, "10,000");
AddCellToBody(tableLayout, "10.");
AddCellToBody(tableLayout, "Cash Withdrawal");
AddCellToBody(tableLayout, "April 24, 2015");
AddCellToBody(tableLayout, "2500");
document.Add(tableLayout);
// add image to the pdf
StorageFile imgfile = await Windows.ApplicationModel.Package.Current.InstalledLocation.GetFileAsync(@"Assets\verified.jpg");
iTextSharp.text.Image img = iTextSharp.text.Image.GetInstance(new Uri((imgfile.Path)));
document.Add(img);
document.Close();
writer.Close();
}
catch (Exception) { }
}
And that is all. You have you pdf ready which can be saved and printed.

Download the entire source code.
Happy Coding !
No comments :
Post a Comment