skip to Main Content

I am working on displaying an image on a webpage that is exported to a pdf using the IronPDF library. The problem I am having is that changing the img tag in cshtml is causing the image to either display in the PDF or the webpage but not both.

Image file is stored in wwwroot/images folder.

Current img tag:

<img src="../images/Logo.png" alt="Logo" align="right" style="width:150px">

This displays the image in the PDF but not on the webpage. If I change the src to be .../images/Logo.png, that displays on the webpage but not the pdf.

PDF create method:

public string CreateAddendumPDF(string html, string agreementID)
{
    var render = new ChromePdfRenderer();
    render.RenderingOptions.MarginLeft = 17;
    render.RenderingOptions.MarginRight = 15;
    render.RenderingOptions.MarginTop = 14;
    render.RenderingOptions.FirstPageNumber = 1;

    var pdf = render.RenderHtmlAsPdf(html,@"wwwroot/images");

    string rootPath = _webHostEnvironment.WebRootPath;

    string path = Path.Combine(rootPath, ReportConstants.Temp + "Addendums\" + agreementID + "_" +"Addendum.pdf");

    pdf.SaveAs(path);

    return path;
}

I tried different image src values and could not get one to work in both the webpage and the pdf document. Next solution is to use Jquery to change the image tag when the user clicks the download pdf button.

2

Answers


  1. If your "Logo.png" is in wwwroot/images/ you could try something like this:

    <img src="~/wwwroot/images/Logo.png" alt="Logo" align="right" style="width:150px">
    

    or

    <img src="~/images/Logo.png" alt="Logo" align="right" style="width:150px">
    

    with this you should be able to get your image.

    I hope it helps.

    Login or Signup to reply.
  2. To ensure that the image can be found by IronPDF and displayed correctly on the website, the baseUrl of IronPDF and src="" attribute on HTML string need to be configured correctly. With the file hierarchy shown below set:

    • baseUrlOrPath to @"wwwroot/image"
    • src attribute to "../image/Sample.jpg"
    wwwroot
    └── image
        ├── Sample.jpg
        └── Sample.png
    

    As I have tested the overlapped below the baseUrlOrPath and src attribute is necessary.

    For example:

    C# code

    ChromePdfRenderer renderer = new ChromePdfRenderer();
    PdfDocument pdf = renderer.RenderHtmlAsPdf("html.Result", @"wwwroot/image");
    

    cshtml code

    <img src="../image/Sample.jpg"/>
    <img src="../image/Sample.png"/>
    

    Please visit Use HTML with CSS and Images to Create PDF in C# to learn more.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search