How to use savePDF method in Webdriverio

Best JavaScript code snippet using webdriverio-monorepo

Run Webdriverio automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

savepdf.js

Source: savepdf.js Github

copy
1console.log("savepdf")
2sue.apps.savepdf={
3	cons:{
4		boxmove:{}
5	},
6	defaultConf:{
7		footerCenter:"",
8		footerLeft:"&PT",
9		footerRight:"&D",
10		headerCenter:"",
11		headerLeft:"&T",
12		headerRight:"&U",
13		marginBottom:0.5,
14		marginLeft:0.5,
15		marginRight:0.5,
16		marginTop:0.5,
17		orientation:0,
18		paperHeight:11.0,
19		paperSizeUnit:0,
20		paperWidth:8.5,
21		scaling:1,
22		showBackgroundColors:false,
23		showBackgroundImages:false,
24		shrinkToFit:true
25	},
26	initUI:function(){
27		let appInfo={
28			appName:"savepdf",
29			headTitle:"savepdf",
30			headCloseBtn:true,
31			menu:[
32				{src:"/image/options.svg",title:"app_tip_opt",className:"menu_item menu_item_opt"},
33				{src:"/image/info.svg",title:"",className:"menu_item menu_item_help"}
34			]
35		}
36		sue.apps.init();
37		var dom=sue.apps.initBox(appInfo);
38			dom.id="su_apps_"+appInfo.appName;
39		sue.apps[appInfo.appName].dom=dom;
40		sue.apps.initPos(dom);
41
42		let theAppBox=sue.apps.domCreate("div",{setName:["className"],setValue:["savepdfbox"]});
43		dom.querySelector(".su_main").appendChild(theAppBox);
44
45		let _optBox=sue.apps.domCreate("div",{setName:["className"],setValue:["su_options"]}),
46			_optDes=sue.apps.domCreate("div",null,null,null,null,sue.apps.i18n("savepdf_resetDes")),
47			_optBtnBox=sue.apps.domCreate("div",{setName:["className"],setValue:["options_btnbox"]}),
48			_optBtn=sue.apps.domCreate("button",{setName:["className"],setValue:["options_btn_reset"]},null,null,null,sue.apps.i18n("btn_reset"));
49		_optBtnBox.appendChild(_optBtn);
50		_optBox.appendChild(_optDes);
51		_optBox.appendChild(_optBtnBox);
52		dom.appendChild(_optBox);
53
54		let _infoBox=sue.apps.domCreate("div",{setName:["className"],setValue:["su_options_help"]}),
55			_info=sue.apps.domCreate("div",null,null,null,null,sue.apps.i18n("savepdf_info"));
56		_infoBox.appendChild(_info);
57		dom.appendChild(_infoBox);
58
59		chrome.storage.local.get(function(items){
60			var data;
61			!items.localConfig?(items.localConfig={},items.localConfig.apps={}):null;
62			!items.localConfig.apps?items.localConfig.apps={}:null;
63			if(!items.localConfig.apps.savepdf){
64				items.localConfig.apps.savepdf=sue.apps.savepdf.defaultConf;
65				data=items.localConfig.apps.savepdf;
66				chrome.storage.local.set(items);
67			}else{
68				data=items.localConfig.apps.savepdf;
69			}
70			//sue.apps.savepdf.initValue(data);
71			sue.apps.savepdf.initOptions(data);
72			dom.addEventListener("click",sue.apps.savepdf.handleEvent,false);
73			sue.apps.initPos(dom);
74		})
75	},
76	initOptions:function(pdfConf){
77		let theAppBox=sue.apps.savepdf.dom.querySelector(".savepdfbox");
78		theAppBox.textContent="";
79
80		let _btnBox=sue.apps.domCreate("div",{setName:["className"],setValue:["btnbox"]}),
81			_btn=sue.apps.domCreate("button",{setName:["className"],setValue:["su_savepdf_btn"]},null,null,null,"Generate PDF");
82		_btnBox.appendChild(_btn);
83		theAppBox.appendChild(_btnBox);
84
85		let _spanOri=sue.apps.domCreate("span",{setName:["className"],setValue:["su_savepdf_span"]},null,null,null,sue.apps.i18n("savepdf_"+"orientation")),
86			_selectOri=sue.apps.domCreate("select",{setName:["className","name"],setValue:["pdfele","savepdf_orientation"]});
87		let _optionOri_0=sue.apps.domCreate("option",{setName:["value"],setValue:["0"]},null,null,null,sue.apps.i18n("savepdf_"+"portrait")),
88			_optionOri_1=sue.apps.domCreate("option",{setName:["value"],setValue:["1"]},null,null,null,sue.apps.i18n("savepdf_"+"landscape"))
89		_selectOri.appendChild(_optionOri_0);
90		_selectOri.appendChild(_optionOri_1);
91		_selectOri.selectedIndex=pdfConf.orientation;
92		theAppBox.appendChild(_spanOri);
93		theAppBox.appendChild(_selectOri);
94		theAppBox.appendChild(sue.apps.domCreate("br"));
95
96		let _spanPap=sue.apps.domCreate("span",{setName:["className"],setValue:["su_savepdf_span"]},null,null,null,sue.apps.i18n("savepdf_"+"paperSizeUnit")),
97			_selectPap=sue.apps.domCreate("select",{setName:["className","name"],setValue:["pdfele","savepdf_paperSizeUnit"]});
98		let _optionPap_0=sue.apps.domCreate("option",{setName:["value"],setValue:["0"]},null,null,null,sue.apps.i18n("savepdf_"+"inches")),
99			_optionPap_1=sue.apps.domCreate("option",{setName:["value"],setValue:["1"]},null,null,null,sue.apps.i18n("savepdf_"+"millimeters"))
100		_selectPap.appendChild(_optionPap_0);
101		_selectPap.appendChild(_optionPap_1);
102		_selectPap.selectedIndex=pdfConf.paperSizeUnit;
103		theAppBox.appendChild(_spanPap);
104		theAppBox.appendChild(_selectPap);
105		theAppBox.appendChild(sue.apps.domCreate("br"));
106
107		let _arrayCheck=["showBackgroundColors","showBackgroundImages","shrinkToFit"];
108		for(var i=0;i<_arrayCheck.length;i++){
109			var _check=sue.apps.domCreate("input",{setName:["className","id","type","checked"],setValue:["pdfele su_savepdf_text","savepdf_"+_arrayCheck[i],"checkbox",(pdfConf[_arrayCheck[i]]?" checked":"")]});
110			var	_label=sue.apps.domCreate("label",{setName:["className","for"],setValue:["su_savepdf_label","savepdf_"+_arrayCheck[i]]},null,null,null,sue.apps.i18n("savepdf_"+_arrayCheck[i]));
111			theAppBox.appendChild(_check);
112			theAppBox.appendChild(_label);
113			theAppBox.appendChild(sue.apps.domCreate("br"));
114		}
115
116		let _arrayText=["footerCenter","footerLeft","footerRight","headerCenter","headerLeft","headerRight"];
117		for(var i=0;i<_arrayText.length;i++){
118			var _spanText=sue.apps.domCreate("span",{setName:["className"],setValue:["su_savepdf_span"]},null,null,null,sue.apps.i18n("savepdf_"+_arrayText[i]));
119			var _text=sue.apps.domCreate("input",{setName:["className","id","type","placeholder","value"],setValue:["pdfele su_savepdf_text","savepdf_"+_arrayText[i],"text",sue.apps.i18n("place_string"),pdfConf[_arrayText[i]]]},null,null,{setName:["type"],setValue:["string"]});
120			theAppBox.appendChild(_spanText);
121			theAppBox.appendChild(_text);
122			theAppBox.appendChild(sue.apps.domCreate("br"));
123		}
124
125		let _arrayText_Num=["marginBottom","marginLeft","marginRight","marginTop","paperHeight","paperWidth","scaling"];
126		for(var i=0;i<_arrayText_Num.length;i++){
127			var _spanText=sue.apps.domCreate("span",{setName:["className"],setValue:["su_savepdf_span"]},null,null,null,sue.apps.i18n("savepdf_"+_arrayText_Num[i]));
128			var _text=sue.apps.domCreate("input",{setName:["className","id","type","placeholder","value"],setValue:["pdfele su_savepdf_text","savepdf_"+_arrayText_Num[i],"text",sue.apps.i18n("place_number"),pdfConf[_arrayText_Num[i]]/**/]},null,null,{setName:["type"],setValue:["number"]});
129			theAppBox.appendChild(_spanText);
130			theAppBox.appendChild(_text);
131			theAppBox.appendChild(sue.apps.domCreate("br"));
132		}
133	},
134	handleEvent:function(e){
135		switch(e.type){
136			case"click":
137				if(e.target.classList.contains("su_savepdf_btn")){
138					sue.apps.savepdf.pdf(e);
139				}else if(e.target.classList.contains("menu_item_help")){
140					sue.apps.savepdf.showHelp(e);
141				}else if(e.target.classList.contains("options_btn_reset")){
142					sue.apps.savepdf.reset(e);
143				}
144				break;
145		}
146	},
147	showHelp:function(e){
148		var domopt=sue.apps.getAPPboxEle(e).querySelector(".su_options_help");
149		var _opt=window.getComputedStyle(domopt).opacity==0?true:false;
150		if(_opt){
151			domopt.style.cssText+="opacity:.9;z-index:10;";
152		}else{
153			domopt.style.cssText+="opacity:0;z-index:-1;";
154		}
155	},
156	reset:function(e){
157		sue.apps.savepdf.initOptions(sue.apps.savepdf.defaultConf);
158		sue.apps.showOpt(e)
159	},
160	pdf:function(e){
161		let pdfData={},pdfDom=sue.apps.getAPPboxEle(e),i=0;
162		let	pdfDoms=pdfDom.querySelectorAll(".pdfele");
163		for(i=0;i<pdfDoms.length;i++){
164			if(pdfDoms[i].tagName.toLowerCase()=="select"){
165				pdfData[pdfDoms[i].name.substr(8)]=pdfDoms[i].selectedIndex//Number(pdfDoms[i].value);
166			}else if(pdfDoms[i].tagName.toLowerCase()=="input"&&pdfDoms[i].type=="checkbox"){
167				pdfData[pdfDoms[i].id.substr(8)]=pdfDoms[i].checked;
168			}else if(pdfDoms[i].tagName.toLowerCase()=="input"&&pdfDoms[i].type=="text"){
169				if(pdfDoms[i].dataset.type=="number"){
170					pdfData[pdfDoms[i].id.substr(8)]=Number(pdfDoms[i].value);
171				}else{
172					pdfData[pdfDoms[i].id.substr(8)]=pdfDoms[i].value;
173				}
174			}
175		}
176		chrome.storage.local.get(function(items){
177			items.localConfig.apps.savepdf={};
178			items.localConfig.apps.savepdf=pdfData;
179			chrome.storage.local.set(items);
180		})
181		sue.apps.boxClose(e);
182		chrome.runtime.sendMessage({type:"appsAction",app:"savepdf",action:"savePDF",value:pdfData});
183	},
184	randnum:function(e){
185		var domsavepdf=sue.apps.getAPPboxEle(e);
186		var printBox=domsavepdf.querySelector("#su_savepdf_print");
187		var randLength=parseInt(domsavepdf.querySelector("#num").value),
188			min=parseInt(domsavepdf.querySelector("#min").value),
189			max=parseInt(domsavepdf.querySelector("#max").value),
190			norepeat=domsavepdf.querySelector("#su_savepdf_norepeat").checked;
191			add=domsavepdf.querySelector("#su_savepdf_add").checked;
192		var nums=[],strs="",flag=false,strlen=0;
193		printBox.value="loading...";
194		if(isNaN(min)||isNaN(max)||isNaN(randLength)){
195			printBox.value="Error";
196			return;
197		}
198		if(max<min){
199			_max=max;_min=min;
200			max=Math.max(_min,_max);
201			min=Math.min(_min,_max);			
202		}
203		if((max-min+1)<randLength){
204			norepeat=false;
205		}
206		for(var i=0;i<randLength;i++){
207			var num=parseInt(Math.savepdf()*(max-min+1)+min-(min<0?1:0));
208			for(var ii=0;norepeat&&ii<nums.length;ii++){
209				if(num==nums[ii]){
210					flag=true;
211					return arguments.callee(e)
212					break;
213				}
214			}
215			nums.push(num);
216		}
217		for(var i=0;add&&i<nums.length;i++){
218			var thestr=nums[i].toString();
219			strlen=(thestr.length>strlen)?thestr.length:strlen;
220		}
221		for(var i=0;i<nums.length;i++){
222			var thestr=nums[i].toString();
223			var addlen=strlen-thestr.length;
224			for(var ii=0;add&&ii<addlen;ii++){
225				thestr="0"+thestr;
226			}
227			strs=strs+" "+thestr;
228		}
229		printBox.value=strs;
230
231		chrome.storage.local.get(function(items){
232			items.localConfig.apps.savepdf={
233				min:min,
234				max:max,
235				num:randLength,
236				norepeat:norepeat,
237				add:add
238			}
239			chrome.storage.local.set(items);
240		})
241	}
242}
243sue.apps.savepdf.initUI();
244
Full Screen

