How to save Jspdf file into specific folder - jspdf

i am using jspdf to generate a pdf.Its working but the file is download to "Download" folder.but i want to download specific folder like this("localhost/ccs/ccs/invoice") folder path to save the generated pdf.how to solve to change in my code. my example code is
<div class="invoice" id="customers" ng-repeat="aim in input">
<div align="right"><h1 align="right"><b>INVOICE</b> </h1></div>
<table>
<tr>
<td>
Hello
</td>
<td>
Hi
</td>
</tr>
</table>
</div>
<button onclick="javascript:demoFromHTML();">PDF</button>
my scripting code is
<script>
function demoFromHTML() {
var pdf = new jsPDF('p', 'pt', 'letter');
// source can be HTML-formatted string, or a reference
// to an actual DOM element from which the text will be scraped.
source = $('#customers')[0];
// we support special element handlers. Register them with 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 compound) at this time.
specialElementHandlers = {
// element with id of "bypass" - jQuery style selector
'#bypassme': function (element, renderer) {
// true = "handled elsewhere, bypass text extraction"
return true
}
};
margins = {
top: 80,
bottom: 60,
left: 40,
width: 522
};
// all coords and widths are in jsPDF instance's declared units
// 'inches' in this case
pdf.fromHTML(
source, // HTML string or DOM elem ref.
margins.left, // x coord
margins.top, {// y coord
'width': margins.width, // max width of content on PDF
'elementHandlers': specialElementHandlers
},
function (dispose) {
// dispose: object with X, Y of the last line add to the PDF
// this allow the insertion of new lines after html
pdf.save('Invoice.pdf');
}, margins);
}
</script>
<script type="text/javascript" src="http://mrrio.github.io/jsPDF/dist/jspdf.debug.js"> </script>
Thank you.

You could use 'FileSaver.js' along with jspdf.js, it will help you to save pdf in specific folder whereever you like.
var pdf = new jsPDF();
// your code here to write something in to pdf.
pdf.save(fileName);

Related

Uncaught TypeError: Cannot read property 'addEventListener' of null. Could not start video source. Face-Api.js and Rails 5

