We're sorry Aspose doesn't work properply without JavaScript enabled.

Free Support Forum - aspose.com

HTML to PDF - Images do not render

I am using the following code to convert from HTML to PDF. Although the PDF is created, no images are rendered. I have tried just about every possible combination of the baseUri and actual image address, but to no avail. The page detailing the conversion to PDF mechanism (HTML to PDF Conversion) does not include examples with images. Nor does it demonstrate the use of the basrUri property (which I’m assuming is what I need to specify)

public Stream Convert(string html, int height, int width, string baseUrl = "")
{
	try
	{
		var options = new Aspose.Html.Rendering.Pdf.PdfRenderingOptions
		{
			PageSetup =
			{
				AnyPage = new Page(new Size(height, width)),
				AdjustToWidestPage = true
			}
		};

		var output = new MemoryStream();

		using (var stream = new MemoryStream())
		using (var writer = new StreamWriter(stream))
		{
			writer.Write(html);
			writer.Flush();
			stream.Position = 0;
			using (var device = new Aspose.Html.Rendering.Pdf.PdfDevice(options, output))
			using (var renderer = new HtmlRenderer())
			using (var document = new HTMLDocument(stream, baseUrl))
			{
				Console.WriteLine(document.Images.Length);
				Console.WriteLine(document.Images[0].Attributes["src"]);
				Console.WriteLine(document.Body.InnerHTML);
				renderer.Render(device, document);
			}

			output.Position = 0;
			return output;
		}
	}
	catch (Exception ex)
	{
		throw new ApplicationException("Error converting to PDF!", ex);
	}
}

@smclean

Thank you for contacting support.

Would you please share source and generated ZIP files with us so that we may try to reproduce and investigate it in our environment.

Thanks for the response.

I have attached a solution file containing a class that performs the conversion and a small test application that generates some very simple HTML and calls the conversion to PDF.

I have included a result PDF file, where you can see the issue (the alt attribute value is rendered, but the image itself is not).

Thank you in advance for taking a look.

DataBank.HtmlConverter.zip (296.3 KB)

@smclean

Thank you for sharing requested data.

We have worked with the data shared by you and have been able to reproduce the issue in our environment. A ticket with ID HTMLNET-1810 has been logged in our issue management system for further investigation and resolution. The ticket ID has been linked with this thread so that you will receive notification as soon as the ticket is resolved.

We are sorry for the inconvenience.

Hi,

Was this every fixed because images are still not rendering for me. I was able to get the PDF of live website but not the images. Please let me know what am I missing.

Thanks

@smclean @Sonal.g

We would like to share our findings about logged ticket, the problem is the server settings which is the case when loading the image.
The server terminates the connection for the default TLS Protocol in the .Net Framework 4.5.2.

There are two ways to handle an exception:

  1. The first way in example 1 is to use the OnError delegate.
  2. The second way in example 2 is to create your own message handler and analyze the error in it.

The problem is the server settings which is the case when loading the image.
The server terminates the connection for the default TLS Protocol in the .net framework 4.5.2
There are two ways to handle an exception.
The first way in example 1 is to use the OnError delegate.
The second way in example 2 is to create your own message handler and analyze the error in it.

using System;
using System.IO;
using System.Threading;
using System.Net;
using Aspose.Html;
using Aspose.Html.Dom.Events;
using Aspose.Html.Drawing;
using Aspose.Html.Net;
using Aspose.Html.Rendering;
using Aspose.Html.Services;

namespace TestLoadingImage
{
    class Program
    {
        static string html =
            "<html><head></head><body>TEST<br><img alt=\"Test Image\" src=\"https://www.databankimx.com/wp-content/uploads/2019/02/Government.jpg\"></body></html>";

        static void Main(string[] args)
        {
            Example1();
            Example2();
            Console.ReadLine();
        }

        /// <summary>
        ///  The using an OnError delegate for treatment of error event
        /// </summary>
        static void Example1() {
            Console.WriteLine("Example 1");
            var outputsStream = new MemoryStream();

            using (var stream = new MemoryStream())
            using (var writer = new StreamWriter(stream))
            {
                writer.Write(html);
                writer.Flush();
                stream.Position = 0;
                ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls;
                var options = new Aspose.Html.Rendering.Pdf.PdfRenderingOptions
                                  {
                                      PageSetup =
                                          {
                                              AnyPage = new Page(new Size(800, 600)),
                                              AdjustToWidestPage = true
                                          }
                                  };

                using (var device = new Aspose.Html.Rendering.Pdf.PdfDevice(options, outputsStream))
                using (var renderer = new HtmlRenderer())
                using (var document = new HTMLDocument())
                {
                    document.OnError += delegate(object sender, Event _event)
                        {
                            Console.WriteLine(((ErrorEvent)_event).Error); 
                        };

                    var wh = new ManualResetEvent(false);
                    document.OnLoad += delegate (object sender, Event _event) { wh.Set(); };

                    document.Navigate(stream, "test.html");
                    wh.WaitOne();

                    renderer.Render(device, document);
                }
            }
        }

        /// <summary>
        /// In this example, using of class MyMessageHandler inherited from MessageHandler,
        /// to handle possible network errors when loading a document
        /// </summary>
        static void Example2()
        {
            Console.WriteLine("Example 2");
            var outputsStream = new MemoryStream();

            using (var stream = new MemoryStream())
            using (var writer = new StreamWriter(stream))
            {
                writer.Write(html);
                writer.Flush();
                stream.Position = 0;

                var configuration = new Configuration();
                configuration.GetService<INetworkService>().MessageHandlers.Add(new MyMessageHandler());

                var options = new Aspose.Html.Rendering.Pdf.PdfRenderingOptions
                                  {
                                      PageSetup =
                                          {
                                              AnyPage = new Page(new Size(800, 600)),
                                              AdjustToWidestPage = true
                                          }
                                  };

                using (var device = new Aspose.Html.Rendering.Pdf.PdfDevice(options, outputsStream))
                using (var renderer = new HtmlRenderer())
                using (var document = new HTMLDocument(stream, "test.html", configuration))
                {
                    renderer.Render(device, document);
                }
            }
        }

        public class MyMessageHandler : MessageHandler
        {
            public override void Invoke(INetworkOperationContext context)
            {
                if (!context.Response.IsSuccess)
                {
                    if (context.Response.Content != null)
                    {
                        Console.WriteLine(context.Response.Content.ReadAsString());
                    }
                }

                Next(context);
            }
        }
    }
}

The problem with loading the image can be corrected by specifying the explicitly used version of the TLS Protocol:

ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;

You can read more about this issue with the TLS Protocol version over this link.

Please feel free to contact us if you need any further assistance.