open plotly in qwebview in interactive mode - javascript

I'm using plotly library in offline mode with python and what I'm trying to do is to create some plot, save them as local html and load in a second moment into a QWebView.
This is the code for a boxplot with a dummy variable:
from PyQt5.QtWebKitWidgets import QWebView
import plotly
import plotly.graph_objs as go
x1 = [10, 3, 4, 5, 20, 4, 3]
trace1 = go.Box(
x = x1)
layout = go.Layout(
showlegend = True
)
data = [trace1]
fig = go.Figure(data=data, layout = layout)
fn = '/home/matteo/plot.html'
plotly.offline.plot(fig, filename = fn,
auto_open = False)
view = QWebView()
view.load(QUrl.fromLocalFile(fn))
view.show()
I'm facing 2 main problems:
if I let the code as it is, the QWebView won't show anything like in the image:
if I open the html file with the standard browser (Firefox for example), I can see and interact with the plot, and that's fine. But if I save the html page from the browser in a local directory and try to load the saved file into the QWebView I can see the plot, but cannot interact with it (maybe for some Javascript missing?!):
Anybody has some ideas how to embed an interactive offline made chart into a QWebView?

Ok, I should have find what the problem is.
Is seems that QWebView has some difficulties to load the local file because it is too heavy (about 2mb for simple plot).
So I used the option to not include the javascript when saving the local file and to load the javascript in a second moment thanks, as described here.
In other words, create the initial html tags, include the result of the figure generated by plotly without the whole javascript code, and include the link of the javascript.
In this way the file is super light and QWebView does not have issue to open it.
# create the initial html code
raw_html = '<head><meta charset="utf-8" /></head>''<head><meta charset="utf-8" /><script src="https://cdn.plot.ly/plotly-latest.min.js"></script></head>'
# call the plot method without all the javascript code
raw_html += plotly.offline.plot(fig, filename = fn, include_plotlyjs=False)
# close the body and html tags
raw_html += '</body></html>'

Related

Web application - Write To .txt file with Javascript FileObject.Write

I'm trying to re-purpose some older java script code that I use in order to create a text file via an intranet web app. The following code creates text files that are picked up and processed by a third party application running on the same device...
<script>
function WriteTransferFile(location) {
var fileSystemObject = new ActiveXObject("Scripting.FileSystemObject");
var fileObject = fileSystemObject.CreateTextFile("C:\\transfer\\transfer.txt", true);
fileObject.Write(location);
fileObject.Close();
return location;
}
</script>
<script id="writetransfer">
function writetransfer() {
var Location = document.getElementById('lblCommand');
var Command = Location.innerHTML;
WriteTransferFile(Command);
}
</script>
This works fine for a single text string to be pasted into a text file, but I now need to create a file which takes 4 different fields from the web page and writes them on to consecutive lines. I've played around with the above but any attempt to add a second line of text overwrites the first line instead creating a new one below it. Desired output...
Field 1
Field 2
Field 3
Field 4
Any ideas how I might accomplish this?
I'm aware this probably isn't the sleekest solution, but there are no concerns regarding the suppression of active X security settings as this is for a closed system with access to local intranet only.
Thanks
Steve

Open Explorer window from Website, on mounted drives, including javascript in the link reference to generate the path

In addition to the question here:
Open Explorer window from Website
I'm also having trouble with this, especially because I need to integrate a function into the link that eventually will open in file explore.
Bacially, we have a very simple intranet webpage, to control our cases etc.
Each case has some files in in a folder on the server, but to avoid to many subfolders in one folder, we split them in groubs of 200!
\ip\fileserver\cases\"split-folder"\subfolder
I what to open the folder clicking on the case on our webpage.
The split-folder..is defined in ranges with case-numbers for evey 200 cases (sager in danish)
Like this
\25000-25199\25001
\25200-25399\25399
\25400-25599\25422 or 25555 etc . .
The math to calculate the "split-folder" is simple enough with a script but getting this into a link that will open file explore is not that easy.
<!DOCTYPE html>
<html>
<body>
<button onclick="myFunction(25555)">Try it</button>
<p id="sagslink"></p>
<script>
function myFunction(sagnr) {
var a = Math.floor(sagnr/200)*200
var b = Math.floor(a+199);
var x = "file://///192.168.15.133/Filserver2016/sager/" + a + '-' + b + "/"+sagnr;
document.getElementById("sagslink").innerHTML = x;
}
</script>
Simple link that Works in IE..but not in firefox og chrome.
sager-full-path
But I can not generate a useful link merging the to!
I have tried evey possible way described here to no awail:
JavaScript function in href vs. onclick
Perhaps I need to revice the function to give the actual link in sted. I also don't what a button but just a generat CASE-Number...that serves as link!
Further more! We mount \\192.168.1.133\Fileserver2016 as Z:
So for our various programs, that use the Z drive path, I would like to open file-explore with the mount path and not the ablosoute path.
We can use IE if nessarry..but I would like i to work on firefox and chrome also
Can this be done!
Ok. So we got it working...sort of ;O)
Our intranet webpage runs in ASP
So the code runs serverside.
Here is the code that works in IE-11.
<%
strSagsNR = rsSag("sagsNR")
Function folderlink(FSagsNR)
a = int(strsagsNR/200)*200
b = int(a+199)
folderlink = "file:///Z:/sager/" & a & "-" & b & "/" & strSagsNR
End Function[enter image description here][1]
%>
To ensure the solution works properly locally and when connected with VPN.
It's necessary to add the server ip to IE-11 Internet security - local Intranet - Webplaces - Advanced
as BOTH FILE AND HTTP! See image.
Security setting in IE
Then you should avoid the remark about this file is dangerous and may harm you computer, and File explore will pop up on the correct path ;O)
I have not found any solution for Chrome or Firefox.

