mirror of
https://github.com/purplecabbage/phonegap-plugins.git
synced 2026-04-24 03:00:11 -04:00
43
iPhone/PrintPlugin/PrintPlugin.h
Normal file
43
iPhone/PrintPlugin/PrintPlugin.h
Normal file
@@ -0,0 +1,43 @@
|
||||
//
|
||||
// PrintPlugin.h
|
||||
// Print Plugin
|
||||
//
|
||||
// Created by Ian Tipton (github.com/itip) on 02/07/2011.
|
||||
// Copyright 2011 Ian Tipton. All rights reserved.
|
||||
// MIT licensed
|
||||
//
|
||||
|
||||
#import <Foundation/Foundation.h>
|
||||
|
||||
#ifdef PHONEGAP_FRAMEWORK
|
||||
#import <PhoneGap/PGPlugin.h>
|
||||
#else
|
||||
#import "PGPlugin.h"
|
||||
#endif
|
||||
|
||||
|
||||
@interface PrintPlugin : PGPlugin {
|
||||
NSString* successCallback;
|
||||
NSString* failCallback;
|
||||
NSString* printHTML;
|
||||
|
||||
//Options
|
||||
NSInteger dialogLeftPos;
|
||||
NSInteger dialogTopPos;
|
||||
}
|
||||
|
||||
@property (nonatomic, copy) NSString* successCallback;
|
||||
@property (nonatomic, copy) NSString* failCallback;
|
||||
@property (nonatomic, copy) NSString* printHTML;
|
||||
|
||||
//Print Settings
|
||||
@property NSInteger dialogLeftPos;
|
||||
@property NSInteger dialogTopPos;
|
||||
|
||||
//Print HTML
|
||||
- (void) print:(NSMutableArray*)arguments withDict:(NSMutableDictionary*)options;
|
||||
|
||||
//Find out whether printing is supported on this platform.
|
||||
- (void) isPrintingAvailable:(NSMutableArray*)arguments withDict:(NSMutableDictionary*)options;
|
||||
|
||||
@end
|
||||
63
iPhone/PrintPlugin/PrintPlugin.js
Normal file
63
iPhone/PrintPlugin/PrintPlugin.js
Normal file
@@ -0,0 +1,63 @@
|
||||
/**
|
||||
* Printer Plugin
|
||||
* Copyright (c) 2011 Ian Tipton (github.com/itip)
|
||||
* MIT licensed
|
||||
*/
|
||||
|
||||
var PrintPlugin = function() {
|
||||
|
||||
}
|
||||
|
||||
/*
|
||||
print - html string or DOM node (if latter, innerHTML is used to get the contents). REQUIRED.
|
||||
success - callback function called if print successful. {success: true}
|
||||
fail - callback function called if print unsuccessful. If print fails, {error: reason}. If printing not available: {available: false}
|
||||
options - {dialogOffset:{left: 0, right: 0}}. Position of popup dialog (iPad only).
|
||||
*/
|
||||
PrintPlugin.prototype.print = function(printHTML, success, fail, options) {
|
||||
if (typeof printHTML != 'string'){
|
||||
console.log("Print function requires an HTML string. Not an object");
|
||||
return;
|
||||
}
|
||||
|
||||
|
||||
//var printHTML = "";
|
||||
|
||||
var dialogLeftPos = 0;
|
||||
var dialogTopPos = 0;
|
||||
|
||||
|
||||
if (options){
|
||||
if (options.dialogOffset){
|
||||
if (options.dialogOffset.left){
|
||||
dialogLeftPos = options.dialogOffset.left;
|
||||
if (isNaN(dialogLeftPos)){
|
||||
dialogLeftPos = 0;
|
||||
}
|
||||
}
|
||||
if (options.dialogOffset.top){
|
||||
dialogTopPos = options.dialogOffset.top;
|
||||
if (isNaN(dialogTopPos)){
|
||||
dialogTopPos = 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
return PhoneGap.exec("PrintPlugin.print", printHTML, GetFunctionName(success), GetFunctionName(fail), dialogLeftPos, dialogTopPos);
|
||||
};
|
||||
|
||||
/*
|
||||
* Callback function returns {available: true/false}
|
||||
*/
|
||||
PrintPlugin.prototype.isPrintingAvailable = function(result) {
|
||||
return PhoneGap.exec("PrintPlugin.isPrintingAvailable", GetFunctionName(result));
|
||||
};
|
||||
|
||||
PhoneGap.addConstructor(function() {
|
||||
if(!window.plugins){
|
||||
window.plugins = {};
|
||||
}
|
||||
window.plugins.printPlugin = new PrintPlugin();
|
||||
});
|
||||
157
iPhone/PrintPlugin/PrintPlugin.m
Normal file
157
iPhone/PrintPlugin/PrintPlugin.m
Normal file
@@ -0,0 +1,157 @@
|
||||
//
|
||||
// PrintPlugin.m
|
||||
// Print Plugin
|
||||
//
|
||||
// Created by Ian Tipton (github.com/itip) on 02/07/2011.
|
||||
// Copyright 2011 Ian Tipton. All rights reserved.
|
||||
// MIT licensed
|
||||
//
|
||||
|
||||
#import "PrintPlugin.h"
|
||||
|
||||
@interface PrintPlugin (Private)
|
||||
-(void) doPrint;
|
||||
-(void) callbackWithFuntion:(NSString *)function withData:(NSString *)value;
|
||||
- (BOOL) isPrintServiceAvailable;
|
||||
@end
|
||||
|
||||
@implementation PrintPlugin
|
||||
|
||||
@synthesize successCallback, failCallback, printHTML, dialogTopPos, dialogLeftPos;
|
||||
|
||||
/*
|
||||
Is printing available. Callback returns true/false if printing is available/unavailable.
|
||||
*/
|
||||
- (void) isPrintingAvailable:(NSMutableArray*)arguments withDict:(NSMutableDictionary*)options{
|
||||
NSUInteger argc = [arguments count];
|
||||
|
||||
if (argc < 1) {
|
||||
return;
|
||||
}
|
||||
|
||||
|
||||
NSString *callBackFunction = [arguments objectAtIndex:0];
|
||||
[self callbackWithFuntion:callBackFunction withData:
|
||||
[NSString stringWithFormat:@"{available: %@}", ([self isPrintServiceAvailable] ? @"true" : @"false")]];
|
||||
|
||||
}
|
||||
|
||||
- (void) print:(NSMutableArray*)arguments withDict:(NSMutableDictionary*)options{
|
||||
NSUInteger argc = [arguments count];
|
||||
|
||||
if (argc < 1) {
|
||||
return;
|
||||
}
|
||||
self.printHTML = [arguments objectAtIndex:0];
|
||||
|
||||
if (argc >= 2){
|
||||
self.successCallback = [arguments objectAtIndex:1];
|
||||
}
|
||||
|
||||
if (argc >= 3){
|
||||
self.failCallback = [arguments objectAtIndex:2];
|
||||
}
|
||||
|
||||
if (argc >= 4){
|
||||
self.dialogLeftPos = [[arguments objectAtIndex:3] intValue];
|
||||
}
|
||||
|
||||
if (argc >= 5){
|
||||
self.dialogTopPos = [[arguments objectAtIndex:4] intValue];
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
[self doPrint];
|
||||
|
||||
}
|
||||
|
||||
- (void) doPrint{
|
||||
if (![self isPrintServiceAvailable]){
|
||||
[self callbackWithFuntion:self.failCallback withData: @"{success: false, available: false}"];
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
UIPrintInteractionController *controller = [UIPrintInteractionController sharedPrintController];
|
||||
|
||||
if (!controller){
|
||||
return;
|
||||
}
|
||||
|
||||
if ([UIPrintInteractionController isPrintingAvailable]){
|
||||
//Set the priner settings
|
||||
UIPrintInfo *printInfo = [UIPrintInfo printInfo];
|
||||
printInfo.outputType = UIPrintInfoOutputGeneral;
|
||||
controller.printInfo = printInfo;
|
||||
controller.showsPageRange = YES;
|
||||
|
||||
|
||||
//Set the base URL to be the www directory.
|
||||
NSString *dbFilePath = [[NSBundle mainBundle] pathForResource:@"www" ofType:nil ];
|
||||
NSURL *baseURL = [NSURL fileURLWithPath:dbFilePath];
|
||||
|
||||
//Load page into a webview and use its formatter to print the page
|
||||
UIWebView *webViewPrint = [[UIWebView alloc] init];
|
||||
[webViewPrint loadHTMLString:printHTML baseURL:baseURL];
|
||||
|
||||
//Get formatter for web (note: margin not required - done in web page)
|
||||
UIViewPrintFormatter *viewFormatter = [webViewPrint viewPrintFormatter];
|
||||
controller.printFormatter = viewFormatter;
|
||||
controller.showsPageRange = YES;
|
||||
|
||||
|
||||
void (^completionHandler)(UIPrintInteractionController *, BOOL, NSError *) =
|
||||
^(UIPrintInteractionController *printController, BOOL completed, NSError *error) {
|
||||
if (!completed || error) {
|
||||
[self callbackWithFuntion:self.failCallback withData:
|
||||
[NSString stringWithFormat:@"{success: false, available: true, error: \"%@\"}", error.localizedDescription]];
|
||||
|
||||
[webViewPrint release];
|
||||
|
||||
}
|
||||
else{
|
||||
[self callbackWithFuntion:self.successCallback withData: @"{success: true, available: true}"];
|
||||
|
||||
[webViewPrint release];
|
||||
}
|
||||
};
|
||||
|
||||
/*
|
||||
If iPad, and if button offsets passed, then show dilalog originating from offset
|
||||
*/
|
||||
if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad &&
|
||||
dialogTopPos != 0 && dialogLeftPos != 0) {
|
||||
[controller presentFromRect:CGRectMake(self.dialogLeftPos, self.dialogTopPos, 0, 0) inView:self.webView animated:YES completionHandler:completionHandler];
|
||||
} else {
|
||||
[controller presentAnimated:YES completionHandler:completionHandler];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
-(BOOL) isPrintServiceAvailable{
|
||||
|
||||
Class myClass = NSClassFromString(@"UIPrintInteractionController");
|
||||
if (myClass) {
|
||||
UIPrintInteractionController *controller = [UIPrintInteractionController sharedPrintController];
|
||||
return (controller != nil) && [UIPrintInteractionController isPrintingAvailable];
|
||||
}
|
||||
|
||||
|
||||
return NO;
|
||||
}
|
||||
|
||||
#pragma mark -
|
||||
#pragma mark Return messages
|
||||
|
||||
-(void) callbackWithFuntion:(NSString *)function withData:(NSString *)value{
|
||||
if (!function || [@"" isEqualToString:function]){
|
||||
return;
|
||||
}
|
||||
|
||||
NSString* jsCallBack = [NSString stringWithFormat:@"%@(%@);", function, value];
|
||||
[self writeJavascript: jsCallBack];
|
||||
}
|
||||
|
||||
@end
|
||||
130
iPhone/PrintPlugin/READEME.md
Normal file
130
iPhone/PrintPlugin/READEME.md
Normal file
@@ -0,0 +1,130 @@
|
||||
# PhoneGap Print-Plugin #
|
||||
by Ian Tipton (github.com/itip).
|
||||
|
||||
Print from iOS devices to AirPrint compatible printers.
|
||||
|
||||
|
||||
## Adding the Plugin to your project ##
|
||||
|
||||
Using this plugin requires [iPhone PhoneGap](http://github.com/phonegap/phonegap-iphone).
|
||||
|
||||
1. Make sure your PhoneGap Xcode project has been [updated for the iOS 4 SDK](http://wiki.phonegap.com/Upgrade-your-PhoneGap-Xcode-Template-for-iOS-4), and you are using PhoneGap version 1 or higher.
|
||||
2. Add the .h and .m files to your Plugins folder in your project
|
||||
3. Add the .js files to your "www" folder on disk, and add reference(s) to the .js files as <link> tags in your html file(s)
|
||||
4. Update the PhoneGap.plist file: Find PhoneGap.plist in your project, expand the "Plugins" section, click on "+" on the last line to add a new line. Add a new value with a key of 'printPlugin' and a value of 'PrintPlugin'
|
||||
5. Although printing is only supported on iOS 4.2+, if your app can be installed on earlier versions of iOS then see the 'Supporting devices running below iOS < 4.2' below.
|
||||
6. See the sample index.html file for an example use of the plugin.
|
||||
|
||||
## RELEASE NOTES ##
|
||||
|
||||
### 20110813 ###
|
||||
* Initial release
|
||||
* Allows the printing of an HTML string to AirPrint compatible printers.
|
||||
|
||||
|
||||
## Using the plugin ##
|
||||
|
||||
The plugin creates the object window.plugins.pgPrint with two methods:
|
||||
|
||||
### isPrintingAvailable ###
|
||||
|
||||
Printing is only available on devices capable of multi-tasking (iPhone 3GS, iPhone 4 etc.) running iOS 4.2 or later. You can use this function to hide print functionality from users who will be unable to use it. Function takes a callback function, passed to which is a JSON object which contains a boolean property called available.
|
||||
|
||||
```javascript
|
||||
/*
|
||||
Find out if printing is available. Use this for showing/hiding print buttons.
|
||||
*/
|
||||
window.plugins.printPlugin.isPrintingAvailable(
|
||||
function(result){
|
||||
alert(result.available ? "Printing is available" : "Printing NOT available");
|
||||
}
|
||||
);
|
||||
```
|
||||
|
||||
### print ###
|
||||
Function takes an html string and (optionally) a success callback, failure callback, and options.
|
||||
|
||||
1. An HTML string, e.g. <strong>hello<strong>
|
||||
2. Success callback - receives an object with two parameters:
|
||||
- success (always true)
|
||||
- available (always true)
|
||||
3. Failure callback - receives an object with properties
|
||||
- success (always false)
|
||||
- available (false if printing not available on this device)
|
||||
- error (error message returned by iOS in the event of an error)
|
||||
4. An object which contains printing options (see below).
|
||||
|
||||
```javascript
|
||||
//Get HTML string
|
||||
var html = document.getElementById("printHTML").innerHTML;
|
||||
|
||||
/*
|
||||
Pass an HTML and - optionally - success function, error function.
|
||||
*/
|
||||
window.plugins.printPlugin.print(
|
||||
html,
|
||||
function(result) {
|
||||
alert("Printing successful");
|
||||
},
|
||||
function(result) {
|
||||
if (!result.available){
|
||||
alert("Printing is not available");
|
||||
}
|
||||
else{
|
||||
//Localised error description
|
||||
alert(result.error);
|
||||
}
|
||||
}
|
||||
/*
|
||||
Add the following on an iPad to position the dialog
|
||||
,
|
||||
{dialogOffset: {left: 500, top: 900}}
|
||||
*/
|
||||
);
|
||||
```
|
||||
|
||||
## LICENSE ##
|
||||
|
||||
### Supporting devices running below iOS < 4.2 ###
|
||||
In order to compile this for versions of iOS earlier than 4.2 (when printing was introduced) then you will need to add -weak_framework UIKit to the project settings under "Other Linker Flags". See the Stack Overflow article for more information: http://stackoverflow.com/questions/4297723/ios-add-printing-but-keep-compatibility-with-ios-3.
|
||||
|
||||
### Testing in the iOS Simulator ###
|
||||
There's no need to waste lots of paper when testing - if you're using the iOS simulator, select File->Open Printer Simulator to open some dummy printers (print outs will appear as PDF files).
|
||||
|
||||
### Adding Page Breaks to Printouts ###
|
||||
Use the 'page-break-before' property to specify a page break, e.g.
|
||||
|
||||
```javascript
|
||||
<p>
|
||||
First page.
|
||||
</p>
|
||||
|
||||
<p style="page-break-before: always">
|
||||
Second page.
|
||||
</p>
|
||||
```
|
||||
|
||||
See W3Schools for more more information: http://www.w3schools.com/cssref/pr_print_pagebb.asp
|
||||
|
||||
Note: you will need to add an extra top margin to new pages.
|
||||
|
||||
|
||||
### Printing on Real Printers ###
|
||||
Printing is only supported on AirPrint-enabled printers or with the use of third-party software on your computer. The following pages contain more information:
|
||||
- AirPrint-enabled printers: http://www.apple.com/ipad/features/airprint.html
|
||||
- Enabling AirPrint on your computer: http://reviews.cnet.com/8301-19512_7-20023976-233.html, or http://www.ecamm.com/mac/printopia/
|
||||
|
||||
|
||||
## LICENSE ##
|
||||
|
||||
The MIT License
|
||||
|
||||
Copyright (c) 2011 Ian Tipton
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
||||
|
||||
|
||||
117
iPhone/PrintPlugin/index.html
Normal file
117
iPhone/PrintPlugin/index.html
Normal file
@@ -0,0 +1,117 @@
|
||||
<!DOCTYPE html>
|
||||
<html>
|
||||
<head>
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no;" />
|
||||
|
||||
<meta http-equiv="Content-type" content="text/html; charset=utf-8">
|
||||
|
||||
<!-- iPad/iPhone specific css below, add after your main css >
|
||||
<link rel="stylesheet" media="only screen and (max-device-width: 1024px)" href="ipad.css" type="text/css" />
|
||||
<link rel="stylesheet" media="only screen and (max-device-width: 480px)" href="iphone.css" type="text/css" />
|
||||
-->
|
||||
<!-- If your application is targeting iOS BEFORE 4.0 you MUST put json2.js from http://www.JSON.org/json2.js into your www directory and include it here -->
|
||||
<script type="text/javascript" charset="utf-8" src="phonegap-1.0.0.js"></script>
|
||||
<script type="text/javascript" charset="utf-8" src="PrintPlugin.js"></script>
|
||||
|
||||
<script type="text/javascript" charset="utf-8">
|
||||
|
||||
function printIt(){
|
||||
|
||||
//Get HTML string
|
||||
var html = document.getElementById("printHTML").innerHTML;
|
||||
|
||||
/*
|
||||
Pass a DOM node (or HTML string) and - optionally - success function, error function, position of print dialog (iPad only).
|
||||
*/
|
||||
window.plugins.printPlugin.print(html,
|
||||
function(result) {
|
||||
alert("Printing successful");
|
||||
},
|
||||
function(result) {
|
||||
if (!result.available){
|
||||
alert("Printing is not available");
|
||||
}
|
||||
else{
|
||||
//Localised error description
|
||||
alert(result.error);
|
||||
}
|
||||
}
|
||||
/*
|
||||
Add the following on an iPad to position the dialog
|
||||
,
|
||||
{dialogOffset: {left: 500, top: 900}}
|
||||
*/
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
// If you want to prevent dragging, uncomment this section
|
||||
/*
|
||||
function preventBehavior(e)
|
||||
{
|
||||
e.preventDefault();
|
||||
};
|
||||
document.addEventListener("touchmove", preventBehavior, false);
|
||||
*/
|
||||
|
||||
/* If you are supporting your own protocol, the var invokeString will contain any arguments to the app launch.
|
||||
see http://iphonedevelopertips.com/cocoa/launching-your-own-application-via-a-custom-url-scheme.html
|
||||
for more details -jm */
|
||||
/*
|
||||
function handleOpenURL(url)
|
||||
{
|
||||
// TODO: do something with the url passed in.
|
||||
}
|
||||
*/
|
||||
|
||||
function onBodyLoad()
|
||||
{
|
||||
document.addEventListener("deviceready",onDeviceReady,false);
|
||||
}
|
||||
|
||||
/* When this function is called, PhoneGap has been initialized and is ready to roll */
|
||||
/* If you are supporting your own protocol, the var invokeString will contain any arguments to the app launch.
|
||||
see http://iphonedevelopertips.com/cocoa/launching-your-own-application-via-a-custom-url-scheme.html
|
||||
for more details -jm */
|
||||
function onDeviceReady()
|
||||
{
|
||||
// do your thing!
|
||||
//navigator.notification.alert("PhoneGap is working")
|
||||
/*
|
||||
Find out if printing is available. Use this for showing/hiding print buttons.
|
||||
*/
|
||||
window.plugins.printPlugin.isPrintingAvailable(
|
||||
function(result){
|
||||
alert(result.available ? "Printing is available" : "Printing NOT available");
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
</script>
|
||||
</head>
|
||||
<body onload="onBodyLoad()">
|
||||
<h1>Printing</h1>
|
||||
|
||||
<button onclick="printIt()">Print the HTML below</button>
|
||||
|
||||
<br /><br /><br />
|
||||
|
||||
<div id="printHTML">
|
||||
|
||||
<div style="color: red;">
|
||||
<p>Either the well was very deep, or she fell very slowly, for she had plenty of time as she went down to look about her and to wonder what was going to happen next. First, she tried to look down and make out what she was coming to, but it was too dark to see anything; then she looked at the sides of the well, and noticed that they were filled with cupboards and book-shelves; here and there she saw maps and pictures hung upon pegs. She took down a jar from one of the shelves as she passed; it was labelled 'ORANGE MARMALADE', but to her great disappointment it was empty: she did not like to drop the jar for fear of killing somebody, so managed to put it into one of the cupboards as she fell past it.</p>
|
||||
</div>
|
||||
|
||||
<div style="color: green; page-break-before:always;">
|
||||
<p>In the Propontis, as far as I can learn, none of that peculiar substance called BRIT is to be found, the aliment of the right whale. But I have every reason to believe that the food of the sperm whale—squid or cuttle-fish—lurks at the bottom of that sea, because large creatures, but by no means the largest of that sort, have been found at its surface. If, then, you properly put these statements together, and reason upon them a bit, you will clearly perceive that, according to all human reasoning, Procopius's sea-monster, that for half a century stove the ships of a Roman Emperor, must in all probability have been a sperm whale.</p>
|
||||
</div>
|
||||
|
||||
|
||||
<div style="color: blue; page-break-before:always;">
|
||||
<p>They were not their families, nor their wives, nor their servants; the relationship was peculiar, and so unlike anything known to us that it is most difficult to describe. All property among the green Martians is owned in common by the community, except the personal weapons, ornaments and sleeping silks and furs of the individuals. These alone can one claim undisputed right to, nor may he accumulate more of these than are required for his actual needs. The surplus he holds merely as custodian, and it is passed on to the younger members of the community as necessity demands.</p>
|
||||
|
||||
</div>
|
||||
|
||||
</div>
|
||||
</body>
|
||||
</html>
|
||||
Reference in New Issue
Block a user