简体   繁体   中英

How to Convert HTML Template into PDF using ITextsharp version less than 5 using ASP.net Core?

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");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM