Can JavaScript change the value of @page CSS?
One simple way is to create a separate style for @page and change it:
var cssPagedMedia = (function () {
var style = document.createElement('style');
document.head.appendChild(style);
return function (rule) {
style.innerHTML = rule;
};
}());
cssPagedMedia.size = function (size) {
cssPagedMedia('@page {size: ' + size + '}');
};
cssPagedMedia.size('landscape');
@jasssonpet saved my butt with his answer. That being said, I changed it to be a little simpler (in my opinion).
** Not quite sure why it was done the way it was, but please educate me if you know. If it's just preference, then I'm sharing my code sample because someone else's preferences might align better with mine.
// just create the style tag and set the page size
function setPageSize(cssPageSize) {
const style = document.createElement('style');
style.innerHTML = `@page {size: ${cssPageSize}}`;
document.head.appendChild(style);
}
// how to use it
setPageSize('letter landscape');
EDIT: I logged in for the first time in a while and saw @jasssonpet's answer and it makes a lot more sense to me now. In case anyone else is confused, the main benefit of his approach is 2 things:
- He makes use of closures so that there is only 1 style tag added to the page that can then be referenced and changed.
- He extends upon cssPagedMedia so that any methods added are namespaced. This way, the global namespace isn't polluted.
Here is it in Class form (which I find easier to understand):
class SingletonStyle {
constructor() {
this.style = document.createElement("style");
document.head.appendChild(this.style);
}
apply(rule) {
this.style.innerHTML = rule;
}
size(size) {
this.apply("@page {size: " + size + "}");
}
}