Print from WebView by setting Paper size Javafx - java

I am generating HTML dynamically for invoices and use WebView to show previews. And to print those invoices.
But when I try to set the Page width by manually creating a Paper Object from PrintHelper Class which I know is not a good idea but there is no other option as I have to specify the page width as 88mm for thermal printers, the result of this process comes as this.
which clearly shows a significant margin on the left. But this is not the case if the width of the Paper is >= 90mm. see this
HTML Page
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<p>This is a really long text to show the width and the margins of page printed on PDF</p>
</body>
</html>
Java code to generate PDF
public void printPDF(Window window, WebEngine engine) {
var printerJob = PrinterJob.createPrinterJob();
if (printerJob == null) return false;
boolean success = printerJob.showPrintDialog(window);
var jobSetting = printerJob.getJobSettings();
var paper = PrintHelper.createPaper("Thermal88mm", 88, 300, Units.MM);
jobSetting.setPageLayout(printerJob.getPrinter().createPageLayout(paper, PageOrientation.PORTRAIT, Printer.MarginType.HARDWARE_MINIMUM));
if (success) {
engine.print(printerJob);
printerJob.endJob();
}
}
I hope anyone can help me.

Related

Use ACE Editor for Java Language in web

I wish to make an online java editor like ideone.com
I wish to use https://ace.c9.io/#nav=about&api=anchor to make my tool.
I have used codeEditor.session.setMode("ace/mode/java"); but stil my tool does not compile java language.
Till now my code is :
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="lib/css/editor-styles.css">
<title>Online Test</title>
</head>
<body>
<div class="editor">
<div class="editor__wrapper">
<div class="editor__body">
<div id="editorCode" class="editor__code"></div>
</div>
<div class="editor__footer">
<div class="editor__footer--left">
<button class="editor__btn editor__run">Run ></button>
<button class="editor__btn editor__reset">Reset ></button>
</div>
<div class="editor__footer--right">
<div class="editor__console">
<ul class="editor__console-logs"></ul>
</div>
</div>
</div>
</div>
</div>
<!-- Required Ace Libraries -->
<script src="lib/js/ace-editor/src-min/ace.js"></script>
<script src="lib/js/ace-editor/src-min/mode-javascript.js"></script>
<script src="lib/js/ace-editor/src-min/ext-language_tools.js"></script>
<!-- Custom Scripts -->
<script src="lib/js/editor.js"></script>
<script src="lib/js/editor-console.js"></script>
</body>
</html>
// Retrieve Elements
const consoleLogList = document.querySelector('.editor__console-logs');
const executeCodeBtn = document.querySelector('.editor__run');
const resetCodeBtn = document.querySelector('.editor__reset');
Building a Code Editor for the Web - Configuring Ace Editor
Building a Code Editor for the Web - Configuring Ace Editor
JS FILE
// Setup Ace
let codeEditor = ace.edit("editorCode");
let defaultCode = 'console.log("Editor")';
let consoleMessages = [];
let editorLib = {
clearConsoleScreen() {
consoleMessages.length = 0;
// Remove all elements in the log list
while (consoleLogList.firstChild) {
consoleLogList.removeChild(consoleLogList.firstChild);
}
},
printToConsole() {
consoleMessages.forEach(log => {
const newLogItem = document.createElement('li');
const newLogText = document.createElement('pre');
newLogText.className = log.class;
newLogText.textContent = `> ${log.message}`;
newLogItem.appendChild(newLogText);
consoleLogList.appendChild(newLogItem);
})
},
init() {
// Configure Ace
// Theme
codeEditor.setTheme("ace/theme/monokai");
// Set language
codeEditor.session.setMode("ace/mode/java");
// Set Options
codeEditor.setOptions({
fontFamily: 'Inconsolata',
fontSize: '12pt',
enableBasicAutocompletion: true,
enableLiveAutocompletion: true,
});
// Set Default Code
codeEditor.setValue(defaultCode);
}
}
// Events
executeCodeBtn.addEventListener('click', () => {
// Clear console messages
editorLib.clearConsoleScreen();
// Get input from the code editor
const userCode = codeEditor.getValue();
// Run the user code
try {
new Function(userCode)();
} catch (err) {
console.error(err);
}
// Print to the console
editorLib.printToConsole();
});
resetCodeBtn.addEventListener('click', () => {
// Clear ace editor
codeEditor.setValue(defaultCode);
// Clear console messages
editorLib.clearConsoleScreen();
})
editorLib.init();
How to add compile feature to it?
Hypothetically ... you get your editor to send the source code to a server that has a Java compiler installed and you run it.
If your app's server side is implemented in Java, you could make use of Java's runtime compilation APIs. See How do I programmatically compile and instantiate a Java class?. (Skip over the part about loading and running the compiled code ... unless you want to do that too.)
Ace is an editor, not a compiler.
You can't use it to compile code.
Ideone use Sphere Engine Compilers to compile...
Refer this documentation : link