WP8 App misbehaving due to StreamWrite in JavaScript

I would like to save the results calculated on html page in a textfile using javascript.
<script type="text/javascript">
window.onload = function () {
var sw : StreamWriter = new StreamWriter("HTML_Results.txt");
sr.Write('xyz");
*** calculations ******
sr.Write (result);
}
</script>
by doing this, my WP8 App is misbehaving and not displaying images as usual. This app is an Image Fader (calculates FPS).
Also tried:
StreamWriter sr;
try {
sr = new StreamWriter("\HTML5\HTMLResults.txt");
sr.Write("xyz");
File.SetAttributes("HTML5\HTMLResults.txt", FileAttributes.Hidden);
} catch(IOException ex) {
console.write ("error writing"); //handling IO
}
The aim is to:
Extract calculated values of several html pages(after getting loaded
one by one) in a single text file.
A Resultant HTML that reads this
text file and displays results in a tabular format.
Is there a better way to this job or the above can be rectified and used? Appreciate help.
Perhaps I've misunderstood your code but it looks like you're trying to write Java within JavaScript scripting tags. You cannot write Java in an HTML document. As far as I know, client-side JavaScript (which given your <script> tags is I guess what you're trying to write) can't perform the kind of file I/O operations you seem to want here.
You need to use Node JS to use JavaScript for something like that and then you're talking server-side. The closest you can get on client-side is using the new localStorage feature in HTML5 (not supported by all browsers).

Set PDF page layout to "TwoPageLeft" using JavaScript (Acrobat Pro)

I would like to change (or add if it doesn't exist) to a PDF file with multiple pages the setting that will force the PDF to be opened in two page mode (PageLayout : TwoPageLeft for example).
I tried with that kind of JavaScript (given with Enfocus FullSwitch as example) :
if(($error == null) && ($doc != null))
{
try
{
$outfile = $outfolder + '/' + $filename + ".pdf";
$doc.layout = "TwoPageLeft";
$doc.saveAs( {cPath : $outfile, bCopy : true});
$outfiles.push($outfile);
}
catch(theError)
{
$error = theError;
$doc.closeDoc( {bNoSave : true} );
}
}
But it doesn't work as I would like (it will be opened with Acrobat Pro and saved as a new file without including the setting about the layout).
Does anyone can help me to correct that code to let JS open the PDF file, set the layout inside the PDF datas and save it out?
The readable information inside the PDF file should looks like this:
PageLayout/TwoPageLeft/Type/Catalog/ViewerPreferences
For information, I'm using FullSwitch (Enfocus) to handle files in a workflow, with Acrobat Pro, and at this time, it's only saving the file without adding the setting.
I can't find myself the answer over all the Web I searched recently, so I askā€¦
Thanks in advance!
I think you copied the "this.layout = ..." line out of the Acrobat JavaScript reference documentation, correct?
When you write a JavaScript for Switch to execute (or rather for Switch to instruct Acrobat to execute for you), you should use the "$doc" variable to refer to the document Switch is processing.
So try changing the line:
$this.layout = "TwoColumnLeft";
to
$doc.layout = "TwoColumnLeft";
As you say the rest of the code works and the document is saved without errors I assume the rest of your code is correct. The change proposed here will make the adjustment in the document you're looking for.

Generating HTML Canvas image data server-side?

The title of this question may be slightly misleading, but I'm not sure what the best title would be (since I can't guess at a solution yet).
Basically the system I am developing relies heavily on canvas graphs. These graphs are generated through javascript, and are made using data pulled via ajax from an API server.
The tricky part is, I'd like to be able to email these graphs to users of this system, without them actually having to go to the web page at all. So while I'm aware that it is possible to get the Base64 value of an image generated with javascript in a browser, what about if no one is there to run that javascript?
I'd like to keep the graphs generated in javascript/canvas, rather than making them in a common server-side graphics library (GD, ImageMagick). The Canvas graphs are dynamic, and allow for interaction via javascript. Though I don't want that functionality in the email notification, I do want them to be identical otherwise (at least in appearance).
So the question is, how can I get these graphs into an email?
At this point, my only guess is that I'd need to literally make a website that does AJAX requests for "graphs to render", renders these graphs, and sends the results to the server. Then I'd need a "server" that just sits there on that web page and churns out graphs. Is that the only solution here?
I used phantomJs (like node.js but different) serverside to run exactly the same code as client side, and get the same result. all you need is one single exe-file (like a webkit stand alone web brower)
The following program (in Perl, but should be feasible to translate to you favourite language) takes some data, inserts into a web-page (could be ajax'ed) and either sends that web page to the client, or stores it as a temporary file, and starts PhantomJs on the same page. Then ask PhantomJs to generate a jpg, that is then picked up (and in this case sendt to the client).
#!/usr/bin/perl
use strict;
use File::Temp;
$|=1;
#this script returns a graph, either as html +js web page to render client side,
#or renders the same page server side, and returns the jpg image.
#files needed:
#.\phantom_srv_client.pl #this script
#.\phantomjs.exe #the webkit runtime stand alone file, from http://phantomjs.org/
#.\Scripts\excanvas.min.js #canvas simulator for IE8-
#.\Scripts\jquery.min.js #jQuery as we know it
#.\Scripts\jquery.jqplot.min.js #graph library on top of jQuery from http://www.jqplot.com/ (Flot or any can be used)
#do we want client side rendering (html + js), or server side rendering (jpg)
#jpg seems to render nicer than png on some pages?
use CGI;
my $show_as_jpg = CGI::param("jpg");
#path to javascript libraries (jQuery etc).
#Must be absolute file location for server rendering, relative for web
use FindBin;
my $script_path = $show_as_jpg
? $FindBin::Bin."/Scripts"
: './Scripts';
#data to send to graph (two sets)
my $data = [[2,5,4], [6,4,5]];
#use json to get this as a javascript text
my $json_data;
eval {require JSON; $json_data=JSON::to_json($data)};
#in case JSON is not installed, get the json/javascript data manually (just for demo)
$json_data ||= "[[2,5,4], [6,4,9]]"; #here 9 at the end to see a difference
#The following is the web page that renders the graph, client or server side
#(links to scripts must be abolute to work serverside, as temp-files may go anywhere, $script_path keeps track of that)
#$json_data is the Perl data structure converted to JSON (aka javascript, but not)
my $graph_html =qq|
<!DOCTYPE html>
<html>
<head>
<!--[if lt IE 9]><script language="javascript" type="text/javascript" src="$script_path/excanvas.min.js"></script><![endif]-->
<script class="include" type="text/javascript" src="$script_path/jquery.min.js"></script>
<script class="include" type="text/javascript" src="$script_path/jquery.jqplot.min.js"></script>
<script class="code" type="text/javascript" language="javascript">
jQuery(document).ready(function(){
/*data from perl (\$json_data) inserted here */
var data = $json_data;
jQuery.jqplot("chart1", data );
});
</script>
</head>
<body>
<div id="chart1" style="width:600px; height:400px;"></div>
<a href='?jpg=1'>View as jpg</a>
</body>
</html>
|;
#this is the javascript that tells PhantomJs what to do (ie open a doc and render it to bitmap)
my $phantom_doc_js =qq|
var system = require('system');
//read from commandline which files to open, and write to
var open_doc = system.args[1];
var return_doc = system.args[2];
var page = require('webpage').create();
page.open(open_doc, function () {
page.render(return_doc);
phantom.exit();
});
|;
#see if we shall render this page serverside
if ($show_as_jpg) {
#get temporary filenames with related file handlers
#where to put phantomjs script (generic so could be a static file)
my ($phantom_doc_filehandler, $phantom_doc_filename) = File::Temp::tempfile( SUFFIX => '.js', TMPDIR => 1);
#where to put web page with data to render and ref to javascripts etc
my ($phantom_graph_filehandler, $phantom_graph_filename) = File::Temp::tempfile(SUFFIX => '.html', TMPDIR => 1);
#also get a filename with no handler, so phantomjs can return the jpg file. Extention must be .jpg!
my (undef, $image_filename) = File::Temp::tempfile( SUFFIX => '.jpg',TMPDIR => 1, OPEN => 0);
#store file content and close files
print $phantom_doc_filehandler $phantom_doc_js; close $phantom_doc_filehandler;
print $phantom_graph_filehandler $graph_html; close $phantom_graph_filehandler;
#now call PhantomJs with filenames to read from and write to.
#Next version should support piping, which would simplify a lot
#use absolute path to phantomjs.exe in case web-server does not use current path
system($FindBin::Bin.'\\phantomjs', $phantom_doc_filename, $phantom_graph_filename, $image_filename) == 0
or die "system failed: $?";
#read the entire image file
my $img = slurp_file($image_filename);
print "Content-Type: image/jpeg\nPragma: no-cache\n\n".$img;
#The temp files are no more needed
unlink $phantom_doc_filename, $phantom_graph_filename, $image_filename;
} else { # just render client side
print "Content-Type: text/html\nPragma: no-cache\n\n".$graph_html;
}
#slurp is not always std perl
sub slurp_file{
my $filename = shift;
my $string;
local $/ = undef;
open FILE, $filename or die "Couldn't open file: $!";
binmode FILE;
$string = <FILE>;
close FILE;
return $string;
}

Categories