Can itextsharp.xmlworker render embedded images?

We need to write our own ImageTagProcessor to support processing of base 64 images:

public class CustomImageTagProcessor : iTextSharp.tool.xml.html.Image
{
    public override IList<IElement> End(IWorkerContext ctx, Tag tag, IList<IElement> currentContent)
    {
        IDictionary<string, string> attributes = tag.Attributes;
        string src;
        if (!attributes.TryGetValue(HTML.Attribute.SRC, out src))
            return new List<IElement>(1);

        if (string.IsNullOrEmpty(src))
            return new List<IElement>(1);

        if (src.StartsWith("data:image/", StringComparison.InvariantCultureIgnoreCase))
        {
            // data:[<MIME-type>][;charset=<encoding>][;base64],<data>
            var base64Data = src.Substring(src.IndexOf(",") + 1);
            var imagedata = Convert.FromBase64String(base64Data);
            var image = iTextSharp.text.Image.GetInstance(imagedata);

            var list = new List<IElement>();
            var htmlPipelineContext = GetHtmlPipelineContext(ctx);
            list.Add(GetCssAppliers().Apply(new Chunk((iTextSharp.text.Image)GetCssAppliers().Apply(image, tag, htmlPipelineContext), 0, 0, true), tag, htmlPipelineContext));
            return list;
        }
        else
        {
            return base.End(ctx, tag, currentContent);
        }
    }
}

Then we can inject this new processor into the HtmlPipelineContext:

        using (var doc = new Document(PageSize.A4))
        {
            var writer = PdfWriter.GetInstance(doc, new FileStream("test.pdf", FileMode.Create));
            doc.Open();
            var html = @"<img src='data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAD4AAABQCAMAAAB24TZcAAAABGdBTUEAANbY1E9YMgAAABl0RVh0U29mdHdhcmUAQWRvYmUgSW1hZ2VSZWFkeXHJZTwAAAGAUExURdSmeJp2SHlbQIRoSUg2J499a8KebqeHZuGufBEVJPz7+3NWPVxGMduwhPXEktnX1mtROLq7t5WDc2VMNv3LmKB8TMSidMbFxLGlmXlhSMSddpJUL+y8i3VlVqedlOzr6gUIF2lXRLCLY4ZyXLyYaYhtUYiJhJFyU1dBLLiVZnlwZrWRY/Hx8b+2rbySaJh9YqeooDw4NygnKvvJlpyblzksIUhGRryYckc7MPjGlKODX5x8VVA8K+azgM3FvDIn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YN7htNB8LxJmCnyaBZULpJ6/g4ZZQCX83FAS1u3675xnTaX/GKFdLl+gIaDZeFpU78rS9oDnzZEmHstqPJKc9n90LJPThyBUZIVRtMv8Q1v9Xx8bzxigddWo1t7yZ//zgSCwRiK6CO0PUD2OR4hMnhHfiPtYiJr4a8Jj4MbHNe7UC4RtTfc5wsd+DD6RbxxTZ8chtkrcJGIlqX41GqTVzFp3wmfmCNi5rNT74Z3nwHi2BjZW11AtdzgvxIfSBl4l/Klzr+bfLvzSNYA1u9xTfmz8f4lLmA5HWfgV8eTa7BEohxox1xeZ1F5Ef4fTrYnL4oGjb7QZ3JVgk2W4KJPMZvmWbo9KWJ27QsXKHm3DkhJT/Gs6z55lo0abV5wCSL5txL/CMa4PYPUXN+5qwTj68aXwa5MP4Efj/VDA4TW3BV3PQMp7Wlgnfg555mcPFO8RbXMbXv8Oh6pG3J7IRM8bq3Q/zKLFqUQ3GteNYvbepG1XG57O0Qt9Hmd1bOKC1qbZH/zbK78FWzYMJ2aZoXPq7kr8ZvORr+iUSjJzQb/Gpa5l8BBgBZTppAyfsf0wAAAABJRU5ErkJggg==' width='62' height='80' style='float: left; margin-right: 28px;' />";

            var tagProcessors = (DefaultTagProcessorFactory)Tags.GetHtmlTagProcessorFactory();
            tagProcessors.RemoveProcessor(HTML.Tag.IMG); // remove the default processor
            tagProcessors.AddProcessor(HTML.Tag.IMG, new CustomImageTagProcessor()); // use our new processor

            CssFilesImpl cssFiles = new CssFilesImpl();
            cssFiles.Add(XMLWorkerHelper.GetInstance().GetDefaultCSS()); 
            var cssResolver = new StyleAttrCSSResolver(cssFiles);
            cssResolver.AddCss(@"code { padding: 2px 4px; }", "utf-8", true);
            var charset = Encoding.UTF8;
            var hpc = new HtmlPipelineContext(new CssAppliersImpl(new XMLWorkerFontProvider()));
            hpc.SetAcceptUnknown(true).AutoBookmark(true).SetTagFactory(tagProcessors); // inject the tagProcessors
            var htmlPipeline = new HtmlPipeline(hpc, new PdfWriterPipeline(doc, writer));
            var pipeline = new CssResolverPipeline(cssResolver, htmlPipeline);
            var worker = new XMLWorker(pipeline, true);
            var xmlParser = new XMLParser(true, worker, charset);
            xmlParser.Parse(new StringReader(html));
        }
        Process.Start("test.pdf");

            string originalFile = "Original1.pdf";
            string copyOfOriginal = "Re-copia.pdf";

            byte[] bytes = Convert.FromBase64String(archivo);

            System.IO.FileStream stream = new FileStream(originalFile, FileMode.CreateNew);
            System.IO.BinaryWriter writer = new BinaryWriter(stream);
            writer.Write(bytes, 0, bytes.Length);
            writer.Close();

            PdfReader reader1 = new PdfReader(originalFile);
            using (FileStream fs = new FileStream(copyOfOriginal, FileMode.Create, FileAccess.Write, FileShare.None))
            // Creating iTextSharp.text.pdf.PdfStamper object to write
            // Data from iTextSharp.text.pdf.PdfReader object to FileStream object
            using (PdfStamper stamper = new PdfStamper(reader1, fs))
            {

                int pageCount = reader1.NumberOfPages;

                // Create New Layer for Watermark
                PdfLayer layer = new PdfLayer("WatermarkLayer", stamper.Writer);
                // Loop through each Page
                for (int i = pageCount; i <= pageCount; i++)
                {
                    // Getting the Page Size
                    Rectangle rect = reader1.GetPageSize(i);



                    // Get the ContentByte object
                    PdfContentByte cb = stamper.GetUnderContent(i);

                    // Tell the cb that the next commands should be "bound" to this new layer
                    cb.BeginLayer(layer);
                    cb.SetFontAndSize(BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.NOT_EMBEDDED), 50);

                    PdfGState gState = new PdfGState();
                    cb.SetGState(gState);


                    string codbartest = codBarras;
                    BarcodePDF417 bcpdf417 = new BarcodePDF417();
                    //Asigna el código de barras en base64 a la propiedad text del objeto..
                    bcpdf417.Text = ASCIIEncoding.ASCII.GetBytes(codbartest);
                    Image imgpdf417 = bcpdf417.GetImage();
                    imgpdf417.SetAbsolutePosition(50, 50);
                    imgpdf417.ScalePercent(100);
                    cb.AddImage(imgpdf417);
                    // Close the layer
                    cb.EndLayer();
                }[enter image description here][1]

