Printing base64 PDF using PDF.JS on document load - javascript

I am trying to print a pdf with PDF.js but currently I cannot get the document data rendered in the pdf element. This is what it looks like right now:
So, no data is being rendered.
This is the code behind:
<script src="jquery-2.2.4.min.js"></script>
<script type="text/javascript" src="pdf.js"></script>
<script type="text/javascript" src="pdf.worker.js"></script>
<body id="printbody" style="margin:0px;">
</body>
<script type="text/javascript">
var pdfData = atob('JVBERi0xLjQK...'); //Shortened
PDFJS.workerSrc = 'pdf.worker.js';
PDFJS.getDocument({data: pdfData}).then(function RenderAndPrint(res) {
var src = URL.createObjectURL(new Blob([res], { type: 'application/pdf' }))
var printFrame = document.createElement('iframe');
printFrame.id = 'print-frame';
//printFrame.style.display = 'none';
printFrame.style.width = '100%'
printFrame.style.height = '100%'
printFrame.style.border = 'none'
printFrame.src = src;
document.body.appendChild(printFrame);
setTimeout(function () {
printFrame.contentWindow.print();
}, 0)
});
</script>
The final goal is to have this entire page appended to an existing page via AJAX so the as soon as the this page is appended and renders the PDF, the iframe (which would be hidden) would print the pdf as soon as it renders and then eventually dispose of itself.

I was using itextsharp, I instead saved the pdf to the local system, set it to print on open like so:
PdfAction print = new PdfAction(PdfAction.PRINTDIALOG);
writer.SetOpenAction(print);
and then used an iframe to render the pdf by setting the file to the src

Related

Adding and running external javascript file in new window.open()

I want adding and running external javascript file in new window.open() , so I tested the solution in Running Javascript in new window.open , but this solution doesn't work.
My code is here :
<input type="button" value="Open a window" onclick="openWindow();">
<script type="text/javascript">
function openWindow()
{
//Open a new window :
var win = window.open("");
//Create script tag :
var script = document.createElement('script');
//Add external javascript file in src attribut of script tag :
script.src = "script.js";
//Append script tag to the new window :
win.document.head.appendChild(script);
}
</script>
The content of external javascript file called script.js is :
alert("It works !");
When you click the button, a new window is opened, but the external javascript file added is not executed.
So how to run the external javascript file added in new window opened ?
Use document.write
const win = window.open('')
win.document.open()
const html = `
<html>
<head>
<script src="https://code.jquery.com/jquery-2.2.4.min.js"><\/script>
</head>
<body>
<h1>Test</h1>
<script>alert($('h1').text())<\/script>
</body>
</html>
`
win.document.write(html)
win.document.close()
Try this
<script type="text/javascript">
function openWindow()
{
//Open a new window :
var win = window.open("");
//Create script tag :
var script = document.createElement('script'),
div = document.createElement('div');
//Add external javascript file in src attribut of script tag :
script.src = "https://cdnjs.cloudflare.com/ajax/libs/preact/8.3.1/preact.min.js";
script.type = "application/javascript";
script.defer = true;
div.appendChild(script);
win.document.body.appendChild(div);
}
</script>
In the new window open developer console and type preact you will see output like {h: ƒ, createElement: ƒ, cloneElement: ƒ, Component: ƒ, render: ƒ, …}

script in HTML string is not executed when passed via JSON

