What CSS should I write in html template to generate a pdf of a particular height & width - css

I am generating a PDF using nodejs with pdf-creator-node and I got success.
My requirement is I need to generate a PDF with Height X Width = 926px X 1296px.
I don' know what css I should write to generate this dimension pdf.
right now if I set div or body height and widht with above mentioned dimension I am getting 3 pages
this is what I tried
#page {
width: 1296px;
height: 926px;
}
<div
class="parent-div"
style="
width: 1296px;
height: 926px;
background-color: #faf0e6;
border: 1px solid red;
"
></div>

jsPDF is able to use plugins. In order to enable it to print HTML, you have to include certain plugins and therefore have to do the following:
Go to https://github.com/MrRio/jsPDF and download the latest
Version.
Include the following Scripts in your project:
jspdf.js
jspdf.plugin.from_html.js
jspdf.plugin.split_text_to_size.js
jspdf.plugin.standard_fonts_metrics.js
If you want to ignore certain elements, you have to mark them with an ID, which you can then ignore in a special element handler of jsPDF. Therefore your HTML should look like this:
<!DOCTYPE html>
<html>
<body>
<p id="ignorePDF">don't print this to pdf</p>
<div>
<p><font size="3" color="red">print this to pdf</font></p>
</div>
</body>
</html>
Then you use the following JavaScript code to open the created PDF in a PopUp:
var doc = new jsPDF();
var elementHandler = {
#ignorePDF': function (element, renderer) {
return true;
}
};
var source = window.document.getElementsByTagName("body")[0];
doc.fromHTML(
source,
15,
15,
{
'width': 180,'elementHandlers': elementHandler
});
doc.output("dataurlnewwindow");
**For me this created a nice and tidy PDF that only included the line 'print this to pdf'.
Please note that the special element handlers only deal with IDs in the current version, which is also stated in a GitHub Issue. It states:**
Because the matching is done against every element in the node tree, my desire was to make it as fast as possible. In that case, it meant "Only element IDs are matched" The element IDs are still done in jQuery style "#id", but it does not mean that all jQuery selectors are supported.
Therefore replacing '#ignorePDF' with class selectors like '.ignorePDF' did not work for me. Instead you will have to add the same handler for each and every element, which you want to ignore like:
var elementHandler = {
#ignoreElement': function (element, renderer) {
return true;
},
#anotherIdToBeIgnored': function (element, renderer) {
return true;
}
};
From the examples it is also stated that it is possible to select tags like 'a' or 'li'. That might be a little bit too unrestrictive for the most use cases though:
We support special element handlers. Register them with a jQuery-style ID selector for either ID or node name. ("#iAmID", "div", "span" etc.) There is no support for any other type of selectors (class, of the compound) at this time.
One very important thing to add is that you lose all your style information (CSS). Luckily jsPDF is able to nicely format h1, h2, h3, etc., which was enough for my purposes. Additionally, it will only print text within text nodes, which means that it will not print the values of textareas and the like. Example:
<body>
<ul>
<!-- This is printed as the element contains a textnode -->
<li>Print me!</li>
</ul>
<div>
<!-- This is not printed because jsPDF doesn't deal with the value attribute -->
<input type="textarea" value="Please print me, too!">
</div>
</body>

Related

How to get list of custom CSS properties