Comments

  1. Callan

    • 2018/12/5

    We need to write our own ImageTagProcessor to support processing of base 64 images: public class CustomImageTagProcessor 

  2. Rizzi

    • 2018/10/26

    Can itextsharp.xmlworker render embedded images? Ask Question Asked 7 years, 10 months ago. Active 3 years, 8 months ago. Viewed 17k times

  3. Carter

    • 2019/7/14

    Can itextsharp.xmlworker render embedded images? Brennan. Jul 12th 2021, 11:5 am. Never. You are currently not 

  4. Mancini

    • 2019/9/21

    Can itextsharp.xmlworker render embedded images? 6. iText XML to PDF using latest version. 2. Could not load type 'iTextSharp.text.html.HtmlParser' from assembly

  5. Franklin

    • 2020/12/10

    How to display Base64 images in HTML? c# - itextsharp.xmlworker Can I render embedded images? html - Multiple use of Base64 embedded images · html - Can 

  6. Dustin

    • 2017/7/22

    32 Can itextsharp.xmlworker render embedded images? Oct 16 '13 31 The DbContext of type cannot be pooled because it does not have a single public constructor accepting a single parameter of type DbContextOptions Sep 5 '17

  7. Jad

    • 2018/3/25

    Out of the box XMLWorker only understands absolute URIs, but Store(string src, Image img) is easy - note inline comments there and for 

  8. Ibrahim

    • 2016/9/26

    By default, images are embedded at 72 dpi (Dots Per Inch) which coincidentally, matches the number of points in an inch. If this file was being prepared for printing, the final job would be a bit nasty. Generally, commercial printers require that colour images for printing have a resolution of 300 dpi. To achieve this, you can scale the image

  9. Lambert

    • 2019/2/5

    Yes, iText supports external images as shown in different examples in the previous chapters, but it also supports inline images stored as Base64 strings.

  10. Reid

    • 2015/5/27

    Can itextsharp.xmlworker render embedded images? 5. Where can I find an iText xml reference? 2. Applying style to div having a class name iTextSharp. 0.

  11. Jonas

    • 2017/11/2

    Acrescente as bibliotecas itextsharp e itextsharp.xmlworker ao seu projeto; [Can itextsharp.xmlworker render embedded images?]

  12. Vincent

    • 2021/2/1

    The above CustomImageTagProcessor class resolves the Images and the image will be encoded in the pdf. Now the final json result will get a pdfstring which is a base64 encoded format. use a javascript file to call the "GeneratePdf" post method and capture the json result and convert the pdfstring to blob and render in the browser or download

  13. Lincoln

    • 2018/2/11

    A PDF file, however, must be independent of the rendering device, XMLWorker can be more complicated sometimes but those complications also make it more 

  14. Kace

    • 2018/1/24

    Out of the box XMLWorker only understands absolute URIs, so the described issues are expected behavior. The parser can't automagically deduce URI schemes or paths without some additional information. Implementing an ILinkProvider fixes the broken hyperlink problem, and implementing an IImageProvider fixes the broken image problem.

  15. Esposito

    • 2018/12/30

    Can itextsharp.xmlworker render embedded images? (2 답변) 3 년 전에 문을 닫았습니다. html 조각을 삽입 해야하는 PDF 보고서를 작성 중입니다.

  16. Erick

    • 2020/7/18

    Visual C# 2015 RC Compiler Could Not Be Created Can itextsharp.xmlworker render embedded images? Using Fonts in System with iTextSharp.

Comments are closed.

Recent Posts