This is a follow-up question of this one.
Goal is to use some user input that is converted to a HTML document that should be displayed in a new tab (that's answered in the link above).
Problem is, however, that - if the HTML document contains <script> tags - those are not executed when this HTML string is passed as JSON. Below I use a simple string:
'<!DOCTYPE html><title>External html</title><div>Externally created</div><script>alert("WORKING");</script>'
This is a minimal example to illustrate the problem (you will see this in your browser when you load the HTML from below):
When I click on the button, the new tab is opened but the script is not executed i.e. there is no alert shown. By clicking on the alert link, the html string is loaded directly and the alert is shown correctly.
My question is, how to postprocess the HTML string that is returned from .getJSON to execute the script correctly. Currently I do it like this (entire code can be found below):
$.get('/_process_data', {
some_data: JSON.stringify('some data'),
}).success(function(data) {
var win = window.open("", "_blank");
win.document.body.innerHTML = data;
})
This is my code:
<!DOCTYPE html>
<html lang="en">
<head>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css">
</head>
<body>
<div class="container">
<div class="header">
<h3 class="text-muted">Get new tab!</h3>
</div>
<button type="button" id="process_input">no alert</button>
<a href="/html_in_tab" class="button" target='_blank'>alert</a>
</div>
<script src="https://code.jquery.com/jquery-1.12.4.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function() {
$('#process_input').bind('click', function() {
$.get('/_process_data', {
some_data: JSON.stringify('some data'),
}).success(function(data) {
var win = window.open("", "_blank");
win.document.body.innerHTML = data;
})
return false;
});
});
</script>
</body>
</html>
and the flask file:
from flask import Flask, render_template, request, jsonify
import json
# Initialize the Flask application
app = Flask(__name__)
#app.route('/html_in_tab')
def get_html():
# provided by an external tool
# takes the user input as argument (below mimicked by a simple string concatenation)
return '<!DOCTYPE html><title>External html</title><div>Externally created</div><script>alert("WORKING");</script>'
#app.route('/_process_data')
def data_collection_and_processing():
# here we collect some data and then create the html that should be displayed in the new tab
some_data = json.loads(request.args.get('some_data'))
# just to see whether data is retrieved
print(some_data)
# oversimplified version of what actually happens; get_html comes from an external tool
my_new_html = get_html() + '<br>' + some_data
print(my_new_html)
# this html should now be displyed in a new tab
return my_new_html
#app.route('/')
def index():
return render_template('index_new_tab.html')
if __name__ == '__main__':
app.run(debug=True)
I think you need something like this:
var win = window.open("", "_blank",);
win.document.write('<!DOCTYPE html><title>External html</title><div>Externally created</div><script>(function(){alert(1);})();</script>');
when you open the popup, this executes JavaScript. You could add data and do whatever you want inside <script>(function(){alert(data);})();</script>
After the HTML has been added to the page, you could execute a function to run it. This would require wrapping your scripts with functions like this:
function onStart() {
// Your code here
}
Then after the HTML is added to the page, run the function:
$.get('/_process_data', {
some_data: JSON.stringify('some data'),
}).success(function(data) {
var win = window.open("", "_blank");
win.document.body.innerHTML = data;
onStart();
})
Instead of...
var win = window.open("", "_blank");
win.document.body.innerHTML = data;
Use jquery to load the html and wait for loading to complete:
$.get('/_process_data', {
some_data: JSON.stringify('some data'),
}).success(function(data) {
var w = window.open("", "_blank");
$(w.document.body).load(data, function () {
//execute javascript here
});
})

Upload Javascript file using variables

EDIT:
I do not want to save to a text file.... I want the user to be able to select their own file and use the variables within that file.
I would like to have the user upload their own "settings.js" file and then the page use the variables once loaded.
How would I change my code to reflect this?
At present I have the following javascript file and HTML code:
Javascript File: settings.js
var myVariable = 6000;
HTML file: index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Load Javascript file</title>
</head>
<body>
<script src="settings.js"></script>
<div>
<script>
alert(myVariable)
</script>
</div>
</body>
</html>
Please help.
something like this maybe
document.getElementById("settings").addEventListener("change", function(){
if(this.files[0] && this.files[0].type == "text/javascript"){
var reader = new FileReader();
reader.onload = function (e) {
var settings = e.target.result.split("data:text/javascript;base64,")[1];
eval(atob(settings));
//use the loaded var's
document.getElementById("result").innerText = myVariable;
}
reader.readAsDataURL(this.files[0]);
}
});
<input type="file" id="settings">
<div id="result"></div>
Here is a full working code for you.
It will read file and print it as text for debugging on the screen and will add the file as script file to the page as well.
<!DOCTYPE HTML>
<html>
<head>
<script>
function loadScript() {
var inputFile = document.querySelector("#scriptFile"),
// Get the selected file
file = inputFile.files[0],
// HTML5 File API
fileReader = new FileReader();
// Add the onload event to the file
fileReader.onload = printFile;
// Read the file as text
fileReader.readAsText(file);
function printFile( reader ) {
// Get the text of the file
var content = reader.target.result,
script;
// Add the fileContent as script to the page
script = document.createElement('script');
script.textContent = content;
document.body.appendChild(script);
///////////////// DEBUG
var pre = document.createElement('pre');
pre.textContent = content;
document.body.appendChild(pre);
}
}
</script>
</head>
<body>
<input type='file' id='scriptFile'>
<input type='button' value='Load' onclick='loadScript();'>
</body>
</html>
This code will run javascript stored in your JS file. Use FileReader() to read file as text, and use eval(content); to execute that code. If you can execute JavaScript you can do anything you want. Use only variables, or anything else.
var fileInput = document.getElementById('fileInput');
var fileDisplayArea = document.getElementById('fileDisplayArea');
fileInput.addEventListener('change', function(e) {
var file = fileInput.files[0];
var textType = /text.*/;
if (file.type.match(textType)) {
var reader = new FileReader();
reader.onload = function(e) {
var content = reader.result;
//Here the content has been read successfuly
eval(content);
}
reader.readAsText(file);
} else {
document.innerText = "File not supported!"
}
});
<input type="file" id="fileInput">

Customize DocxJS to render local docx file

