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

前端 未结 10 2074
南笙
南笙 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:46

    If you only want a certain HTML string written to the PDF but not the rest, you can use the HtmlContainer from TheArtOfDev HtmlRenderer. This snippet uses V 1.5.1

    using PdfSharp.Pdf;
    using PdfSharp;
    using PdfSharp.Drawing;
    using TheArtOfDev.HtmlRenderer.PdfSharp;
    
    //create a pdf document
    using (PdfDocument doc = new PdfDocument())
    {
        doc.Info.Title = "StackOverflow Demo PDF";
    
        //add a page
        PdfPage page = doc.AddPage();
        page.Size = PageSize.A4;
    
        //fonts and styles
        XFont font = new XFont("Arial", 10, XFontStyle.Regular);
        XSolidBrush brush = new XSolidBrush(XColor.FromArgb(0, 0, 0));
    
        using (XGraphics gfx = XGraphics.FromPdfPage(page))
        {
            //write a normal string
            gfx.DrawString("A normal string written to the PDF.", font, brush, new XRect(15, 15, page.Width, page.Height), XStringFormats.TopLeft);
    
            //write the html string to the pdf
            using (var container = new HtmlContainer())
            {
                var pageSize = new XSize(page.Width, page.Height);
    
                container.Location = new XPoint(15,  45);
                container.MaxSize = pageSize;
                container.PageSize = pageSize;
                container.SetHtml("This is a HTML string written to the PDF.

    www.google.nl"); using (var measure = XGraphics.CreateMeasureContext(pageSize, XGraphicsUnit.Point, XPageDirection.Downwards)) { container.PerformLayout(measure); } gfx.IntersectClip(new XRect(0, 0, page.Width, page.Height)); container.PerformPaint(gfx); } } //write the pdf to a byte array to serve as download, attach to an email etc. byte[] bin; using (MemoryStream stream = new MemoryStream()) { doc.Save(stream, false); bin = stream.ToArray(); } }

提交回复
热议问题