Search code examples
wkhtmltopdfdjango-wkhtmltopdf

wkhtmltopdf exclude css files from PDF but show in HTML


I was working with wkhmtltopdf and found that I have a problem with it. I am using the html page to also preview the content in a browser prior to converting to PDF.

But to make it more readable in my preview, I have added some css on the page: (In javascript/jQuery on document ready)

  $(document).ready(function () {
    if(window.location.href.indexOf("preview") > -1 && window.location.href.indexOf(".pdf") == -1) {
      appendCSStoHtml();
    }
  });

  function appendCSStoHtml() {
    $("body").css({"background-color":" #F0F8FF"});

    $("#previewHtml").css({
      "margin-left":"15%",
      "margin-right":"15%",
      "margin-top":"15px",
      "max-width":"1024px"});

    $("#previewHtml > h2").css({"margin-left":" 15px"});
  }

So this is all good and dandy, but when I generate my PDF based on this HTML page, then the css is also renderend inside my PDF and the outlining and background are also present inside the PDF.

I don't want this to happen, I only want my css style elements to be renderen on the HTML page and not inside the PDF.

How can I achieve this?

I tried with the following:

  $(document).ready(function () {
    if(window.location.href.indexOf("preview") > -1 && window.location.href.indexOf(".pdf") == -1) {
      appendCSStoHtml();
    }
  });

But that did not matter.

Any ideas?


Solution

  • it's me again.

    Not sure if there is something that resembles what I am looking for. Thus I made my own.

    I added a page parameter and check this in the code to see if it's true or false:

    <script type="text/javascript">
    
      $(document).ready(function () {
        var url_string = window.location.href;
        var url = new URL(url_string);
        var renderCss = url.searchParams.get("renderCss");
    
        if(renderCss == 'true') {
          appendCSStoHtml();
        }
      });
    
      function appendCSStoHtml() {
        $("body").css({"background-color":" #F0F8FF"});
    
        $("#previewHtml").css({
          "margin-left":"15%",
          "margin-right":"15%",
          "margin-top":"15px",
          "max-width":"1024px"});
    
        $("#previewHtml > h2").css({"margin-left":" 15px"});
      }
    
    </script>