I'm looking into custom CSS properties and have come up with the code below.
If I put the CSS inline using a STYLE attribute on the canvas tag (like this: style="--rgLinewidth: 3" ) then I can get the custom CSS values using the script shown below.
But using a tag, as below, then it doesn't show the custom CSS properties.
Is it possible to? And if so how?
<html>
<head>
<style>
canvas#cvs {
--rgLinewidth: 3;
background-color: red;
}
</style>
</head>
<body>
<canvas id="cvs" width="600" height="250">[No canvas support]</canvas>
<script>
canvas = document.getElementById("cvs");
styles = window.getComputedStyle(canvas);
alert(styles.getPropertyValue('background-color'));
alert(styles.getPropertyValue('--rgLinewidth'));
for (var i=0; i<styles.length; i++) {
if (canvas.style[i].indexOf('--rg') === 0) {
var value = styles.getPropertyValue(canvas.style[i]);
alert([canvas.style[i], value]);
}
}
</script>
</body>
</html>
It does not work because you query for computed style and then attempt to retrieve values of corresponding properties from the inline style, where they do not exist -- your canvas does not define an inline style. You need to query the values through the same styles object where you find the properties.
Consider the following function which when passed an element, will search through its computed style and return the value of the first CSS variable whose name starts with --rg:
function find_first_rg_value(el) {
var styles = getComputedStyle(el);
for (var i = 0; i < styles.length; i++) {
if (styles[i].startsWith('--rg')) {
return styles.getPropertyValue(styles[i]);
}
}
}
(Use like find_first_rg_value(canvas))
The difference between my approach and yours is, as I said, that you attempt to fetch the value from canvas.style[i], but canvas.style is effectively empty. Use styles instead.
Computed style (getComputedStyle), as the name implies, contains "summary" style computed per CSS cascading, inheriting, and so on, with inline style, if any, applied on top (overriding priority). Assigning inline style therefore affects the computed style, but querying inline style only gives you inline style you assigned, no more.
This means that in most cases like yours one would want to use getComputedStyle. Additionally, since CSS variables cannot be queried using style.fontName syntax, you need to use getPropertyValue function for these (all dashes intact in the passed property name), regardless if you are dealing with an inline or computed style object.

apply css class to all instances

