2

I am developing an Application in Xamarin for Android. I have already generated HTML file using StringBuilder. Now I have a HTML file in my External storage and the same template is required for PDF. So when I try to convert HTML to PDF using iTextSharp using XML Worker & PDFSharp libraries, I am getting build errors due to missing System.Drawing.dll. Then I found from Xamarin forums & Stackoverflow links that it is not supported for Xamarin.Android.

Can anyone please tell me other alternative about how to create template for PDF or any other working nuget package for Xamarin.Android which will convert html file to pdf.

NOTE: I am able to generate PDF but not able to convert HTML to PDF.

It would be of great help!. Thanks a ton!.

shakunthalaMK
  • 386
  • 1
  • 4
  • 20
  • Have a look at this question http://stackoverflow.com/questions/7597103/generate-pdf-based-on-html-code-itextsharp-pdfsharp – InitLipton Nov 11 '16 at 13:35
  • @InitLipton I checked but got this following error "Could not install package 'HtmlRenderer.Core 1.5.0.5'. You are trying to install this package into a project that targets 'MonoAndroid,Version=v6.0', but the package does not contain any assembly references or content files that are compatible with that framework. For more information, contact the package author." And in my project properties, Compile using Android version provides only "Use latest platform" option. So, I am unable to change the version as well. – shakunthalaMK Nov 14 '16 at 08:00

1 Answers1

4

Use Nuget package Xam.iTextSharpLGPL

Below is the sample code

using System.IO;
using iTextSharp.text;
using iTextSharp.text.pdf;
using iTextSharp.text.html.simpleparser;
using Android.Graphics;


  string path = Android.OS.Environment.ExternalStorageDirectory.Path;
  string pdfPath = System.IO.Path.Combine(path, "samplee.pdf");
  System.IO.FileStream fs = new FileStream(pdfPath, FileMode.Create);    
  Document document = new Document(PageSize.A4);
  PdfWriter writer = PdfWriter.GetInstance(document, fs);
  HTMLWorker worker = new HTMLWorker(document);
  document.Open();
  StringBuilder html = new StringBuilder();
  html.Append("<? xml version='1.0' encoding='utf-8' ?><html><head><title></title></head>");
  html.Append("<CENTER>Simple Sample html</H1>");
  html.Append("<H4>By User1</H4>");
  html.Append("<H2>Demonstrating a few HTML features</H2>");
  html.Append("</CENTER>");
  html.Append("<p>HTML doesn't normally use line breaks for ordinary text. A white space of any size is treated as a single space. This is because the author of the page has no way of knowing the size of the reader's screen, or what size type they will have their browser set for.");
  html.Append("</p></body</html>");
  TextReader reader = new StringReader(html.ToString());
  worker.StartDocument();
  worker.Parse(reader);
  worker.EndDocument();
  worker.Close();
  document.Close();
  writer.Close();
  fs.Close();
Rolwin Crasta
  • 4,219
  • 3
  • 35
  • 45