1

I am generating PDFs from HTML documents. Styles must be applied using the style="" attribute (inline) currently.

I would like to populate the style attribute with rules being applied to elements by an external stylesheet.

I have explored the possibility outlined here: CSS style to inline style via JavaScript - however, this applied an excessive amount of browser default styles as you can see by inspecting the DIV in my example below.

Is there a way to apply only the styles I have defined in my stylesheet?

function applyStyles(el) {
  var styles = getComputedStyle(el);
  
  for(let key in styles) {
    let prop = key.replace(/\-([a-z])/g, v => v[1].toUpperCase());
    
    el.style[prop] = styles[key];
  }
}


applyStyles(document.getElementById('test-div'));
#test-div {
  padding: 1rem;
  border: 1px solid #CCC;
  border-radius: 3px;
  font-family: sans-serif;
  box-shadow: 1px 1px 6px rgba(0, 0, 0, 0.15);
}
<div id="test-div">I am the test DIV</div>  
James Allen
  • 969
  • 4
  • 16
  • 1
    You could always create an array (a whitelist), with a list of properties you want to leave, and then use it to filter out the unwanted properties. But I'm not sure how you could filter out the property values ​​together with the property names. It wouldn't be the best way, but it's always something you could try. – Shape Aug 26 '19 at 16:59
  • Great suggestion, I will pursue that unless someone offers a cleaner approach – James Allen Aug 26 '19 at 17:01
  • And also, I wouldn't use any complex regex, as I've noticed it sometimes reports wrong values when using `.test()` in older versions of Firefox. (As I was testing my code for browsers for Windows XP) – Shape Aug 26 '19 at 17:13
  • Updated w/ whitelist idea: https://codepen.io/JimmyJames88/pen/MWgpLOY – James Allen Aug 26 '19 at 17:13
  • @AleksanderCiecierski I'm worried enough to use indexOf() instead of includes() to check my whitelist -- but supporting XP era firefox browsers seems a tad excessive for my needs. Thanks for the suggestion! – James Allen Aug 26 '19 at 17:15
  • The global usage of Windows XP is about 2% (Of every Windows OS) but I've seen MANY people still using it. I would rather worry about Windows 7 getting out of date soon, as it stands for over 30% of all wundows usage. Outdated OS = no browser updates = opportunity for hackers. Still, XP support would always be good to have there. – Shape Aug 26 '19 at 17:22
  • Less than 2% of Windows machines are XP...a fraction of that when compared against all OS's. Usually when I see XP nowadays it's on a POS system in a retail store. I do my part by supporting down to IE11, but that's where my generosity expires. – James Allen Aug 26 '19 at 17:30

0 Answers0