how to unescape html entities **except** < > & " &apos; in java

I have html input in utf-8. In this input accented characters are presented as html entities. For example:
<html>
<head>
<META http-equiv="Content-Type" content="text/html; charset=utf-8">
</head>
<body>árvíztűrő<b</body>
</html>
My goal is to "canonicalize" the html by replacing html entities with utf-8 characters where possible in Java. In other words, replace all entities except < > & " &apos;.
The goal:
<html>
<head>
<META http-equiv="Content-Type" content="text/html; charset=utf-8">
</head>
<body>árvíztűrő<b</body>
</html>
I need this to make it easier to compare htmls in tests, and to be easier to read for the naked eye (lots of escaped accented characters makes it very hard to read).
I don't care cdata sections (there's no cdata in the inputs).
I have tried JSOUP (https://jsoup.org/) and Apache's Commons Text (https://commons.apache.org/proper/commons-text/) unsuccessfully:
public void test() throws Exception {
String html =
"<html><head><META http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\">" +
"</head><body>árvíztűrő<b</body></html>";
// this is not good, keeps only the text content
String s1 = Jsoup.parse(html).text();
System.out.println("s1: " + s1);
// this is better, but it unescapes the < which is not what I want
String s2 = StringEscapeUtils.unescapeHtml4(html);
System.out.println("s2: " + s2);
}
The StringEscapeUtils.unescapeHtml4() is almost what I need, but it unfortunately unescapes the < also:
<body>árvíztűrő<b</body>
How should I do it?
Here is a minimal demonstration: https://github.com/riskop/html_utf8_canon.git
Looking into the Commons Text source it is clear that StringEscapeUtils.unescapeHtml4() delegates work to an AggregateTranslator, which is composed of 4 CharSequenceTranslator:
new AggregateTranslator(
new LookupTranslator(EntityArrays.BASIC_UNESCAPE),
new LookupTranslator(EntityArrays.ISO8859_1_UNESCAPE),
new LookupTranslator(EntityArrays.HTML40_EXTENDED_UNESCAPE),
new NumericEntityUnescaper()
);
I need only three of the translators to fullfill my goal.
So this is it:
// this is what I needed!
String s3 = new AggregateTranslator(
new LookupTranslator(EntityArrays.ISO8859_1_UNESCAPE),
new LookupTranslator(EntityArrays.HTML40_EXTENDED_UNESCAPE),
new NumericEntityUnescaper()
).translate(html);
System.out.println("s3: " + s3);
Whole method:
#Test
public void test() throws Exception {
String html =
"<html><head><META http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\">" +
"</head><body>árvíztűrő<b</body></html>";
// this is what I needed!
CharSequenceTranslator UNESCAPE_HTML_EXCEPT_BASIC = new AggregateTranslator(
new LookupTranslator(EntityArrays.ISO8859_1_UNESCAPE),
new LookupTranslator(EntityArrays.HTML40_EXTENDED_UNESCAPE),
new NumericEntityUnescaper()
);
String s3 = UNESCAPE_HTML_EXCEPT_BASIC.translate(html);
System.out.println("s3: " + s3);
}
Result:
<html>
<head>
<META http-equiv="Content-Type" content="text/html; charset=utf-8">
</head>
<body>árvíztűrő<b</body>
</html>

How to Capture Image using Web Camera in JSP only (Without using Servlet) and save it into MS SQL Server

I want to capture the image using web camera and store it into MS SQL Server database.
I am able to capture the image using web camera but right now i am trying to pass the image to next page but could not get the image on next jsp to process the image.
Code to capture image
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Web camera - Testing</title>
<script>
// Put event listeners into place
window.addEventListener("DOMContentLoaded", function () {
// Grab elements, create settings, etc.
var canvas = document.getElementById("canvas"),
context = canvas.getContext("2d"),
video = document.getElementById("video"),
videoObj = {"video": true},
errBack = function (error) {
console.log("Video capture error: ", error.code);
};
// Put video listeners into place
if (navigator.getUserMedia) { // Standard
navigator.getUserMedia(videoObj, function (stream) {
video.src = stream;
video.play();
}, errBack);
} else if (navigator.webkitGetUserMedia) { // WebKit-prefixed
navigator.webkitGetUserMedia(videoObj, function (stream) {
video.src = window.webkitURL.createObjectURL(stream);
video.play();
}, errBack);
} else if (navigator.mozGetUserMedia) { // WebKit-prefixed
navigator.mozGetUserMedia(videoObj, function (stream) {
video.src = window.URL.createObjectURL(stream);
video.play();
}, errBack);
}
// Trigger photo take
document.getElementById("snap").addEventListener("click", function () {
context.drawImage(video, 0, 0, 213, 160);
document.getElementById('canvasImg').src = canvas.toDataURL("image/png");
// document.getElementById('video').style.display = "none"; // hide the live image video portin after click on take picture
});
}, false);
</script>
</head>
<body>
<h1>Capture Image using Camera!</h1>
<!--
Ideally these elements aren't created until it's confirmed that the
client supports video/camera, but for the sake of illustrating the
elements involved, they are created with markup (not JavaScript)
-->
<video id="video" width="213" height="160" autoplay></video>
<button id="snap">Capture Photo</button>
<form action="savetesting.jsp" method="post">
<canvas id="canvas" width="213" height="160" name="ImageFile1" style="display: none;"></canvas>
<img id="canvasImg" name="ImageFile"><img>
<input type="reset" value="Reset"/>
<input type="submit" value="Submit"/>
</form>
</body>
</html>
but now i am trying to get the captured image using
request.getParameter("ImageFile");
but could not succeed.
Please help me out with this issue, How to get the image on next page then i will try to save the image in MS SQL Server Database but only using JSP (without using Servlet).
Neither canvas nor img are form input fields, even when placed inside form tag. Add
<input type="hidden" name="ImageData" id="ImageData" />
to your form, and
document.getElementById('ImageData').value = canvas.toDataURL("image/png");
to the click event handler of the snap button.
Then, in JSP, get the image data (in the data URI format) using
String imageData = request.getParameter("ImageData");
and process them using javax.xml.bind.DatatypeConverter as described in Convert DataURL image to image file in java

How to take value from div in Java Script and sort to it?

I am making an application that receive data from servlet to jsp page.
I have used List<> mechanism to store and retrieve data.
So I have used one time a html design code and embed it into for loop that display data untill List<> data end.
I want to sort data retrieved data on jsp page using java script but how to get value of that retrieved data in Java Script I don't know.
My JSP Code :
<div class="listinggitems">
<%
List<Integer> prdIDList = (List<Integer>)request.getAttribute("prodID");
List<String> prdNAMEList = (List<String>)request.getAttribute("prodNAME");
List<String> prdIMAGEList = (List<String>)request.getAttribute("prodIMAGE");
List<Float> prdPRICEList = (List<Float>)request.getAttribute("prodPRICE");
List<String> prdFEATUREList = (List<String>)request.getAttribute("prodFEATURE");
for(int i = 0;i < prdIDList.size();i++)
{
Integer prdID = prdIDList.get(i);
String prdNAME = prdNAMEList.get(i);
String prdIMAGE = prdIMAGEList.get(i);
Float prdPRICE = prdPRICEList.get(i);
String prdFEATURE = prdFEATUREList.get(i);
%>
<div class="mainitemlist">
<div class="mainitemlistimage"><div align="center"> <img src="product_images/<%= prdIMAGE %>" height="125px" width="100px"></div></div>
<div class="mainitemlistname">
<div align="center"><%= prdNAME %></div>
</div>
<div class="mainitemlistprice">
<div align="center"><%= prdPRICE %></div>
</div>
<div class="mainitemlistfeatures"><div align="center"><%= prdFEATURE %></div></div>
</div>
<%
}
%>
</div>
I have taken 2 buttons:
1 for to sort data as per price,
2 for to sort data as per name.
When user click on button it calls Java Script Function to Sort data.
But how to get all data into Java Script for to sort I don't know.
Anyone will guide me, how to do that ?
I strongly believe that the most appropriate solution to this issue is the use of AJAX as suggested by Hussain Akhtar Wahid failing that my suggestion to convert the product data to a JSON object and pass that to a JavaScript function would allow you to use mainly JavaScript. However if you must use nothing more than the request object and JavaScript then I have a solution for you.
In short, you must get the product data from the request object into a JavaScript object. This is possible but it not a pretty. Then once the product data is in the JavaScript object you can sort it using a custom sort function in JavaScript.
Here is your modified JSP code: ShowProduct.jsp
<%# page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>
<%# page import="java.util.*"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html><head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Product Catalogue</title>
<link rel="stylesheet" type="text/css" href="sortList/layout.css" />
<script type="text/javascript" src="sortList/sort.js"></script>
<script type="text/javascript">
//Puts the products into the product array of the catalogue object
<%
List<Integer> prdIDList = (List<Integer>) request.getAttribute("prodID");
List<String> prdNAMEList = (List<String>) request.getAttribute("prodNAME");
List<String> prdIMAGEList = (List<String>) request.getAttribute("prodIMAGE");
List<Float> prdPRICEList = (List<Float>) request.getAttribute("prodPRICE");
List<String> prdFEATUREList = (List<String>) request.getAttribute("prodFEATURE");
for (int i = 0; i < prdIDList.size(); i++) {
Integer prdID = prdIDList.get(i);
String prdNAME = prdNAMEList.get(i);
String prdIMAGE = prdIMAGEList.get(i);
Float prdPRICE = prdPRICEList.get(i);
String prdFEATURE = prdFEATUREList.get(i);
%>
catalogue.product[<%=i%>] = {pId:<%=prdID%>, pImage:"<%=prdIMAGE%>", pName:"<%=prdNAME%>", pPrice:<%=prdPRICE%>, pFeature:"<%=prdFEATURE%>"};
<%
}
%>
</script></head>
<body onload="catalogue.sortByName()">
<button onclick="catalogue.sortById()">Sort By Id</button>
<button onclick="catalogue.sortByName()">Sort By Name</button>
<button onclick="catalogue.sortByPrice()">Sort By Price</button>
<div id="container"><div id="mainitemlist"></div></div>
</body></html>
A lot of changes to go over so I will be brief. Two major changes.
Instead of displaying the product data immediately I cycle through the lists and put the data into a JavaScript array of objects. The array is call product and is a property of the catalogue literal object. See the JavaScript file below.
catalogue.product[<%=i%>] = {pId:<%=prdID%>, pImage:"<%=prdIMAGE%>", pName:"<%=prdNAME%>", pPrice:<%=prdPRICE%>, pFeature:"<%=prdFEATURE%>"};
I have created a div into which to insert the product data once it is sorted.
<div id="container"><div id="mainitemlist"></div></div>
I have also created three buttons that sort the product data
<button onclick="catalogue.sortById()">Sort By Id</button>
<button onclick="catalogue.sortByName()">Sort By Name</button>
<button onclick="catalogue.sortByPrice()">Sort By Price</button>
I have created a JavaScript file called sort.js which sorts and displays the product data.
// The catalogue literal object
var catalogue = {
sortDirection: -1, // The direction of the sort
product: [], // The product list generated by the JSP
// Sorts the products by their ID
sortById: function sortById() {
catalogue.product.sort(function(a, b) {
return catalogue.sortDirection * (a.pId - b.pId);
});
catalogue.sortDirection *= -1;
catalogue.display();
},
// Sorts the products by their NAME
sortByName: function sortByName() {
catalogue.product.sort(function(a, b) {
var result = 0;
var nameA = a.pName.toLowerCase(), nameB = b.pName.toLowerCase();
if (nameA < nameB) {
result = -1;
} else if (nameA > nameB) {
result = 1;
} else {
result = 0;
}
return catalogue.sortDirection*result;
});
catalogue.sortDirection *= -1;
catalogue.display();
},
// Sorts the products by their PRICE
sortByPrice: function sortByPrice() {
catalogue.product.sort(function(a, b) {
return catalogue.sortDirection * (a.pPrice - b.pPrice);
});
catalogue.sortDirection *= -1;
catalogue.display();
},
// Displays the sorted products
display: function display(){
var node = document.getElementById('container');
while (node.hasChildNodes()) {
node.removeChild(node.firstChild);
}
var html = "";
for(var i = 0; i < catalogue.product.length; i++){
var tableRow = new catalogue.tableRow(catalogue.product[i]);
html += tableRow.generateHTML();
}
document.getElementById('container').innerHTML = html;
},
// Contructor object for the table row
tableRow: function tableRow(product){
this.id = product.pId;
this.image = product.pImage;
this.name = product.pName;
this.price = product.pPrice;
this.feature = product.pFeature;
var image = "<div id='mainitemlist'><div id='mainitemlistimage'><a href='product?pid=prdID'><img src='product_images/prdIMAGE'></a></div>";
var name = "<div id='mainitemlistname'><a href='product?pid=prdID'>prdNAME</a></div>";
var price = "<div id='mainitemlistprice'>prdPRICE</div>";
var features = "<div id='mainitemlistfeatures'>prdFEATURE</div></div>";
this.generateHTML = function generateHTML(){
html = "";
html += image.replace("prdIMAGE", this.image).replace("prdID", this.id);
html += name.replace("prdNAME", this.name).replace("prdID", this.id);
html += price.replace("prdPRICE", this.price);
html += features.replace("prdFEATURE", this.feature);
return html;
};
}
};
This script creates a catalogue literal object that contains all the properties and methods necessary to sort and display the product data.
There are three sort functions: sortById, sortByName and sortByPrice. Each implements a custom sort. I wont explain how custom sort works in as there are many article on the internet that explain it very well.
In order for the sort to be bidirectional (sorts alternate low to high on clicking the sort button) I use the sortDirection variable that alternates its value between 1 and -1. This controls the direction of the sort.
The display method produces the output to the screen by passing each product object in the product array to the constructor of the tableRow constructor object. Then by calling the generateHTML() method on this object the HTML for each row is generated.
This an example of the template that is used to generate the HTML:
var name = "<div id='mainitemlistname'>
<a href='product?pid=prdID'>prdNAME</a></div>";
This method replaces the place holders prdID and prdName with the real values, obtained from the product and returns a string of HTML to the display method. Then this HTML in inserted into the ShowProduct DOM by setting the innerHTML property.
This JavaScript can be improved substantially nevertheless you have some code that gives you a rough solution to your issue. But I must reiterate that this is not the best way to tackle this issue, especially as you are using scriptlets which I am sure you know are taboo.
EDIT: Its missing the CSS, see below. Save it in a file called layout.css and import is in the HEAD elements of the HTML like so: <link rel="stylesheet" type="text/css" href="sortList/layout.css" />
div#mainitemlist{
float: left;
width: 100%;
}
div#mainitemlistimage {
float: left;
width: 200px;
}
div#mainitemlistimage img{
height: 125px;
width: 100px;
}
div#mainitemlistname{
float: left;
width: 200px;
}
div#mainitemlistname a{
color: #9caeb9;
text-decoration: none;
}
div#mainitemlistprice{
float: left;
width: 200px;
}
div#mainitemlistfeatures{
float: left;
width: 200px;
}

