PDF Javascript message from PDF to HTML document is not delivered - javascript

I'm trying to get my PDF javascript embedded code to communicate to its HTML container page. But I've been able to make it work only 1 way(HTML->PDF)
Maybe the problem is that the object tag is being generated dynamically( because I need to load pdfs on-the-fly)
js in my pdf file(runs in the OPEN action):
this.hostContainer.messageHandler =
{
onMessage: function(messageArray)
{
app.alert('msg received' + messageArray);
},
onError: function(error, messageArray){ },
onDisclose: function() {return true;}
};
try{
this.hostContainer.postMessage(["never", "delivered"]); // this line doesn't work. :(
}
catch(e){
app.alert(e.message);
}
my html page js code :
function messageFunc(messageArray) {
alert('finally!!');
}
$j('#pdf_div').html("<object type='application/pdf' data='http://url.to.dinamically.generated.pdf' id='PdfObject'> </object>");
$j("#PdfObject").ready(function() {
document.getElementById('PdfObject').messageHandler = { onMessage: messageFunc };
});
As I said, the PDF can receive the messages without problems, but I'm unable to send messages from the PDF to HTML code.
Btw, I'm using JQuery.
Any help would be really appreciated.
Thanks.

Related

Localization of static HTML with i18next (loading local json translation files)

My project is HTML only. I am not going to use node or react version.
I've tried default example that works fine
<div id="output" />
<script src="https://unpkg.com/i18next/dist/umd/i18next.min.js"></script>
<script>
i18next.init({
lng: 'en',
debug: true,
resources: {
en: {
translation: {
"key": "Hello World"
}
},
de: {
translation: {
"key": "hello welt"
}
}
}
}, function(err, t) {
// init set content
updateContent();
});
function updateContent() {
document.getElementById('output').innerHTML = i18next.t('key');
}
function changeLng(lng) {
i18next.changeLanguage(lng);
}
i18next.on('languageChanged', () => {
updateContent();
});
</script>
but I can't figure out how to load local json files instead of placing all translations in the js. Do I have to install an additional plugin for loading json translation files?
and is this the correct way of targeting every string in HTML?
function updateContent() {
document.getElementById("homeTitle").innerHTML = i18next.t("home.title");
document.getElementById("homeSubtitle").innerHTML = i18next.t("home.subtitle");
}
is there a way to add an attribute to HTML string like
<h1 data-i18n="home.title"></h1>
to get the translation?
You could load them with fetch, running a bunch of promises.
I wrote a sandbox code example for you in vanilla JS.
PS: Don't know why, but when you open code sandbox the code isn't executed well, you have to refresh the local preview to get it working (or you could try to open the preview from here), but I tested it via Live Server in my dev environment and it's working fine.

How to print a pdf on client side from a groovy webApp?

