Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Wait load css and manually run print when document is ready #172

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
40 changes: 40 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,8 @@ $('selector').printThis();
```

### Advanced Features

##### Provide options for print
```javascript
$('#kitty-one, #kitty-two, #kitty-three').printThis({
importCSS: false,
Expand All @@ -29,6 +31,27 @@ $('#kitty-one, #kitty-two, #kitty-three').printThis({
});
```

##### Manually start the print functionality
```javascript
$('#kitty-one, #kitty-two, #kitty-three').printThis({
importCSS: false,
loadCSS: "",
header: "<h1>Look at all of my kitties!</h1>"
}, function(doPrint, $doc) {
// handle image errors in the document to print
// ... or do what ever you want with the document already list for print
$doc.find('img').each(function(){
let img = new Image();
img.onerror = handleImageError;
img.src = $(this).attr('src');
});

// run the print
doPrint();
});
```


### Troubleshooting
[Check the printThis wiki for common issues and questions](https://github.com/jasonday/printThis/wiki)

Expand All @@ -43,6 +66,9 @@ Debug leaves the iframe visible on the page after `printThis` runs, allowing you
#### importCSS
Copy CSS `<link>` tags to the printThis iframe. On by default.

#### waitLoadCSS
Wait for all css was loaded before start print.

#### importStyle
Copy CSS `<style>` tags to the printThis iframe. Off by default.

Expand Down Expand Up @@ -126,6 +152,7 @@ This is called even if `debug: true`, which does not remove the iframe.
$("#mySelector").printThis({
debug: false, // show the iframe for debugging
importCSS: true, // import parent page css
waitLoadCSS: false, // wait for all css was loaded before start print
importStyle: false, // import style tags
printContainer: true, // print outer container/$.selector
loadCSS: "", // path to additional css file - use an array [] for multiple
Expand All @@ -147,6 +174,19 @@ $("#mySelector").printThis({
});
```

### Callback
`printThis` allow an optional function as second parameter.
This function will be executed once the document is ready to print.
The function receive two parameters `doPrint` and `$doc`.

#### doPrint
A function to run the print functionality manually.

#### $doc
The document ready to print.

If you pass a callback, you are responsible to run the `doPrint` function to start print.

## Please read
* "It's not working" without any details is not a valid issue and will be closed
* A url, or html file, is necessary to debug. Due to the complexities of printing and this plugin, an example is the best way to debug
Expand Down
116 changes: 86 additions & 30 deletions printThis.js
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
* $("#mySelector").printThis({
* debug: false, // show the iframe for debugging
* importCSS: true, // import parent page css
* waitLoadCSS: false, // wait for all css was loaded before start print
* importStyle: false, // import style tags
* printContainer: true, // grab outer container as well as the contents of the selector
* loadCSS: "path/to/my.css", // path to additional css file - use an array [] for multiple
Expand Down Expand Up @@ -87,9 +88,10 @@
}

var opt;
$.fn.printThis = function(options) {
$.fn.printThis = function(options, callback) {
opt = $.extend({}, $.fn.printThis.defaults, options);
var $element = this instanceof jQuery ? this : $(this);
var pendingStylesheets = [];

var strFrameName = "printThis-" + (new Date()).getTime();

Expand Down Expand Up @@ -150,6 +152,46 @@
$base = $('base'),
baseURL;

function addStyleSheet(href, media) {
// create a new stylesheet element
var $link = $('<link>', {
rel: 'stylesheet',
type: 'text/css'
});
if (media) {
$link.attr('media', media);
}

if (opt.waitLoadCSS) {
// include it in the list of pending stylesheets
pendingStylesheets.push($link);

// subscribe events to know when the stylesheet was loaded
$link.on('load', stylesheetResolved($link));
$link.on('error', stylesheetResolved($link));
}

// after events subscription we setup the href and include the link in the doc
$link.attr('href', href);
$head.append($link);
}

function stylesheetResolved($link) {
// return a callback
return function() {
// remove the $link element from the pending stylesheets
var index = pendingStylesheets.indexOf($link);
if (index != -1) {
pendingStylesheets.splice(index, 1);
}

// start the print functionality once all pending stylesheets was loaded
if (pendingStylesheets.length === 0) {
startPrint();
}
}
}

// add base tag to ensure elements use the parent domain
if (opt.base === true && $base.length > 0) {
// take the base tag from the original page
Expand All @@ -169,7 +211,7 @@
var href = $(this).attr("href");
if (href) {
var media = $(this).attr("media") || "all";
$head.append("<link type='text/css' rel='stylesheet' href='" + href + "' media='" + media + "'>");
addStyleSheet(href, media);
}
});

Expand All @@ -185,10 +227,10 @@
if (opt.loadCSS) {
if ($.isArray(opt.loadCSS)) {
jQuery.each(opt.loadCSS, function(index, value) {
$head.append("<link type='text/css' rel='stylesheet' href='" + this + "'>");
addStyleSheet(this);
});
} else {
$head.append("<link type='text/css' rel='stylesheet' href='" + opt.loadCSS + "'>");
addStyleSheet(opt.loadCSS);
}
}

Expand Down Expand Up @@ -274,37 +316,50 @@
}
attachOnBeforePrintEvent($iframe, opt.beforePrint);

setTimeout(function() {
if ($iframe.hasClass("MSIE")) {
// check if the iframe was created with the ugly hack
// and perform another ugly hack out of neccessity
window.frames["printIframe"].focus();
$head.append("<script> window.print(); </s" + "cript>");
} else {
// proper method
if (document.queryCommandSupported("print")) {
$iframe[0].contentWindow.document.execCommand("print", false, null);
} else {
$iframe[0].contentWindow.focus();
$iframe[0].contentWindow.print();
}
}

// remove iframe after print
if (!opt.debug) {
function startPrint() {
function print() {
setTimeout(function() {
$iframe.remove();

}, 1000);
if ($iframe.hasClass("MSIE")) {
// check if the iframe was created with the ugly hack
// and perform another ugly hack out of neccessity
window.frames["printIframe"].focus();
$head.append("<script> window.print(); </s" + "cript>");
} else {
// proper method
if (document.queryCommandSupported("print")) {
$iframe[0].contentWindow.document.execCommand("print", false, null);
} else {
$iframe[0].contentWindow.focus();
$iframe[0].contentWindow.print();
}
}

// remove iframe after print
if (!opt.debug) {
setTimeout(function() {
$iframe.remove();

}, 1000);
}

// after print callback
if (typeof opt.afterPrint === "function") {
opt.afterPrint();
}

}, opt.printDelay);
}

// after print callback
if (typeof opt.afterPrint === "function") {
opt.afterPrint();
if (callback) {
callback(print, $doc);
} else {
print();
}
}

}, opt.printDelay);

if (!opt.waitLoadCSS) {
startPrint();
}
}, 333);

};
Expand All @@ -313,6 +368,7 @@
$.fn.printThis.defaults = {
debug: false, // show the iframe for debugging
importCSS: true, // import parent page css
waitLoadCSS: false, // wait for all css was loaded before start print
importStyle: false, // import style tags
printContainer: true, // print outer container/$.selector
loadCSS: "", // path to additional css file - use an array [] for multiple
Expand Down