I just found a working docx to html converter using only javascript on github. The main code which converts docx to html is below. The issue is the page just has a button which on click or drag and choosing a word document, opens it as html. I want to specify a file location in the code so I can load it on the server for loading some documents from computer locally.
Code which converts docx to html and renders :
<html lang="en">
<head>
<meta charset="UTF-8">
<title>DocxJS Example</title>
<script type="text/javascript" src="https://code.jquery.com/jquery-2.2.4.min.js"></script>
<script type="text/javascript" src="https://www.docxjs.com/js/build/latest.docxjs.min.js"></script>
</head>
<body>
<input id="inputFiles" type="file" name="files[]" multiple="false">
<div id="loaded-layout" style="width:100%;height:800px;"></div>
<script>
$(document).ready(function(){
var $inputFiles = $('#inputFiles');
$inputFiles.on('change', function (e) {
var files = e.target.files;
var docxJS = new DocxJS();
docxJS.parse(
files[0],
function () {
docxJS.render($('#loaded-layout')[0], function (result) {
if (result.isError) {
console.log(result.msg);
} else {
console.log("Success Render");
}
});
}, function (e) {
console.log("Error!", e);
}
);
});
});
</script>
</body>
</html>
I tried changing var files = e.target.files; to var files = "C:/sda/path/to/docx"; but that didn't help.
I tried to change
var files = e.target.files;
to
var files = new Array(new File([""], "sample.docx"));
but it gives me OOXML parse error.
Update:
Lets say I have a file location variable in PHP and I wish to use that instead in the javascript code. How do I do it?
I also checked docx2html javascript code and here is the code for it:
<!DOCTYPE html>
<html>
<head>
<script src="index.js"></script>
<script>
function test(input){
require("docx2html")(input.files[0]).then(function(converted){
text.value=converted.toString()
})
}
</script>
</head>
<body>
<input type="file" style="position:absolute;top:0" onchange="test(this)">
<br/>
<br/>
<textarea id="text"></textarea>
</body>
</html>
Same issue need input.files[0] here as well
Update:
I am trying to use the method mentioned in the comments but encounter some errors:
var fil;
var getFileBlob = function (url, cb) {
var xhr = new XMLHttpRequest();
xhr.open("GET", url);
xhr.responseType = "blob";
xhr.addEventListener('load', function() {
cb(xhr.response);
});
xhr.send();
};
var blobToFile = function (blob, name) {
blob.lastModifiedDate = new Date();
blob.name = name;
return blob;
};
var getFileObject = function(filePathOrUrl, cb) {
getFileBlob(filePathOrUrl, function (blob) {
cb(blobToFile(blob, 'test.docx'));
});
};
getFileObject('demo.docx', function (fileObject) {
console.log(fileObject);
fil = fileObject;
});
The error primarily was “Cross origin requests are only supported for HTTP.” before I used https://calibre-ebook.com/downloads/demos/demo.docx instead of just demo.docx in above file path. This however gives another error:
Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https, chrome-extension-resource.
which means chrome cannot load it. It needs to be working on a server. If someone can help providing a fix to make it work offline, let me know. The last method was asynchronous call.
In the browser, there is a sandbox policy.
It can not access files directly via Path.
Please access the file through drag & drop event or input file change event.

Javascript - Reading file in client directory

I'm a new programmer that learn javascript, Im new in js actually.
I have a task that require a web page able to read file in client directory. I've got some js code :
<html>
<script type="text/javascript">
function ReadWeight() {
var filePath = "file:///D:/Text.txt";
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET",filePath,false);
xmlhttp.send(null);
var fileContent = xmlhttp.responseText;
alert(fileContent);
}
ReadWeight();
</script>
<body>
</body>
</html>
When I save this code in my directory and access it by this link, It works well.
file:///D:/test.html
But when I put it in my localhost and I access it, the JS doesn't works.
Does my code incorrect when in web server?
Please help me out.
Might I suggest using an error console to display the error so people know how to help you? =] And paste it in your query
Download something like firebug and see if a request is being made (for FireFox)
It looks like you would rather want to access the file via the http:// protocol, instead of file://
As far as I know you can only read client files using an <input type="file"> element. Once you get the file you can read it multiple times:
HTML:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>File Refresh</title>
<script src="filerefresh.js"></script>
</head>
<body>
<input id="fileInput" type="file">
<pre id="fileDisplay"></pre>
</body>
</html>
JavaScript:
(function() {
var sleepInterval = 1000; // 1 second
var fileInput;
var fileDisplay;
var reader;
var id = undefined;
function initialize() {
fileInput = document.getElementById("fileInput");
fileDisplay = document.getElementById("fileDisplay");
reader = new FileReader();
reader.onloadend = function() {
fileDisplay.innerHTML = reader.result;
reschedule();
};
fileInput.addEventListener("change", readFile);
}
function reschedule() {
if (id !== undefined) {
clearTimeout(id);
}
id = setTimeout(readFile, sleepInterval);
}
function readFile() {
reader.readAsText(fileInput.files[0]);
}
window.onload = initialize;
})();

Categories

Resources