I am know developping a webapp that as to create a pdf document and print it on client side.
Here is my problem:
i created the pdf using itext and stored it in a shared folder. i did it on a server side.
Now i need to print the created pdf on the client side, the client knows the path of the pdf and can access it.
To be on client side, i am trying to print that document using javascript or jquery.
I tried using embed in my html but it didn't work.
Thx for helping,
here is a working code on server side :
FileInputStream fis = new FileInputStream("test.pdf");
DocFlavor psInFormat = DocFlavor.INPUT_STREAM.AUTOSENSE;
Doc pdfDoc = new SimpleDoc(fis, psInFormat, null);
PrintRequestAttributeSet aset = new HashPrintRequestAttributeSet();
PrintService services = PrintServiceLookup.lookupDefaultPrintService();
DocPrintJob job = services.createPrintJob();
job.print(pdfDoc, aset);
and here is what i tried on client side :
// Grabs the Iframe
document.write('<embed type="application/pdf" src="\\SN782629\TempPartage\test.pdf" id="PDF" name="PDF" width="100%" height="100%" />');
var ifr = document.getElementById("PDF");
//PDF is completely loaded. (.load() wasn't working properly with PDFs)
ifr.onreadystatechange = function() {
if (ifr.readyState == 'complete') {
ifr.contentWindow.focus();
if ($.browser.msie) {
document.execCommand('print', false, null);
} else {
window.print();
}
}
ifr.parentNode.removeChild(ifr);
this second code is on the success section of ajax request, i can put the entire function if needed.
fyi: Recommended way to embed PDF in HTML?
and another point: you'll meet a lot of restrictions in different browsers when including pdf from local file system into a page loaded through HTTP.
i'll advice to expose your pdf through url on your server. for example http://myhost/getPdf/SN782629/TempPartage/test.pdf instead of ""\SN782629\TempPartage\test.pdf" and use this link in rendered page.

protractor-html-reporter screenshot is corrupted

I'm using protractor to automate testing an angularjs application. I use protractor-html-reporter to generate reports.
In a hooks.js file I have placed the following code, in order to generate a screenshot whenever a test scenario fails. The image then is attached to the report.
this.After(function (scenario,callback) {
if (scenario.isFailed()) {
browser.takeScreenshot().then(function (base64png) {
var decodedImage = new Buffer(base64png, 'base64').toString('binary');
scenario.attach(decodedImage, 'image/png');
callback();
}, function (err) {
return callback(err);
});
} else{
callback();
}
});
The JSON, html and screenshot files are generated. The reports are readable and can be viewed using a browser or text editor. However, the screenshot ("png") file is always "damaged".
In the report, the image displays like reserved space (X symbol inside a black square). When trying to open the screenshot using a graphic editor, it tells that the image is damaged.
This is the html report
This is the image error
Am I missing something?

How do I return a file to the user?

I am trying to return a file to the user.
"GetExcel" appears to work and in debug I can see that "ba" has data.
The method completes BUT nothing appears to be returned to the browser - I am hoping to see the file download dialog.
C#
public FileResult GetExcel()
{
using (ExcelPackage pck = new ExcelPackage())
{
ExcelWorksheet ws = pck.Workbook.Worksheets.Add("Demo");
ws.Cells["A1"].Value = "LBHERE";
var ba = pck.GetAsByteArray();
return File(ba, "text/plain", "testFile.txt");
}
}
Javascript
function clickedTest() {
alert("Test clicked");
$.get(myPath + "/Employee/GetExcel", { }, function (data) {
})
};
jQuery's $.get() function pulls data from a webpage into your client-side scripts through AJAX. This is not what you want to do if you want to download a file. Instead, you should open a new tab set to the URL of the file you wish to download.
Try this:
function clickedTest() {
window.open(myPath + "/Employee/GetExcel", "_blank");
}
If your browser still isn't initiating a download, but is instead just displaying a file, you may have to go one step further.
Somewhere in your server-side code, when you have access to the Response object, you should set the Content-Disposition header to attachment and provide a filename for the spreadsheet you are serving. This will inform your browser that the file you are requesting is meant to be downloaded, not displayed.
This can be done as follows:
Response.AddHeader("Content-Disposition", "attachment;filename=myfile.xls")
Of course, replace myfile.xls with the proper filename for your spreadsheet.

Getting notified when the user clicks a link in an embedded PDF

I got a PDF embedded in my page, and I'd like to set something like a Javascript-callback to be called whenever the user clicks a link within the PDF.
Is there a way to accomplish this?
If you check out the Acrobat JS Reference for the minimum version you want to support, you'll see documentation on the HostContainer object.
In the PDF:
this.hostContainer.messageHandler =
{
onMessage: function(messageArray)
{
for(var i = 0; i < messageArray.length; i++)
console.println("Message " + i + ": " + messageArray[i]);
},
onError: function(error, messageArray){ },
onDisclose: function() {return true;}
};
In your HTML, assuming your PDF is inside an <object id="thePdf"> tag:
function messageFunc(messageArray) {
for(var i = 0; i < messageArray.length; i++)
alert("Message " + i + ": " + messageArray[i]);
}
document.getElementById("thePdf").messageHandler = { onMessage: messageFunc };
In your PDF, you'd also need to modify the links so they have a JS action that would post a message to the containing web page. This could be done programmatically (varying wildly depending on the language/library you use), or manually in Acrobat Pro.
this.hostContainer.postMessage(["urlClicked", "http://blah.blah.blah..."]);
Not terribly hard, but no one's ever heard of it. I'd be stunned if this worked anywhere outside an Adobe viewer (Reader/Acrobat) for the next several years.
If you want to send a message from your HTML to the PDF for some reason, it goes something like this:
var thePDF = document.getElementById("thePdf");
thePDF.postMessage(["This", "is", "an", "array", "too."]);
You could even yank out all the existing links and have the PDF request the links be opened by the wrapping HTML page... that way you can give the new windows names, close them from JS, etc. You can get down right snazzy.
But you have to be able to change the PDFs.
Your link is probably represented as a "Link annotation" inside your PDF file. Annotations in PDF can contain "Additional Actions", you could use a pdf processing software like iText (free for non commercial use) or Amyuni PDF Creator(commercial, usual disclaimer applis) to add a Javascript action to the "Additional Actions" collection of your link(s). You can invoke a page or method in your server using this Javascript code.
Client side:
PDF
$("#pdf-link").click(function(){
$.post('yoursite.com/phpfunctionpage/notifyPdf',
{event:'pdf'},
function(response){
alert(response['message']);
}, 'json'
);
});
Your server side:
function notifyPdf(){
$event = $_POST['event'];
if ($event == 'pdf'){
// handle notification here
echo json_encode(array('result'=>1, 'message'=>'notifiation successful'));
}
}
<a href="file.pdf" onclick:'javascriptFunction();'>Open the pdf file</a>
<script>
function javascriptFunction(){
}
</script>

Categories

Resources