on click show Iframe

I have a map that you can click on locations to get information for that area and I would like to show that information in a Iframe on the same page when clicked
My page has this for the link now
`<AREA SHAPE="CIRCLE" COORDS="555,142,6" HREF="http://www.Page.com" TITLE="" />`
Any suggestions
The beauty of AJAX is that you don't really need an IFRAME to do this.
You've got a server that will return to you information about a certain area. Each of the AREA tags simply needs an onclick attribute that calls a JavaScript function to retrieve that information and display it in a location you set aside on your page.
Here is a sample HTML page that will retrieve information from the server using AJAX
<html>
<head>
<script type="text/javascript">
function getAreaInfo(id)
{
var infoBox = document.getElementById("infoBox");
if (infoBox == null) return true;
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if (xhr.readyState != 4) return;
if (xhr.status != 200) alert(xhr.status);
infoBox.innerHTML = xhr.responseText;
};
xhr.open("GET", "info.php?id=" + id, true);
xhr.send(null);
return false;
}
</script>
<style type="text/css">
#infoBox {
border:1px solid #777;
height: 400px;
width: 400px;
}
</style>
</head>
<body onload="">
<p>AJAX Test</p>
<p>Click a link...
Area One
Area Two
Area Three
</p>
<p>Here is where the information will go.</p>
<div id="infoBox"> </div>
</body>
</html>
And here is the info.php that returns the information back to the HTML page:
<?php
$id = $_GET["id"];
echo "You asked for information about area #{$id}. A real application would look something up in a database and format that information using XML or JSON.";
?>
Hope this helps!

Categories

Resources