0

I am trying to create a simple example to embed an an image into a PDF either using HTML to PDF with image sharp or QuestPDF

with QuestPDF i have tried the following


public void Crear(string output)
        {
            try
            {
                var doc = Document.Create(container =>
                
                     container.Page(p => {

                        p.Size(PageSizes.A0.Landscape());
                        p.Content().Layers(l =>
                        {
                            l.PrimaryLayer().Stack(stack => {


                                var text = stack.Item().Text("Hello");
                            });
                            l.Layer().Image(( Model.CaraA_2 ));
                        });
                        //p.Content().Canvas((canva, e) =>
                        //{
                        //    canva.DrawBitmap(GetBitmapFrom(Model.CaraA_2), new SKRect(600, 600, 500, 500));
                        //});
                    }
                        )
                        .Page(page => {

                            page.Size(PageSizes.A0.Landscape());
                            
                            page.Content().Layers(l =>
                            { 
                                 l.PrimaryLayer().Stack(stack => {


                                     var text =stack.Item().Text("Hello");
                                 });
                                 l.Layer().Image((Model.CaraB_1)); 
                            });
                    //page.Content().Canvas((canva, e) =>
                    //{
                    //    canva.DrawBitmap(GetBitmapFrom(Model.CaraB_1), new SKRect(600, 600, 500, 500));

                    //});



                    })


                );
                doc.GeneratePdf(output);
            }
            catch (Exception ex)
            {

            }
            

        }

this prints 2 empty pages in QuestPDF

while in ITextSharp it produces a PDF with the text but without the images... only is able to embed the qr core at the last part of the PDF here is the HTML text for the PDF https://gist.github.com/PontiacGTX/6c9ab85b0d33ccc550ada12f8ba43ab4 for Itextsharp


 public static string CreatePdf(string[] body, string output)
            {
                
                float dpi = 100f;
                float widthInches = (3600f *1.1f)/ dpi;
                float heightInches =( 2575f*1.1f) / dpi;
                var pageSize = new iTextSharp.text.Rectangle(widthInches * 72f, heightInches * 72f);
                var rect = new iTextSharp.text.Rectangle(widthInches * 72f, heightInches * 72f);


                iTextSharp.text.Document pdfDoc = new iTextSharp.text.Document(rect, 10f, 10f, 10f, 0f);
                HTMLWorker htmlparser = new HTMLWorker(pdfDoc);
                using (MemoryStream memoryStream = new MemoryStream())
                {
                  

                    try
                    {

                        PdfWriter writer = PdfWriter.GetInstance(pdfDoc, memoryStream);
                        pdfDoc.Open();
                        for(var i=0;i< body.Length;i++)
                        {
                            htmlparser.Parse(new StringReader(body[i]));
                            if(body.Length>1 && body.Length-1!=i)
                            {
                                htmlparser.NewPage();
                            }
                            
                        }


                        pdfDoc.Close();

                        byte[] bytes = memoryStream.ToArray();
                        System.IO.File.WriteAllBytes(output, bytes);
                        memoryStream.Close();
                       
                    }
                    catch (Exception ex)
                    {
                    }
                }

                        
                return output;
            }

the code to convert the file to a base64:

 private string ImagePathToBase64(string path,string mimeType)
        {
            if (!System.IO.File.Exists(path))
            {
                throw new Exception($"File not found {path}");
            }
            var bytes = System.IO.File.ReadAllBytes(path);
            return $"data:{mimeType};base64,{Convert.ToBase64String(bytes)}";
        }
PontiacGTX
  • 185
  • 2
  • 15
  • If you've set the `img` element's `src` attribute to a path then that's probably your issue. For iTextSharp you probably need to encode the image with Base64 and apply that value to the `img` element's `src` property, and not a path to an image. [How to Apply Base64 Images in HTML](https://www.w3docs.com/snippets/html/how-to-display-base64-images-in-html.html) and [Image from path to Base64 string](https://stackoverflow.com/questions/21325661/convert-an-image-selected-by-path-to-base64-string) – quaabaam May 17 '23 at 23:03
  • @quaabaam yes it is an absolute path i will try sending the image's base64 and report back thank you – PontiacGTX May 17 '23 at 23:21
  • @quaabaam it throws an exceptions tating that "The given path's format is not supported" when using base64 on the src attribute – PontiacGTX May 18 '23 at 02:04
  • Did you add the `data:image/png;base64,` before the Base64 encoding? If you take the example from the link above and past it in an HTML file and open it does it show the 'red dot' image? – quaabaam May 18 '23 at 16:34
  • @quaabaam i will add to the OP the code to convert the file to base64 – PontiacGTX May 18 '23 at 16:52
  • 1
    @quaabaam Are you sure the iTextSharp `HtmlWorker` supports base64 img sources? I had a quick glance at the sources of the old iText variants and only in the OpenPDF `HtmlWorker` I could spot base64 img support... – mkl May 18 '23 at 17:01
  • @PontiacGTX While not finding (at quick glance) base64 img support in iTextSharp's `HtmlWorker`, I saw numerous options to retrieve images from there, by absolute and relative URL, via an image provider, and via static maps. You might want to debug your code and descend into the iTextSharp code to determine why your images are not displayed. Depending on what you identify as cause, one of the alternatives might be better suited to your task. – mkl May 18 '23 at 17:10
  • @PontiacGTX And just to be sure, have you checked whether possibly iTextSharp might have issues with the format of your image? Simply export one example of those images as file and use iTextSharp to create a simple PDF containing just that image loaded directly, not via HTML. – mkl May 18 '23 at 17:14
  • @mkl i have thought about using a lower resolutionof the image, but I wanted to rule out any possible code bug but I can see that maybe I should do a simple pdf with a lower resolution image just in case there is a resolution scaling issue? – PontiacGTX May 18 '23 at 17:48
  • @mkl I changed the resolution twice by reducing it by 50% each time and used only a body wrapping a div wrapping an image and nothing changed no image is being displayed somehow – PontiacGTX May 18 '23 at 18:03
  • @mkl what do you mean by not loading via html? – PontiacGTX May 18 '23 at 18:07
  • *"what do you mean by not loading via html"* - iTextSharp foremost is a library to directly create PDF content, by adding objects like paragraphs or images to a `Document`. So I mean you should load your image into a iText `Image` object and add that to your `Document pdfDoc` instead of using the `HtmlWorker`. – mkl May 18 '23 at 22:09
  • @mkl I will try that next – PontiacGTX May 19 '23 at 00:56

0 Answers0