How to use Docx.js? - javascript

i have use docx.js for generate docx file, but generaeted docx doenot open. my generated docx file output is
i have included following js file into my Html page
<script type="text/javascript" src="js/Docx/jszip.js"></script>
<!-- Include main js lib -->
<script type="text/javascript" src="js/Docx/DOCX.js"></script>
and javascript function is
function test() {
//alert("test fn call");
var doc = new DOCXjs();
doc.text('DOCX.js is a free open source library for generating Microsoft Word Documents using pure client-side JavaScript.');
//doc.text('It was developed by James Hall at Snapshot Media.');
var output = doc.output('datauri');
}
when i click button this function will be calling, and also i want to add datatable as a content of word document so how to add content using Docx.js?

Probably you are trying to use the docx.js without server, that will not work because it can't load the necessary files.
if you are executing the code on a server then edit the path of '/blank/' somewhere in the docx.js file
$.ajax({
url: '/blank/' + files[file],
complete: function(r) {
//file_data[this.url.replace(/blank_/, '')] = r.responseText;
zip.add(this.url.replace('/blank/', ''), r.responseText);
file_count_current ++;
if (file_count == file_count_current) {
doOutput();
}
}
});

Related

How do I share Javascript code between files in Windbg preview?

How do I share Javascript code between files in Windbg preview?
Right now I have several helper methods that I have copied and pasted into different javascript files. I'm not all that experienced with javascript, so my apologies if this is a stupid question.
As an example, let's say I want to use this function in more than one file:
function GetGuid( objectPtr )
{
return ExecuteCommandToString( "dt nt!_GUID " + objectPtr )
.FindLineContaining("{").trim().replace("{", "").replace("}","");
}
I have a common.js which has a few functions that are normally reusable like
host.diagnostics.debugLog()
i first load it using .scriptload
then in other js files I create a var to those functions and use it
see if this helps
contents of common function file
C:\>cat c:\wdscr\common.js
function log(instr) {
host.diagnostics.debugLog(instr + "\n");
}
function exec (cmdstr){
return host.namespace.Debugger.Utility.Control.ExecuteCommand(cmdstr);
}
a js file using the function from common.js
C:\>cat c:\wdscr\usecommon.js
function foo(){
var commonlog = host.namespace.Debugger.State.Scripts.common.Contents.log
var commonexec = host.namespace.Debugger.State.Scripts.common.Contents.exec
commonlog("we are using the logging function from the common.js file")
var blah = commonexec("lma #$exentry")
for(var a of blah) {
commonlog(a)
}
}
actual usage
C:\>cdb calc
Microsoft (R) Windows Debugger Version 10.0.16299.15 X86
0:000> .load jsprovider
0:000> .scriptload c:\wdscr\common.js
JavaScript script successfully loaded from 'c:\wdscr\common.js'
0:000> .scriptload c:\wdscr\usecommon.js
JavaScript script successfully loaded from 'c:\wdscr\usecommon.js'
0:000> dx #$scriptContents.foo()
we are using the logging function from the common.js file
start end module name
00f10000 00fd0000 calc (deferred)
#$scriptContents.foo()
0:000>

How to read the contents of a file inside an epub using javascript

I need to read, inside a page of an epub3 book, the contents of one of the file of that same epub, being some data to process with a javascript function.
Unfortunately, Javascript prevents from loading local files for security reasons. (e.g the File API only allows loading uploaded user files).
But for me in the context of an epub3, it makes sense and I didn't find any information in the IDPF EPUB3 documentation related to this topic.
Any idea ?
OK. Let's clarify:
I have an epub3 with the following structure:
<root>
META-INF
...
OEBPS
pages
page.xhtml
data
data.xml
In page.xhtml, I want to write in Javascript something like:
<script type="text/javascript">
//pseudo code
var indata = readAsText("../data/data.xml"); // how to write that ???
var outdata = myfunction(indata);
</script>
Found the solution for ages, and realized that it had never been answered:
So answering to my own question ;-)
<script type="text/javascript">
/* Load the file using HTTP GET */
$.get( "../data/data.xml", function( indata ) {
var outdata = myfunction(indata);
}, 'text');
</script>

Organizing Handlebars files