desktopreport_spec.js

Source: desktopreport_spec.js Github

copy
1'use strict';
2
3describe('desktopreport controller', function () {
4    
5    var $scope;
6    var $controller;
7    var $httpBackend;
8    var $location;
9    var $q;
10    var common;
11    var fsp = require('promise-fs');
12    var mockElectron = {
13        currentWindow: {
14            webContents: {
15                print: function() {},
16                printToPDF: function() {},
17                reload: function() {}
18            }
19        },
20        dialog: {
21            printPDF: function() {},
22            savePDF: function() {}
23        }
24    };
25    var mockDatacontext = {
26        load: function() { return $q.when(null);}
27    }
28    var mockThreatModelLocator = {
29        getModelLocation: function() {}
30    }
31    
32    beforeEach(function () {
33
34        angular.mock.module('app');
35        angular.mock.module(function ($provide) {
36            $provide.value('electron', mockElectron);
37            $provide.value('datacontext', mockDatacontext);
38            $provide.value('threatmodellocator', mockThreatModelLocator);
39        });
40        
41        angular.mock.inject(function ($rootScope, _$q_, _$controller_, _$location_, _$httpBackend_, _common_) {
42            $scope = $rootScope.$new();
43            $q = _$q_;
44            $controller = _$controller_;
45            $location = _$location_;
46            $httpBackend = _$httpBackend_;
47            common = _common_;
48            $httpBackend.expectGET().respond();
49        });
50    });
51    
52    describe('initialisation tests', function () {
53
54        beforeEach(function() {
55            $controller('desktopreport as vm', { $scope: $scope });
56            $scope.$apply();
57        });
58
59        it('should be defined', function () {
60            expect($scope.vm).toBeDefined();
61        });
62        
63        it('should have "Threat Model Report" for its title', function () {
64            expect($scope.vm.title).toEqual('Threat Model Report');
65        });
66
67    });
68
69    describe('viewmodel tests', function () {
70
71        it('should set the loaded flag', function () {
72            
73            $controller('desktopreport as vm', { $scope: $scope });
74            $scope.$apply();
75            $scope.vm.loaded = false;
76            $scope.vm.onLoaded();
77            expect($scope.vm.loaded).toEqual(true);
78
79        });
80
81        it('should load from the datacontext', function() {
82
83            var testModel = 'test model';
84            var testLocation = 'test location';
85            spyOn(mockDatacontext, 'load').and.returnValue($q.when(testModel));
86            spyOn(mockThreatModelLocator, 'getModelLocation').and.returnValue(testLocation);
87            $controller('desktopreport as vm', { $scope: $scope });
88            $scope.$apply();
89            expect(mockDatacontext.load.calls.argsFor(0)[0]).toEqual(testLocation);
90            expect($scope.vm.threatModel).toEqual(testModel);
91        });
92
93        it('should log an error', function() {
94
95            var testError = new Error('test error');
96            var testErrorMessage = 'message';
97            testError.data = { message: testErrorMessage };
98            var errorLogger = jasmine.createSpy('errorLogger');
99            var loggerSpy = spyOn(common.logger, 'getLogFn').and.returnValue(errorLogger);
100            $controller('desktopreport as vm', { $scope: $scope });
101            $scope.$apply();
102
103            $scope.vm.error = null;
104            loggerSpy.calls.reset();
105            $scope.vm.onError(testError);
106            expect($scope.vm.error).toEqual(testError);
107            expect(errorLogger).toHaveBeenCalled();
108            expect(errorLogger.calls.argsFor(1)).toEqual([testErrorMessage]);
109        });
110
111        describe('PDF tests', function() {
112
113            it('should log an error', function() {
114
115                var testError = new Error('test error');
116                var testErrorMessage = 'message';
117                testError.data = { message: testErrorMessage };
118                var errorLogger = jasmine.createSpy('errorLogger');
119                var loggerSpy = spyOn(common.logger, 'getLogFn').and.returnValue(errorLogger);
120
121                mockElectron.currentWindow.webContents.printToPDF = function(settings, callback) {
122                    callback(testError, null);
123                };
124
125                var done = jasmine.createSpy('done');
126                
127                $controller('desktopreport as vm', { $scope: $scope });
128                $scope.$apply();
129                loggerSpy.calls.reset();
130                $scope.vm.savePDF(done);
131
132                expect(done).toHaveBeenCalled();
133                expect($scope.vm.error).toEqual(testError);
134                expect(errorLogger).toHaveBeenCalled();
135                expect(errorLogger.calls.argsFor(1)).toEqual([testErrorMessage]);
136
137            });
138
139            it('should save the PDF file with default file name', function() {
140
141                var testData = 'data';
142                mockElectron.currentWindow.webContents.printToPDF = function(settings, callback) {
143                    callback(null, testData);
144                };
145                var file = 'test';
146                mockDatacontext.threatModelLocation = file + '.json';
147                var done = jasmine.createSpy('done');
148                mockElectron.dialog.savePDF = function(defaultPath, onSave, onCancel) {
149                    onSave();
150                }
151                spyOn(mockElectron.dialog, 'savePDF').and.callThrough();
152                spyOn(fsp, 'writeFile').and.returnValue($q.when(null));
153                $controller('desktopreport as vm', { $scope: $scope });
154                $scope.$apply();
155                $scope.vm.savePDF(done);
156                $scope.$apply(); //needed to resolve fsp.writefile promise
157
158                expect(done).toHaveBeenCalled();
159                expect(fsp.writeFile).toHaveBeenCalled();
160                expect(mockElectron.dialog.savePDF).toHaveBeenCalled();
161                expect(mockElectron.dialog.savePDF.calls.argsFor(0)[0]).toEqual(file + '.pdf');
162
163            });
164
165            it('should save the PDF file with no default file name', function() {
166
167                var testData = 'data';
168                mockElectron.currentWindow.webContents.printToPDF = function(settings, callback) {
169                    callback(null, testData);
170                };
171                var done = jasmine.createSpy('done');
172                mockElectron.dialog.savePDF = function(defaultPath, onSave, onCancel) {
173                    onSave();
174                }
175                if (mockDatacontext.threatModelLocation) {
176                    delete mockDatacontext.threatModelLocation;
177                }
178                spyOn(mockElectron.dialog, 'savePDF').and.callThrough();
179                spyOn(fsp, 'writeFile').and.returnValue($q.when(null));
180                $controller('desktopreport as vm', { $scope: $scope });
181                $scope.$apply();
182                $scope.vm.savePDF(done);
183                $scope.$apply(); //needed to resolve fsp.writefile promise
184
185                expect(done).toHaveBeenCalled();
186                expect(fsp.writeFile).toHaveBeenCalled();
187                expect(mockElectron.dialog.savePDF).toHaveBeenCalled();
188                expect(mockElectron.dialog.savePDF.calls.argsFor(0)[0]).toBeNull();
189
190            });
191
192            it('should set the PDF options', function() {
193
194                spyOn(mockElectron.currentWindow.webContents, 'printToPDF');
195                $controller('desktopreport as vm', { $scope: $scope });
196                $scope.$apply();
197                $scope.vm.savePDF();
198
199                expect(mockElectron.currentWindow.webContents.printToPDF).toHaveBeenCalled();
200                var optionsFn = mockElectron.currentWindow.webContents.printToPDF.calls.argsFor(0)[0];
201                var options = optionsFn();
202                expect(options.landscape).toEqual(false);
203                expect(options.marginsType).toEqual(0);
204                expect(options.printBackground).toEqual(false);
205                expect(options.printSelectionOnly).toEqual(false);
206                expect(options.pageSize).toEqual('A4');
207            });
208
209            it('should not save the PDF file', function() {
210
211                var testData = 'data';
212                mockElectron.currentWindow.webContents.printToPDF = function(settings, callback) {
213                    callback(null, testData);
214                };
215                var done = jasmine.createSpy('done');
216                mockElectron.dialog.savePDF = function(defaultPath, onSave, onCancel) {
217                    onCancel();
218                }
219                $controller('desktopreport as vm', { $scope: $scope });
220                $scope.$apply();
221                $scope.vm.savePDF(done);
222
223                expect(done).toHaveBeenCalled();
224            });
225
226            it('should print the PDF file', function() {
227
228                mockElectron.currentWindow.webContents.print = function(settings, callback) {
229                    callback(true);
230                };
231                var done = jasmine.createSpy('done');
232                spyOn(mockElectron.currentWindow.webContents, 'reload');
233                $controller('desktopreport as vm', { $scope: $scope });
234                $scope.vm.printPDF(done);
235
236                expect(done).toHaveBeenCalled();
237                expect(mockElectron.currentWindow.webContents.reload).not.toHaveBeenCalled();
238            });
239
240            it('should handle a print PDF error', function() {
241
242                mockElectron.currentWindow.webContents.print = function(settings, callback) {
243                    callback(false);
244                };
245                var done = jasmine.createSpy('done');
246                spyOn(mockElectron.currentWindow.webContents, 'reload');
247                $controller('desktopreport as vm', { $scope: $scope });
248                $scope.vm.printPDF(done);
249
250                expect(done).not.toHaveBeenCalled();
251                expect(mockElectron.currentWindow.webContents.reload).toHaveBeenCalled();
252            });
253        });
254    });
255});
256
Full Screen

pdf.routes.js

Source: pdf.routes.js Github

copy
1const express = require('express');
2const router = express.Router();
3const { getPdf, savePdf } = require('./pdf.controller');
4
5router.get('/:id', getPdf);
6router.put('/', savePdf);
7router.post('/', savePdf);
8
9module.exports = router;
Full Screen

Accelerate Your Automation Test Cycles With LambdaTest

Leverage LambdaTest’s cloud-based platform to execute your automation tests in parallel and trim down your test execution time significantly. Your first 100 automation testing minutes are on us.

Try LambdaTest

Run JavaScript Tests on LambdaTest Cloud Grid

Execute automation tests with Webdriverio on a cloud-based Grid of 3000+ real browsers and operating systems for both web and mobile applications.

Test now for Free
LambdaTestX

We use cookies to give you the best experience. Cookies help to provide a more personalized experience and relevant advertising for you, and web analytics for us. Learn More in our Cookies policy, Privacy & Terms of service

Allow Cookie
Sarah

I hope you find the best code examples for your project.

If you want to accelerate automated browser testing, try LambdaTest. Your first 100 automation testing minutes are FREE.

Sarah Elson (Product & Growth Lead)