Hello I have a application with rails 5 where I add the Face-api.js library for face recognition.
In my view I have the script and video for face detection and recogniton but when I go to browser and load the page the console return the follow error.
Uncaught TypeError: Cannot read property 'addEventListener' of null
at new:161
(anonymous) # new:161
new:149 NotReadableError: Could not start video source
My view with scripts and webcam video:
<head>
<%= javascript_include_tag 'face_api'%>
<%= javascript_include_tag "face-api.js/dist/face-api.min.js" %>
<%= javascript_include_tag "face-api.js/dist/face-api.js" %>
<script>
const camfr = document.getElementById('camfr')
const startVideo = () => {
var constraints = { audio: true, video: { width: 1280, height: 720 } };
navigator.mediaDevices.getUserMedia(constraints)
.then(function(mediaStream) {
var video = document.querySelector('video');
video.srcObject = mediaStream;
video.onloadedmetadata = function(e) {
video.play();
};
})
.catch(function(err) { console.log(err.name + ": " + err.message); }); // always check for errors at the end.
}
Promise.all([
faceapi.nets.tinyFaceDetector.loadFromUri("<%= asset_path('face-api.js/models/tiny_face_detector/tiny_face_detector_model-weights_manifest.json') %>"),
faceapi.nets.faceLandmark68Net.loadFromUri("<%= asset_path('face-api.js/models/face_landmark_68/face_landmark_68_model-weights_manifest.json') %>"), //desenha os traços do rosto
faceapi.nets.faceRecognitionNet.loadFromUri("<%= asset_path('face-api.js/models/face_recognition/face_recognition_model-weights_manifest.json') %>"),//faz o conhecimento do rosto
faceapi.nets.faceExpressionNet.loadFromUri("<%= asset_path('face-api.js/models/face_expression/face_expression_model-weights_manifest.json') %>"),//detecta expressoes
faceapi.nets.ageGenderNet.loadFromUri("<%= asset_path('face-api.js/models/age_gender_model/age_gender_model-weights_manifest.json') %>"),//idade e genero
faceapi.nets.ssdMobilenetv1.loadFromUri("<%= asset_path('face-api.js/models/ssd_mobilenetv1/ssd_mobilenetv1_model-weights_manifest.json') %>") // usada para detectar rosto
]).then(startVideo)
camfr.addEventListener('play', async () => {
const canvas = faceapi.createCanvasFromMedia(camfr)
const canvasSize = {
width: camfr.width,
height: camfr.height
}
faceapi.matchDimensions(canvas, canvasSize)
document.body.appendChild(canvas)
setInterval(async () => {
const detections = await faceapi
.detectAllFaces(
camfr,
new faceapi.TinyFaceDetectorOptions()
)
.withFaceLandmarks()
.withFaceExpressions()
.withAgeAndGender()
const resizedDetections = faceapi.resizeResults(detections, canvasSize)
canvas.getContext('2d').clearRect(0, 0, canvas.width, canvas.height)
faceapi.draw.drawDetections(canvas, resizedDetections)
faceapi.draw.drawFaceLandmarks(canvas, resizedDetections)
faceapi.draw.drawFaceExpressions(canvas, resizedDetections)
resizedDetections.forEach(detection => {
const {age, gender, genderProbability} = detection
new faceapi.draw.DrawTextField([
`${parseInt(age, 10)} years`,
`${gender} (${ parseInt(genderProbability * 100, 10)})`
], detection.detection.box.topRight).draw(canvas)
})
}, 100)
})
</script>
</head>
<body>
<video autopĺay id="camfr" width="400" height="400" muted></video>
</body>
I doesnt understand what this doesnt work the face-api.js is on vendor/assets/javascripts, in assets.rb i make the pre compile of new javascripts and models of face-api.js.
my face-api.js
//= require face-api.js/dist/face-api
//= require face-api.js/dist/face-api.js
//= require face-api.js/dist/face-api.min.js
A <head> tag loads before the rest of the page, and hence the DOM isn't loaded when camfr = document.getElementById('camfr') runs. You need to wrap your script in an event to ensure the DOM is fully loaded before it executes. If you're using turbolinks:
document.addEventListener('turbolinks:load', () => {
const camfr = document.getElementById('camfr');
if (element) {
...
}
});
If you aren't using turbolinks you can use the onload event instead of turbolinks:load.
Also, The 'Rails way' of using Javascript would be to extract your code into a separate .js file in the asset path (or webpacker pack if you are using Rails 6) rather than embedding directly into a <script> tag.

Knockout Binding Not Working with jQueryUI Dialogue