Im trying to style some autogenerated html. I built a system that allowed me to overlay bootstrap on this autogen stuff and now I want to do some tweaking of whats there.
the autogen produces stuff like this
<dl>...</dl>
Now I want to apply bootstraps dl-horizontal class to that generated tag. Since its generated, I can't simply class it, I can't ID it, nothing. It has to be purely CSS selectors, which is something I know very little about.
What would a CSS tag that does this look like?
you can use jQuery to add a class to your <dl> tag like this:
$( document ).ready(function() {
$("dl").addClass("dl-horizontal");
});
$( document ).ready(function() {
$("dl").addClass("dl-horizontal");
});
.dl-horizontal {
color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<dl>
<dt>Coffee</dt>
<dd>Black hot drink</dd>
<dt>Milk</dt>
<dd>White cold drink</dd>
</dl>
jsFiddle Demo.
There is no option in css to add a class. But you can use children selectors to format if all your elements are the children of the same parent.
For example if your elements are a children of the parent body then:
body > dl
{
color : red;
}
The above code will change the text - color of all the elements that are the children of

How do I conditionally apply CSS styles in AngularJS?

Q1. Suppose I want to alter the look of each "item" that a user marks for deletion before the main "delete" button is pressed. (This immediate visual feedback should eliminate the need for the proverbial "are you sure?" dialog box.) The user will check checkboxes to indicate which items should be deleted. If a checkbox is unchecked, that item should revert back to its normal look.
What's the best way to apply or remove the CSS styling?
Q2. Suppose I want to allow each user to personalize how my site is presented. E.g., select from a fixed set of font sizes, allow user-definable foreground and background colors, etc.
What's the best way to apply the CSS styling the user selects/inputs?
Angular provides a number of built-in directives for manipulating CSS styling conditionally/dynamically:
ng-class - use when the set of CSS styles is static/known ahead of time
ng-style - use when you can't define a CSS class because the style values may change dynamically. Think programmable control of the style values.
ng-show and ng-hide - use if you only need to show or hide something (modifies CSS)
ng-if - new in version 1.1.5, use instead of the more verbose ng-switch if you only need to check for a single condition (modifies DOM)
ng-switch - use instead of using several mutually exclusive ng-shows (modifies DOM)
ng-disabled and ng-readonly - use to restrict form element behavior
ng-animate - new in version 1.1.4, use to add CSS3 transitions/animations
The normal "Angular way" involves tying a model/scope property to a UI element that will accept user input/manipulation (i.e., use ng-model), and then associating that model property to one of the built-in directives mentioned above.
When the user changes the UI, Angular will automatically update the associated elements on the page.
Q1 sounds like a good case for ng-class -- the CSS styling can be captured in a class.
ng-class accepts an "expression" that must evaluate to one of the following:
a string of space-delimited class names
an array of class names
a map/object of class names to boolean values
Assuming your items are displayed using ng-repeat over some array model, and that when the checkbox for an item is checked you want to apply the pending-delete class:
<div ng-repeat="item in items" ng-class="{'pending-delete': item.checked}">
... HTML to display the item ...
<input type="checkbox" ng-model="item.checked">
</div>
Above, we used ng-class expression type #3 - a map/object of class names to boolean values.
Q2 sounds like a good case for ng-style -- the CSS styling is dynamic, so we can't define a class for this.
ng-style accepts an "expression" that must evaluate to:
an map/object of CSS style names to CSS values
For a contrived example, suppose the user can type in a color name into a texbox for the background color (a jQuery color picker would be much nicer):
<div class="main-body" ng-style="{color: myColor}">
...
<input type="text" ng-model="myColor" placeholder="enter a color name">
Fiddle for both of the above.
The fiddle also contains an example of ng-show and ng-hide. If a checkbox is checked, in addition to the background-color turning pink, some text is shown. If 'red' is entered in the textbox, a div becomes hidden.
I have found problems when applying classes inside table elements when I had one class already applied to the whole table (for example, a color applied to the odd rows <myClass tbody tr:nth-child(even) td>). It seems that when you inspect the element with Developer Tools, the element.style has no style assigned. So instead of using ng-class, I have tried using ng-style, and in this case, the new CSS attribute does appear inside element.style. This code works great for me:
<tr ng-repeat="element in collection">
[...amazing code...]
<td ng-style="myvar === 0 && {'background-color': 'red'} ||
myvar === 1 && {'background-color': 'green'} ||
myvar === 2 && {'background-color': 'yellow'}">{{ myvar }}</td>
[...more amazing code...]
</tr>
Myvar is what I am evaluating, and in each case I apply a style to each <td> depending on myvar value, that overwrites the current style applied by the CSS class for the whole table.
UPDATE
If you want to apply a class to the table for example, when visiting a page or in other cases, you can use this structure:
<li ng-class="{ active: isActive('/route_a') || isActive('/route_b')}">
Basically, what we need to activate a ng-class is the class to apply and a true or false statement. True applies the class and false doesn't. So here we have two checks of the route of the page and an OR between them, so if we are in /route_a OR we are in route_b, the active class will be applied.
This works just having a logic function on the right that returns true or false.
So in the first example, ng-style is conditioned by three statements. If all of them are false, no style is applied, but following our logic, at least one is going to be applied, so, the logic expression will check which variable comparison is true and because a non empty array is always true, that will left an array as return and with only one true, considering we are using OR for the whole response, the style remaining will be applied.
By the way, I forgot to give you the function isActive():
$rootScope.isActive = function(viewLocation) {
return viewLocation === $location.path();
};
NEW UPDATE
Here you have something I find really useful. When you need to apply a class depending on the value of a variable, for example, an icon depending on the contents of the div, you can use the following code (very useful in ng-repeat):
<i class="fa" ng-class="{ 'fa-github' : type === 0,
'fa-linkedin' : type === 1,
'fa-skype' : type === 2,
'fa-google' : type === 3 }"></i>
Icons from Font Awesome
This works well when ng-class can't be used (for example when styling SVG):
ng-attr-class="{{someBoolean && 'class-when-true' || 'class-when-false' }}"
(I think you need to be on latest unstable Angular to use ng-attr-, I'm currently on 1.1.4)
I have published an article on working with AngularJS+SVG. It talks about this issue and numerous others. http://www.codeproject.com/Articles/709340/Implementing-a-Flowchart-with-SVG-and-AngularJS
span class="circle circle-{{selectcss(document.Extension)}}">
and code
$scope.selectcss = function (data) {
if (data == '.pdf')
return 'circle circle-pdf';
else
return 'circle circle-small';
};
css
.circle-pdf {
width: 24px;
height: 24px;
font-size: 16px;
font-weight: 700;
padding-top: 3px;
-webkit-border-radius: 12px;
-moz-border-radius: 12px;
border-radius: 12px;
background-image: url(images/pdf_icon32.png);
}
This solution did the trick for me
<a ng-style="{true: {paddingLeft: '25px'}, false: {}}[deleteTriggered]">...</a>
You can use ternary expression. There are two ways to do this:
<div ng-style="myVariable > 100 ? {'color': 'red'} : {'color': 'blue'}"></div>
or...
<div ng-style="{'color': (myVariable > 100) ? 'red' : 'blue' }"></div>
Another option when you need a simple css style of one or two properties:
View:
<tr ng-repeat="element in collection">
[...amazing code...]
<td ng-style="{'background-color': getTrColor(element.myvar)}">
{{ element.myvar }}
</td>
[...more amazing code...]
</tr>
Controller:
$scope.getTrColor = function (colorIndex) {
switch(colorIndex){
case 0: return 'red';
case 1: return 'green';
default: return 'yellow';
}
};
See the following example
<!DOCTYPE html>
<html ng-app>
<head>
<title>Demo Changing CSS Classes Conditionally with Angular</title>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.min.js"></script>
<script src="res/js/controllers.js"></script>
<style>
.checkboxList {
border:1px solid #000;
background-color:#fff;
color:#000;
width:300px;
height: 100px;
overflow-y: scroll;
}
.uncheckedClass {
background-color:#eeeeee;
color:black;
}
.checkedClass {
background-color:#3ab44a;
color:white;
}
</style>
</head>
<body ng-controller="TeamListCtrl">
<b>Teams</b>
<div id="teamCheckboxList" class="checkboxList">
<div class="uncheckedClass" ng-repeat="team in teams" ng-class="{'checkedClass': team.isChecked, 'uncheckedClass': !team.isChecked}">
<label>
<input type="checkbox" ng-model="team.isChecked" />
<span>{{team.name}}</span>
</label>
</div>
</div>
</body>
</html>
As of AngularJS v1.2.0rc, ng-class and even ng-attr-class fail with SVG elements (They did work earlier, even with normal binding inside the class attribute)
Specifically, none of these work now:
ng-class="current==this_element?'active':' ' "
ng-attr-class="{{current==this_element?'active':' '}}"
class="class1 class2 .... {{current==this_element?'active':''}}"
As a workaround, I've to use
ng-attr-otherAttr="{{current==this_element?'active':''}}"
and then style using
[otherAttr='active'] {
... styles ...
}
One more (in the future) way to conditionally apply style is by conditionally creating scoped style
<style scoped type="text/css" ng-if="...">
</style>
But nowadays only FireFox supports scoped styles.
There is one more option that I recently discovered that some people may find useful because it allows you to change a CSS rule within a style element - thus avoiding the need for repeated use of an angular directive such as ng-style, ng-class, ng-show, ng-hide, ng-animate, and others.
This option makes use of a service with service variables which are set by a controller and watched by an attribute-directive I call "custom-style". This strategy could be used in many different ways, and I attempted to provide some general guidance with this fiddle.
var app = angular.module('myApp', ['ui.bootstrap']);
app.service('MainService', function(){
var vm = this;
});
app.controller('MainCtrl', function(MainService){
var vm = this;
vm.ms = MainService;
});
app.directive('customStyle', function(MainService){
return {
restrict : 'A',
link : function(scope, element, attr){
var style = angular.element('<style></style>');
element.append(style);
scope.$watch(function(){ return MainService.theme; },
function(){
var css = '';
angular.forEach(MainService.theme, function(selector, key){
angular.forEach(MainService.theme[key], function(val, k){
css += key + ' { '+k+' : '+val+'} ';
});
});
style.html(css);
}, true);
}
};
});
well i would suggest you to check condition in your controller with a function returning true or false .
<div class="week-wrap" ng-class="{today: getTodayForHighLight(todayDate, day.date)}">{{day.date}}</div>
and in your controller check the condition
$scope.getTodayForHighLight = function(today, date){
return (today == date);
}
One thing to watch is - if the CSS style has dashes - you must remove them. So if you want to set background-color, the correct way is:
ng-style="{backgroundColor:myColor}"
Here's how i conditionally applied gray text style on a disabled button
import { Component } from '#angular/core';
#Component({
selector: 'my-app',
styleUrls: [ './app.component.css' ],
template: `
<button
(click)='buttonClick1()'
[disabled] = "btnDisabled"
[ngStyle]="{'color': (btnDisabled)? 'gray': 'black'}">
{{btnText}}
</button>`
})
export class AppComponent {
name = 'Angular';
btnText = 'Click me';
btnDisabled = false;
buttonClick1() {
this.btnDisabled = true;
this.btnText = 'you clicked me';
setTimeout(() => {
this.btnText = 'click me again';
this.btnDisabled = false
}, 5000);
}
}
Here's a working example:
https://stackblitz.com/edit/example-conditional-disable-button?file=src%2Fapp%2Fapp.component.html

