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

前端 未结 10 2073
南笙
南笙 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

    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

    
        
            
                  
        
        
            

    Images

提交回复
热议问题