I have to convert this Html tempelate written in notepad into PDF using itextsharp
Asked
Active
Viewed 1,406 times
-1
-
Google `NReco.PdfGenerator` it would give you what you want. – iSR5 Aug 14 '20 at 10:56
-
I have to use itextsharp – UmeshDixit Aug 14 '20 at 11:00
-
Then, read this : https://stackoverflow.com/questions/25164257/how-to-convert-html-to-pdf-using-itextsharp – iSR5 Aug 14 '20 at 11:01
1 Answers
0
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
Michael Wang
- 3,248
- 1
- 3
- 14
-
Hi, @UmeshDixit, please let us know if you have updated information on this issue. – Michael Wang Aug 20 '20 at 08:00