Attach an image to any word

I'd like to attach images to specific words but cannot find the right CSS selector to do so.
I have a portion of my site which displays data as it's pulled from a database, so adding classes or id's to certain words is not an option for me. I need the css to simply display a background image wherever that word (or in this case, name) is found on the page.
For example, in the following (which is pulled from a database):
<td class="data1"><font face="Verdana, Arial, Helvetica, sans-serif" size="1">Patrick</font></td>
I would like to add a background image where the name Patrick is found.
I tried variations of,
td[.table1 *='Parick'] {
background-image:url(../images/accept.png);
but that didn't get me anywhere. And since it's not in a <span> or <div> or even a link, I can't figure it out. If you have any ideas or a jQuery workaround, please let me know. Thanks!
If you can guarantee the names only appear as the only text nodes in elements, you can use a simple jQuery selector...
$(':contains("Patrick")').addClass('name');
jsFiddle.
If there may be surrounding whitespace and/or the search should be case insensitive, try...
$('*').filter(function() {
return $.trim($(this).text()).toLowerCase() == 'patrick';
}).addClass('name');
jsFiddle.
If you need to find the name anywhere in any text node and then you need to wrap it with an element, try...
$('*').contents().filter(function() {
return this.nodeType == 3;
}).each(function() {
var node = this;
this.data.replace(/\bPatrick\b/i, function(all, offset) {
var chunk = node.splitText(offset);
chunk.data = chunk.data.substr(all.length);
var span = $('<span />', {
'class': 'name',
text: all
});
$(node).after(span);
});
});​
jsFiddle.
I would recommend using the third example.

How can I customise the browser's output for print/print preview?

I'm trying to dynamically hide certain DIV's when a print (or print preview) occurs from the browser.
I can easily differentiate statically by having two style sheets, one for normal and one for print media:
But I need to go one step further and hide some elements dynamically when the print style sheet becomes active during a print based upon certain criteria
One way to easily solve it would be to handle a DOM event for handling print / printview, then I could just use jQuery to change the display:none on the classes that need to be hidden, but I can't find a DOM print event!!
Anyone know what the solution is?
Not all browsers allow you to capture the print event. I've seen this tackled by adding a 'print this page' link and then using that click event to accomplish what you need.
I don't think you need a print event. All you need to do is adjust your #media print styles based on your Javascript(?) criteria. When the user attempts to print the page, the #media print style will apply and your styles will be in effect:
<html>
<head>
<style id="styles" type="text/css">
#media print { .noprint { display:none; } }
</style>
<script type="text/javascript">
var x = Math.random();
if (x > .5) {
var style = document.createElement('style');
style.type = 'text/css';
style.innerHTML = '#media print { .maybe_noprint { display:none; } }';
document.getElementsByTagName('head')[0].appendChild(style);
}
</script>
</head>
<body>
<div class="noprint">This will never print.</div>
<span class="maybe_noprint">This may print depending on the value of x.</span>
</body>
</html>
If you are using server-side criteria to determine what prints, then just have server-side code spit out #media print to decorate the classes as necessary. Also, you may want to consider modifying an existing class that's already inside #media print, or building up the new CSS using something other than innerHTML, which I'll admit smells awful to me, but seems to work in Opera 9.6, Safari for Windows 3.1.2, IE 6 and Firefox 2.0.0.17 (I didn't test any other browsers).
Just tag those DIVs with a class that's hidden on the print stylesheet:
HTML
<div id='div19' class='noprint'>
...
</div>
print.css
.noprint {
display: none;
}
If you don't know in advance which elements you need to hide, you can use javascript to set the class for the given objects:
Javascript
document.getElementById('div19').className='noprint';
There's an onbeforeprint event in IE. It doesn't appear to be supported by other major browsers. (I tested Firefox 3.0.3 and Safari 3.1.2.)

Resources