In this simple example...
http://plnkr.co/edit/78ObAiirrSFPcvyiBKqn
...I try to have a Handlebars template and the content that should populate it into separate files, instead of having the template inside the HTML and the content object in the js script, as in this other example:
http://embed.plnkr.co/KXdVgedRA8K95S17peuH/
And I also found this post where this guy means the same as I do (right?):
Using pre-compiled templates with Handlebars.js (jQuery Mobile environment)
I tried that (what's on the accepted answer, see the code below), but it doesn't work. I get "undefined is not a function".
On the other hand, that answer has 90 upvotes so I must be missing something somewhere. Could someone point that out to me?
Another related question: should I use AJAX to load a local file?
index.html
<script src="cities.tmpl.js"></script> <!-- compiled template -->
<script src="content.js"></script>
<script src="script.js"></script>
script.js
var template = Handlebars.templates['cities.tmpl']; // your template minus the .js
var context = data_pr.all(); // your data
var html = template(context);
Solved it, based on this post:
http://www.jblotus.com/2011/05/24/keeping-your-handlebars-js-templates-organized/
I changed a little bit so it's easier to read (at least for me):
function getTemplate(path, callback) {
$.ajax({
url: path,
success: function(data) {
var template = Handlebars.compile(data);
if (callback) callback(template);
}
});
}
getTemplate('cities.tmpl', function(template) {
var html = template(data_pr); // data_pr = my data from content.js
document.getElementById('cities-placeholder').innerHTML = html;
});
sample code here

Load page with Ajax and load new scripts if necessary

I have a page1 which has a wrapper with articles.
<div id="wrapper">
<article>...</article>
<article>...</article>
<article>...</article>
<article>...</article>
</div>
I am loading new articles from page2 with Ajax and appending them to the wrapper
$.ajax({
url : page_to_load,
success : function (data) {
$('article',data).appendTo('#wrapper');
}
});
But some of this new articles might need specific scripts that were not loaded in page1 but would be loaded if accessed directly page2.
So the problem is some of the content in new articles breaks as they are missing those scripts.
What is the best solution? I can think of checking the new loaded page scripts and compare them with the already loaded and download the new ones, but I have no idea of how to do this.
EDIT
I noticed if I set the dataType to 'html' I cant search for the scripts, although they are there:
$('script',data)//doesn't match anything
But if I do:
console.log(data);
I can see the whole page with <html> and <script> tags
There is no problem actually, if you append HTML to the Dom then script calls will be interpreted as if the page was loaded directly, just make sure you use the same parameters as the shorthand jquery $.POST method.
I actually do this all the time and the <script src=""> are called and interpreted correctly
Just make sure you're accessing the scripts from the right scope as if the html was hardcoded on page1.
If this doesn't work, then check with the web inspector if the scripts are loaded or not.
Working solution:
$.ajax({
url : page_to_load,
success : function (data) {
// load the scripts
var dom = $(data);
dom.filter('script').each(function(){
var scriptSrc = $(this).attr('src');
if(!$('script[src="'+ scriptSrc +'"]').length && scriptSrc !== undefined) {
var script = $("<script/>");
script.attr('src', scriptSrc);
$("head").append(script);
}
});
// load the articles
$('article',data).appendTo('#wrapper');
}
});
Not sure but maybe you could add a script in the AJAX call - I'm not sure of this because I haven't tried it:
Proxy.Scripts.Add(new ScriptReference(AddVersion("/Pages/Items/SearchList/SearchList.Grid.js" )));
This workflow should work :
After every page request :
Get all the script tags in the loaded page.
Loop over the scripts
If it's not loaded yet , load it.
Here is the code snippet :
$.ajax({
url : 'http://localhost',
success : function (data) {
$('article',data).appendTo('#wrapper');
$.each($.parseHTML(data,null,true),function(){
if($(this)[0].tagName == "SCRIPT"){
var src = $(this).attr('src');
if($('script[src="'+ src +'"]').length){
$.getScript(src);
}
});
}
});
Disable async.
$.ajax({
url : page_to_load,
async: false,
success : function (data) {
$('article',data).appendTo('#wrapper');
}
});
you can use RequireJS or HeadJs library for calling js files.
RequireJS is a JavaScript file and module loader and HeadJS, a small library for Responsive Design, Feature Detections & Resource Loading
HeadJs is great and useful, try it.

How can I include all JavaScript files in a directory via JavaScript file?

I have a bunch of JavaScript files that I would like to include in the page, but I don't want to have to keep writing
<script type="text/javascript" src="js/file.js"></script>
So is there a way to include all files in a directory (unknown size)? Can I do something like...
$.getScript("js/*.js");
... to get all the JavaScript files in the "js" directory? How can I do this using jQuery?
In general, this is probably not a great idea, since your html file should only be loading JS files that they actually make use of. Regardless, this would be trivial to do with any server-side scripting language. Just insert the script tags before serving the pages to the client.
If you want to do it without using server-side scripting, you could drop your JS files into a directory that allows listing the directory contents, and then use XMLHttpRequest to read the contents of the directory, and parse out the file names and load them.
Option #3 is to have a "loader" JS file that uses getScript() to load all of the other files. Put that in a script tag in all of your html files, and then you just need to update the loader file whenever you upload a new script.
What about using a server-side script to generate the script tag lines? Crudely, something like this (PHP) -
$handle = opendir("scripts/");
while (($file = readdir($handle))!== false) {
echo '<script type="text/javascript" src="' . $file . '"></script>';
}
closedir($handle);
Given that you want a 100% client side solution, in theory you could probably do this:
Via XmlHttpRequest, get the directory listing page for that directory (most web servers return a listing of files if there is no index.html file in the directory).
Parse that file with javascript, pulling out all the .js files. This will of course be sensitive to the format of the directory listing on your web server / web host.
Add the script tags dynamically, with something like this:
function loadScript (dir, file) {
var scr = document.createElement("script");
scr.src = dir + file;
document.body.appendChild(scr);
}
It can be done fully client side, but all javascript file names must be specified.
For example, as array items:
function loadScripts(){
var directory = 'script/';
var extension = '.js';
var files = ['model', 'view', 'controller'];
for (var file of files){
var path = directory + file + extension;
var script = document.createElement("script");
script.src = path;
document.body.appendChild(script);
}
}
You can't do that in JavaScript, since JS is executed in the browser, not in the server, so it didn't know anything about directories or other server resources.
The best option is using a server side script like the one posted by jellyfishtree.
#jellyfishtree it would be a better if you create one php file which includes all your js files from the directory and then only include this php file via a script tag. This has a better performance because the browser has to do less requests to the server. See this:
javascripts.php:
<?php
//sets the content type to javascript
header('Content-type: text/javascript');
// includes all js files of the directory
foreach(glob("packages/*.js") as $file) {
readfile($file);
}
?>
index.php:
<script type="text/javascript" src="javascripts.php"></script>
That's it!
Have fun! :)
You could use something like Grunt Include Source. It gives you a nice syntax that preprocesses your HTML, and then includes whatever you want. This also means, if you set up your build tasks correctly, you can have all these includes in dev mode, but not in prod mode, which is pretty cool.
If you aren't using Grunt for your project, there's probably similar tools for Gulp, or other task runners.
You can't do that in Javascript from the browser... If I were you, I would use something like browserify. Write your code using commonjs modules and then compile the javascript file into one.
In your html load the javascript file that you compiled.
I was looking for an answer to this question and had my own problems. I found a couple solutions in various places and put them together into my own preferred answer.
function exploreFolder(folderURL,options){
/* options: type explaination
**REQUIRED** callback: FUNCTION function to be called on each file. passed the complete filepath
then: FUNCTION function to be called after loading all files in folder. passed the number of files loaded
recursive: BOOLEAN specifies wether or not to travel deep into folders
ignore: REGEX file names matching this regular expression will not be operated on
accept: REGEX if this is present it overrides the `ignore` and only accepts files matching the regex
*/
$.ajax({
url: folderURL,
success: function(data){
var filesLoaded = 0,
fileName = '';
$(data).find("td > a").each(function(){
fileName = $(this).attr("href");
if(fileName === '/')
return; //to account for the (go up a level) link
if(/\/\//.test(folderURL + fileName))
return; //if the url has two consecutive slashes '//'
if(options.accept){
if(!options.accept.test(fileName))
//if accept is present and the href fails, dont callback
return;
}else if(options.ignore)
if(options.ignore.test(fileName))
//if ignore is present and the href passes, dont callback
return;
if(fileName.length > 1 && fileName.substr(fileName.length-1) === "/")
if(options.recursive)
//only recurse if we are told to
exploreFolder(folderURL + fileName, options);
else
return;
filesLoaded++;
options.callback(folderURL + fileName);
//pass the full URL into the callback function
});
if(options.then && filesLoaded > 0) options.then(filesLoaded);
}
});
}
Then you can call it like this:
var loadingConfig = {
callback: function(file) { console.log("Loaded file: " + file); },
then: function(numFiles) { console.log("Finished loading " + numFiles + " files"); },
recursive: true,
ignore: /^NOLOAD/,
};
exploreFolder('/someFolderURL/', loadingConfig);
This example will call that callback on every file/folder in the specified folder except for ones that start with NOLOAD. If you want to actually load the file into the page then you can use this other helper function that I developed.
function getFileExtension(fname){
if(fname)
return fname.substr((~-fname.lastIndexOf(".") >>> 0) + 2);
console.warn("No file name provided");
}
var loadFile = (function(filename){
var img = new Image();
return function(){
var fileref,
filename = arguments[0],
filetype = getFileExtension(filename).toLowerCase();
switch (filetype) {
case '':
return;
case 'js':
fileref=document.createElement('script');
fileref.setAttribute("type","text/javascript");
fileref.setAttribute("src", filename);
break;
case "css":
fileref=document.createElement("link");
fileref.setAttribute("rel", "stylesheet");
fileref.setAttribute("type", "text/css");
fileref.setAttribute("href", filename);
break;
case "jpg":
case "jpeg":
case 'png':
case 'gif':
img.src = filename;
break;
default:
console.warn("This file type is not supported: "+filetype);
return;
}
if (typeof fileref !== undefined){
$("head").append(fileref);
console.log('Loaded file: ' + filename);
}
}
})();
This function accepts a JS | CSS | (common image) file and loads it. It will also execute the JS files.
The complete call that needs to be run in your script to load all images and* stylesheets and other scripts could look like this:
loadingConfig = {
callback: loadfile,
then: function(numFiles) { console.log("Finished loading " + numFiles + " files"); },
recursive: true,
ignore: /^NOLOAD/,
};
exploreFolder('/someFolderURL/', loadingConfig);
It works amazingly!
Another option that is pretty short:
<script type="text/javascript">
$.ajax({
url: "/js/partials",
success: function(data){
$(data).find('a:contains(.js)').each(function(){
// will loop through
var partial= $(this).attr("href");
$.getScript( "/js/partials/" + partial, function( data, textStatus, jqxhr ) {});
});
}
});
</script>

Categories

Resources