I have to convert this Html tempelate written in notepad into PDF using itextsharp
<Body>
<h3>Hello</h3><img src="https://i.stack.imgur.com/nMwn1.png">
</Body>
I have to convert this Html tempelate written in notepad into PDF using itextsharp
<Body>
<h3>Hello</h3><img src="https://i.stack.imgur.com/nMwn1.png">
</Body>
Install a package called iTextSharp
through Nuget Package.
using iTextSharp.text;
using iTextSharp.text.html.simpleparser;
using iTextSharp.text.pdf;
public class PdfController : Controller
{
[Route("/htmlpdf")]
public FileStreamResult DownloadPDF()
{
string HTMLContent = "Hello <b>World</b>";// Put your html tempelate here
MemoryStream ms = new MemoryStream();
TextReader txtReader = new StringReader(HTMLContent);
// 1: create object of a itextsharp document class
Document doc = new Document(PageSize.A4, 25, 25, 25, 25);
// 2: we create a itextsharp pdfwriter that listens to the document and directs a XML-stream to a file
PdfWriter PdfWriter = PdfWriter.GetInstance(doc, ms);
PdfWriter.CloseStream = false;
// 3: we create a worker parse the document
HTMLWorker htmlWorker = new HTMLWorker(doc);
// 4: we open document and start the worker on the document
doc.Open();
htmlWorker.StartDocument();
// 5: parse the html into the document
htmlWorker.Parse(txtReader);
// 6: close the document and the worker
htmlWorker.EndDocument();
htmlWorker.Close();
doc.Close();
ms.Flush(); //Always catches me out
ms.Position = 0; //Not sure if this is required
return File(ms, "application/pdf", "HelloWorld.pdf");
}
}
Test of result
//You can also use this free "SelectPdf" library for basic use
SelectPdf.HtmlToPdf converter = new SelectPdf.HtmlToPdf();
//SelectPdf.PdfDocument doc = converter.ConvertUrl("https://google.com");
SelectPdf.PdfDocument doc = converter.ConvertHtmlString(HTMLContent.ToString());
doc.Save("test.pdf");