My viewModel has an array called 'Items'. I want to display the contents of 'Items' using a foreach binding. Everything works fine when I use regular HTML. But does not work with a dialogue box which I created using jQueryUI.
HTML:
<div id="skus0">
<div id="skus1">
<ul data-bind="foreach: Items">
<li data-bind="text:Name"></li>
</ul>
</div>
<input type="button" id="openQryItems" class="btn btn-info" value="Open" data-bind="click:openQueryItems" />
</div>
JavaScript:
// my view model
var viewModel = {
Items: [{Name:'Soap'},{Name:'Toothpaste'}]
};
// JS to configure dialogue
$("#skus1").dialog({
autoOpen: false,
width: 500,
modal: true,
buttons: {
"OK": function () {
$(this).dialog("close");
},
"Cancel": function () {
$(this).dialog("close");
}
}
});
// for mapping my model using ko.mapping plugin
var zub = zub || {};
zub.initModel = function (model) {
zub.cycleCountModel = ko.mapping.fromJS(model);
zub.cycleCountModel.openQueryItems = function () {
$("#skus1").dialog("open");
}
ko.applyBindings(zub.cycleCountModel, $("#skus0")[0]);
}
zub.initModel(viewModel);
I have created a fiddle here my fiddle
$.fn.dialog removes the element from its place in the DOM and places it in a new container; this is how it can create a floating window. The problem with this happening is that it breaks data binding, since the dialog DOM is no-longer nested within the top-level data-bound DOM.
Moving the dialog initialization to after ko.applyBindings will enable dialog to yank stuff out of the DOM after the list is populated. Of course, this means that after that point, future changes will still not be reflected, which may be important if you're wanting the opened dialog to change automatically.
If you are wanting the dialog contents to be fully dynamic, you could create a binding handler; we did this in our project. Here's a rough outline of how we did this:
ko.bindingHandlers.dialog = {
init: function (element, valueAccessor, allBindingsAccessor, viewModel, bindingCtx) {
var bindingValues = valueAccessor();
var hasAppliedBindings = false;
var elem = $(element);
var options = {
id: ko.utils.unwrapObservable(bindingValues.id),
title: ko.utils.unwrapObservable(bindingValues.title),
// etc...
onOpen: function () {
if (!hasAppliedBindings) {
hasAppliedBindings = true;
var childCtx = bindingCtx.createChildContext(viewModel);
ko.applyBindingsToDescendants(childCtx, element);
}
}
};
elem.dialog(options);
}
return { controlsDescendantBindings: true };
}
...which we used like this:
<div data-bind="dialog: { title: 'some title', id: 'foo', ... }">
<!-- dialog contents -->
</div>
What return { controlsDescendantBindings: true } does is makes sure that outer bindings do not affect anything using the dialog binding handler. Then we create our own Knockout binding "island" after it is pulled out of the DOM, based on the original view model.
Although in our project we also used hybrid jQuery+Knockout, I would highly recommend you avoid this whenever possible. There were so many hacks we had to employ to sustain this type of application. The very best thing you should do is prefer Knockout binding handlers (and I think it has a "component" concept now which I haven't played with) over DOM manipulations to avoid buggy UI management.

Jquery data-role collapsible events aren't being captured in Jquery Mobile

Could anybody please let me know why the following code isn't working when i am using with Jquery mobile JS
http://jsfiddle.net/znz17ctm/7/
This is my code
<div role="main" class="ui-content oms-content" id="dd">
<div class="myactivelabelsWrap" id="result"></div>
</div>
var response = {
"Restaurants": [{
"RestrntArea": "Haii",
"cust_loc_id": "374"
}, {
"RestrntArea": "rerrrwe",
"cust_loc_id": "373"
}]
}
showLabels();
function showLabels() {
//$("#result").html("");
var favoriteresultag = '';
for (var i = 0; i < response.Restaurants.length; i++) {
var name = response.Restaurants[i].RestrntArea;
if (name) {
favoriteresultag +=
'<div data-role="collapsible" data-inset="false" class="my-collaspible"><h3>' +
name +
' <a class="icon-pencil-1 labelEditIcon "></a></h3></div>';
}
}
$("#result").append(favoriteresultag).trigger("create");
}
$(document).ready(function() {
$('.my-collaspible').bind('expand', function() {
alert('Expanded');
});
$('.my-collaspible').bind('collapse', function() {
alert('Collapsed');
});
});
Why the collapse and expand even'ts are being captured ??
Instead of document ready i tried with al the page events of mobile . But no luck .
From your fiddle I can't tell which version of jQM you are using. You have checked version 1.3 but then added the 1.4 css. Assumin version 1.4, I have updated your fiddle:
FIDDLE
Basically, you need to use event delegation to attach the events because the collapsibles do not exist at the time of the bind. Also the event names are actually collapsibleexpand and collapsiblecollapse.
So use on() instead of bind() by handling the event on the parent div and delegating it to all items with class my-collapsible that exist now or added dynamically:
$("#result").on('collapsibleexpand', '.my-collaspible', function () {
alert('Expanded');
});
$("#result").on('collapsiblecollapse', '.my-collaspible', function () {
alert('Collapsed');
});

need some guidance in dialog box implementation

I have a cakephp view (index.ctp) where I have edit button. On button edit I want the jquery dialog box open with what i have in edit.ctp. (Currently if I go to edit.ctp, it works fine but I am trying to use model / dialog box so the user stays on same page)
This is what I have in my index.ctp
<td>
<?php echo $this->Html->link($team['Company']['name'], array('action' => 'edit_reload','team_id'=>$team['Team']['id']), array('id'=>"dialog_link", 'class'=>"ui-state-default ui-corner-all"));?>
</td>
<div id="dialog" title="Dialog Title">
</div>
Now when the link clicked I want to show the edit_reload.ctp contents here. I am totally exhausted so any help will be appreciated
thanks
In a separate JS file write the following code and add your values to the variables and include the JS file in your .ctp file.
$(document).ready(function() {
$myWindow = $('#dialog');
//instantiate the dialog
$myWindow.dialog({ height: 250,
width: 200,
modal: true,
position: 'center',
autoOpen:false,
title:'',
overlay: { opacity: 0.5, background: 'black'}
});
$J("#dialog_link").click( showDialog );
});// end (document).ready
var showDialog = function() {
var team_id = '';
var url = '/controller/action/' + team_id;//Apply path to controller, action
$.post(url, function(res) {
$myWindow.dialog({
title:'Give Title'
});
$('#dialog').html(res);
$myWindow.show();
});
}
In .ctp file use the link as follows-
echo $this->Html->link($team['Company']['name'],'#', array('id'=>"dialog_link", 'class'=>"ui-state-default ui-corner-all"));
I have show you an example.You can also write the js code in the .ctp file also.

How do I save the position of draggable & resizeable elements?

I'm building a site which allows users to create an html page which can then be saved and shared on another site. I want them to be able to resize and drag the page elements. I can do this using jQuery, but I'm not sure how I then save that so that when the page is viewed elsewhere, it looks the same.
I haven't decided yet how to store the page info, but what I'm thinking is that I can store each element in the database along with its absolute position, and its contents. Does that sound like a good plan?
If so, how do I get the position for the div to pass to the php so that it can be saved?
Thanks.
JQueryUI Resizable has an event called resize that you can use:
var resposition = '';
$('#divresize').resizable({
//options...
resize: function(event,ui){
resposition = ui.position;
}
});
The same occurs with JQueryUI Draggable and its event drag:
var dragposition = '';
$('#divdrag').draggable({
// other options...
drag: function(event,ui){
dragposition = ui.position;
}
});
resposition and dragposition is going to be arrays. You can see it working here: http://jsbin.com/uvuzi5
EDIT: using a form, you can save dragposition and resposition into hidden inputs
var inputres = '<input type="hidden" id="resposition" value="'+resposition.left+','+resposition.top+'"/>'
$('#myform').append(inputres);
var inputdrag = '<input type="hidden" id="dragposition" value="'+dragposition.left+','+dragposition.top+'"/>'
$('#myform').append(inputdrag);
And in your PHP file to handle the form:
$dragposition = $_GET['dragposition'];
$resposition = $_GET['resposition'];
$dragposition = explode(',',$dragposition);
$resposition = explode(',',$resposition);
Finally, both variables should be arrays with top and left attributes:
$dragposition => [top,left] attributes from draggable
$resposition => [top,left] attributes from resizable
you have to save position at some where so that you can get position
details when next time you open page.
option 1: you can store html elements position details in "localStorage" its default browser storage.
Example: Demo
<!DOCTYPE html>
<html lang="en">
<head>
<title>Dashboard</title>
<!-- jQuery -->
<script src="vendor/jquery/jquery.min.js"></script>
<link rel="stylesheet" type="text/css" href="dist/css/jquery-ui.min.css">
<script src="dist/js/jquery-ui.min.js"></script>
</head>
<body>
<script>
var positions = JSON.parse(localStorage.positions || "{}");
$(function() {
var d = $("[id=draggable]").attr("id", function(i) {
return "draggable_" + i
})
$.each(positions, function(id, pos) {
$("#" + id).css(pos)
})
d.draggable({
containment: "#wrapper",
scroll: false,
stop: function(event, ui) {
positions[this.id] = ui.position
localStorage.positions = JSON.stringify(positions)
}
});
});
</script>
<div id="wrapper">
<div id="draggable" class="ui-widget-content draggable" style="height:100px;width:100px;float:left">Div1</div>
<div id="draggable" class="ui-widget-content draggable" style="height:100px;width:100px;float:left">Div2</div>
<div id="draggable" class="ui-widget-content draggable" style="height:100px;width:100px;float:left">Div3</div>
</div>
</body>
</html>
option 2: you can store html elements position details in "your database"

Resources