Unable to create PDF from HTML in Xamarin Android

跟風遠走 提交于 2019-12-06 05:24:19

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();
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!