Generate PDF based on HTML code (iTextSharp, PDFSharp?)

前端 未结 10 2031
南笙
南笙 2020-12-08 08:15

Does the library PDFSharp can - like iTextSharp - generate PDF files *take into account HTML formatting *? (bold (strong), spacing

相关标签:
10条回答
  • 2020-12-08 08:50

    Have you guys heard of this. I might be answering very late but I thought it helps. It is very simple and works well.

    var htmlContent = String.Format("<body>Hello world: {0}</body>", 
            DateTime.Now);
    var htmlToPdf = new NReco.PdfGenerator.HtmlToPdfConverter();
    var pdfBytes = htmlToPdf.GeneratePdf(htmlContent);
    

    Edit: I came here with the question of converting HTML code to PDF using 'PDFSharp' and found out that 'PDFSharp' cannot do it then I found out about NReco and it worked for me so I felt it might help someone just like me.

    0 讨论(0)
  • 2020-12-08 08:50

    HTML Renderer for PDF using PdfSharp can generate a PDF from an HTML

    1. as an image, or
    2. as text

    before inserting to the PDF.

    To render as an image, please refer to the code from Diego answer.

    To render as text, please refer code below:

    static void Main(string[] args)
    {
        string html = File.ReadAllText(@"C:\Temp\Test.html");
        PdfDocument pdf = PdfGenerator.GeneratePdf(html, PageSize.A4, 20, null, OnStylesheetLoad, OnImageLoadPdfSharp);
        pdf.Save(@"C:\Temp\Test.pdf");
    }
    
    public static void OnImageLoadPdfSharp(object sender, HtmlImageLoadEventArgs e)
    {
        var imgObj = Image.FromFile(@"C:\Temp\Test.png");
        e.Callback(XImage.FromGdiPlusImage(imgObj));    
    }
    
    public static void OnStylesheetLoad(object sender, HtmlStylesheetLoadEventArgs e)
    {
        e.SetStyleSheet = @"h1, h2, h3 { color: navy; font-weight:normal; }";
    }
    

    HTML code

    <html>
        <head>
            <title></title>
            <link rel="Stylesheet" href="StyleSheet" />      
        </head>
        <body>
            <h1>Images
                <img src="ImageIcon" />
            </h1>
        </body>
    </html>
    
    0 讨论(0)
  • 2020-12-08 08:53

    No, PDFsharp does not currently include code to parse HTML files.

    0 讨论(0)
  • 2020-12-08 08:54

    I'll recommend you NReco.PdfGenerator because have free and paid license and its easy to install from nuget.

    Main page: https://www.nrecosite.com/pdf_generator_net.aspx

    Documentation: https://www.nrecosite.com/doc/NReco.PdfGenerator/

    If you want create PDF from html file try:

    String html = File.ReadAllText("main.html");
    var htmlToPdf = new NReco.PdfGenerator.HtmlToPdfConverter();
    htmlToPdf.GeneratePdf(html, null, "C:/Users/Tmp/Desktop/mapa.pdf");
    
    0 讨论(0)
提交回复
热议问题