Specify file name when printing page element using javascript - javascript

I need to specify a filename when printing a page element using javascript.
Here is my code that will print the specified elementId from the page:
function printPartOfPage(elementId) {
var printHeader = document.getElementById('header');
var printContent = document.getElementById(elementId);
var windowUrl = 'NewWindow';
var uniqueName = new Date();
var windowName = 'Print' + uniqueName.getTime();
var printWindow = window.open(windowUrl, windowName, 'left=20,top=200');
printWindow.document.write('<html xmlns="http://www.w3.org/1999/xhtml"><head>');
printWindow.document.write('<link href='+sURL+'css/style.css rel="stylesheet">');
printWindow.document.write('<link href='+sURL+'css/print.css rel="stylesheet">');
printWindow.document.write('</head><body>');
printWindow.document.write(printContent.innerHTML);
printWindow.document.write('</body></html>');
printWindow.document.close();
printWindow.focus();
setTimeout(function(){
printWindow.print();
}, 500)
printWindow.setTimeout("window.close()", 2000);
}
This works fine, except that the default file name that appears in the print dialog is download.pdf and I need to specify my own file name based on parameters from the url:
https://example.com/a/b/c/123456789/2019/1
I would like to construct a file name using the last three elements of the URL such that the default file name that appears in the print dialog window is:
123456789_2019_1.pdf

Take a look at this: How to set a file name using window.open
Seems to be a work around, but a good one.

Related

Open html text in new tab using $window.open

$window.open('<span>request processed successfully</span>', '_blank');
I would like the $window service to show the simple text request processed successfully in a new tab.
But instead of it, it treats the html text as location url and tries to open the page http://domain-addr#request processed successfully
How can i pass html text argument to angular's $window service?
You can do something like this in standard JavaScript...
function newWindow() {
// create some html elements
var para = document.createElement('p');
var title = document.createElement('title');
// define some window attributes
var features = 'width=400, height=400, status=1, menubar=1, location=0, left=100, top=100';
var winName = 'New_Window';
// populate the html elements
para.textContent = 'Some example text.';
title.textContent = 'New Window Title';
// define a reference to the new window
// and open it with defined attributes
var winRef = window.open('', winName, features);
// append the html elements to the head
// and body of the new window
winRef.document.head.appendChild(title);
winRef.document.body.appendChild(para);
}
you can use pure javascript,
var w = window.open("www.mydomain.com/test.php", "_blank");
w.document.write('<span>request processed successfully</span>');
you could just create a simple html document with called success.htm or similar with "request processed successfully" and include that in the function.
so $window.open('success.html','_blank', 'size blah blah');
Try this:
HTML:
<button id="newWindow">
Click
</button>
JavaScript:
//call the function right away
(function() {
//grab button by id
var newWindow = document.getElementById("newWindow");
//add an event listener
newWindow.addEventListener("click", function() {
//create a new p element
var p = document.createElement('p');
// change the styles of your paragraph
// optional
p.style.color = "red";
p.style.fontSize = "4em";
//Insert the text you want
p.textContent = "request processed successfully";
//open the window
var windRed = window.open('', '_blank');
//append the p element to the new window's body
windRed.document.body.appendChild(p);
}, false);
})();

Angularjs/Restangular, how to name file blob for download?

For some reason this seems easier in IE than Chrome/FF:
$scope.download = function() {
Restangular.one(myAPI)
.withHttpConfig({responseType: 'blob'}).customGET().then(function(response) {
//IE10 opens save/open dialog with filename.zip
window.navigator.msSaveOrOpenBlob(response, 'filename.zip');
//Chrome/FF downloads a file with random name
var url = (window.URL || window.webkitURL).createObjectURL(response);
window.location.href = url;
});
};
Is there a way to do something similar to how IE10+ works? That is, I can specify a file name/type (will only be zip)?
As soon as you have your object url you can create an anchor and set the download attribute to the filename you want, set the href to the object url, and then just call click
var myBlob = new Blob(["example"],{type:'text/html'})
var blobURL = (window.URL || window.webkitURL).createObjectURL(myBlob);
var anchor = document.createElement("a");
anchor.download = "myfile.txt";
anchor.href = blobURL;
anchor.click();
Download attribute compatibility
Just use https://www.npmjs.com/package/angular-file-saver
Browser Support table can be seen here: https://github.com/eligrey/FileSaver.js/

How to open generated pdf using jspdf in new window

I am using jspdf to generate a pdf file. Every thing is working fine. But how to open generated
pdf in new tab or new window.
I am using
doc.output('datauri');
Which is opening the pdf in same tab.
Based on the source you can use the 'dataurlnewwindow' parameter for output():
doc.output('dataurlnewwindow');
Source in github:
https://github.com/MrRio/jsPDF/blob/master/jspdf.js#L914
All possible cases:
doc.output('save', 'filename.pdf'); //Try to save PDF as a file (not works on ie before 10, and some mobile devices)
doc.output('datauristring'); //returns the data uri string
doc.output('datauri'); //opens the data uri in current window
doc.output('dataurlnewwindow'); //opens the data uri in new window
This solution working for me
window.open(doc.output('bloburl'))
I have to use this to load the PDF directly. Using doc.output('dataurlnewwindow'); produces an ugly iframe for me. Mac/Chrome.
var string = doc.output('datauristring');
var x = window.open();
x.document.open();
x.document.location=string;
this code will help you to open generated pdf in new tab with required title
let pdf = new jsPDF();
pdf.setProperties({
title: "Report"
});
pdf.output('dataurlnewwindow');
Or...
You can use Blob to achive this.
Like:
pdf.addHTML($('#content'), y, x, options, function () {
var blob = pdf.output("blob");
window.open(URL.createObjectURL(blob));
});
That code let you create a Blob object inside the browser and show it in the new tab.
Search in jspdf.js this:
if(type == 'datauri') {
document.location.href ='data:application/pdf;base64,' + Base64.encode(buffer);
}
Add :
if(type == 'datauriNew') {
window.open('data:application/pdf;base64,' + Base64.encode(buffer));
}
call this option 'datauriNew' Saludos ;)
using javascript you can send the generated pdf to a new window using the following code.
var string = doc.output('datauristring');
var iframe = "<iframe width='100%' height='100%' src='" + string + "'></iframe>"
var x = window.open();
x.document.open();
x.document.write(iframe);
x.document.close();
This is how I handle it.
window.open(doc.output('bloburl'), '_blank');
Generally you can download it, show, or get a blob string:
const pdfActions = {
save: () => doc.save(filename),
getBlob: () => {
const blob = doc.output('datauristring');
console.log(blob)
return blob
},
show: () => doc.output('dataurlnewwindow')
}
STEP 1
Turn off addblock
STEP 2
Add
window.open(doc.output('bloburl'), '_blank');
Or try
doc.output('dataurlnewwindow')
Javascript code
// IE doesn't allow using a blob object directly as link href
// instead it is necessary to use msSaveOrOpenBlob
if (window.navigator && window.navigator.msSaveOrOpenBlob) {
window.navigator.msSaveOrOpenBlob(doc.output("blob"), "Name.pdf");
} else {
// For other browsers:
// Create a link pointing to the ObjectURL containing the blob.
doc.autoPrint();
window.open(
URL.createObjectURL(doc.output("blob")),
"_blank",
"height=650,width=500,scrollbars=yes,location=yes"
);
// For Firefox it is necessary to delay revoking the ObjectURL
setTimeout(() => {
window.URL.revokeObjectURL(doc.output("bloburl"));
}, 100);
}
This works for me!!!
When you specify window features, it will open in a new window
Just like :
window.open(url,"_blank","top=100,left=200,width=1000,height=500");
Step I: include the file and plugin
../jspdf.plugin.addimage.js
Step II: build PDF content
var doc = new jsPDF();
doc.setFontSize(12);
doc.text(35, 25, "Welcome to JsPDF");
doc.addImage(imgData, 'JPEG', 15, 40, 386, 386);
Step III: display image in new window
doc.output('dataurlnewwindow');
Stepv IV: save data
var output = doc.output();
return btoa( output);
Javascript code: Add in end line
$("#pdf_preview").attr("src", pdf.output('datauristring'));
HTML Code: Insert in body
<head>
</head>
<body>
<H1>Testing</h1>
<iframe id="pdf_preview" type="application/pdf" src="" width="800" height="400"></iframe>
</body>
</html>
preview within same window inside iframe along with with other contents.
Additionally, it is important to remember that the output method has other values and it might be interesting to test all of them to choose the ideal one for your case.
https://artskydj.github.io/jsPDF/docs/jsPDF.html#output
test one line at a time:
doc.output('arraybuffer');
doc.output('blob');
doc.output('bloburi');
doc.output('bloburl');
doc.output('datauristring');
doc.output('dataurlstring');
doc.output('datauri');
doc.output('dataurl');
doc.output('dataurlnewwindow');
doc.output('pdfobjectnewwindow');
doc.output('pdfjsnewwindow');

Window.print is not printing the whole page

I am creating a report table in my jsp which contains 60 columns. I can see all the columns by scrolling.
Now I want to print this report. The function I am using to print is
function printReport(rpt)
{
var report = document.getElementById(rpt);
var newWindow = "toolbar=no, addressbar=no, directories=no,location=no, status=yes, menubar=no, scrollbars=yes, resizable=yes, width=5000 , height=500, left=50, top=50";
var printWindow = window.open('',rpt, newWindow);
printWindow.document.write('<html><body>');
printWindow.document.write('<div id="rpt" name="rpt" style="overflow:scroll;" >');
printWindow.document.write(report.innerHTML);
printWindow.document.write('</div>');
printWindow.document.write('</body></html>');
printWindow.document.close();
printWindow.focus();
printWindow.print();
printWindow.close();
}
Now the problem is it only prints the content which is visible on screen i.e the printed paper only has around 10 columns which are visible on screen. But I want to print the remaining columns also in the next page so that whole table is printed.
Any Suggestions?
remove
style="overflow:scroll;"
or even just this (and note that I first removed the spaces in the parms and then removed most of them since they are irrelevant)
function printReport(rpt)
{
var report = document.getElementById(rpt);
var parms = "scrollbars,resizable,width=500,height=500,left=50,top=50";
var printWindow = window.open('',rpt, parms);
printWindow.document.write('<html><body onload="window.focus();window.print()">');
printWindow.document.write(report.innerHTML);
printWindow.document.write('</body></html>');
printWindow.document.close();
printWindow.close(); // not sure this is ok either.
}
UPDATE: I strongly suggest you send a PDF instead of trying to force the browser to print your page like you want

is it possible to display pictures in a popup.php window, using the src from the main page?

I have a page with pictures, which I want to displayed in a popup.php when clicking on them.
I want the popup window to display a picture(the one I'm clicking on), some text, and a print button.
I'm doing this on the page:
<img src="graphics/picture1.png" width="340" height="200" border="0"/>
In the JS file:
function popup()
{
window.open('popup.php', 'window', 'toolbar=no,location=no,status=no,menubar=no,scrollbars=no,resizable=no,width=520,height=400,left=350,top=100');
}
function showImg(img)
{
var imageSrc = "imageName/imagePath.png";
if(img.src != imageSrc){
img.src = imageSrc;
}
}
And in the popup.php:
<img src="graphics/picture03.png" onload="showImg(this)" />
There should be an obvious way, but I can't find it.
I would think adding the image name and text content to the URL would be the obvious way.
popup.php?image=myImage.gif&text=Say%20something%20witty%20here
Well, you'll want to have your popup contain a holder for the image (which it seems like you already have), but you'll also need to have a holder for your text. Your popup.php should have something like <div id="textHolder"></div> - then your javascript function needs to accept the appropriate text as well as populate it into the textHolder div.
I'm not sure how you're calling these JS functions, or from where - so some of the code might need to change - it should be something to the tune of....
function showImg(img, textHolderObj, text)
{
var imageSrc = "imageName/imagePath.png";
if(img.src != imageSrc){
img.src = imageSrc;
}
textHolderObj.innerHTML= text
}
If is that simple, you could create it:
var win = window.open('', 'win', 'toolbar=no,location=no,status=no,menubar=no,scrollbars=no,resizable=no,width=520,height=400,left=350,top=100');
var img = win.document.createElement('img');
img.src = 'image.png';
img.alt = 'Some text';
var label = win.document.createElement('p');
label.innerHTML = 'Some text';
var button = win.document.createElement('a');
button.href = 'javascript:window.close()';
button.innerHTML = 'Close';
win.document.body.appendChild(img);
win.document.body.appendChild(label);
win.document.body.appendChild(button);
I don't get the question too well. You want to access a function that was defined in the page that opened a popup? You should be able to use opener.showImg(this)
your popup has no idea what image you clicked on. you need to do this:
onClick="popup('imgSrc')"
and in your window reference:
window.open('popup.php?imgSrc='+imgSrc, ...
then... your popup window has to run off of url vars, but php now knows what its looking for:
<?php echo '<img src="' . $_GET["imgSrc"] . '" />'; // this is going to load the image, so you don't need the onLoad()
It is possible to create a new popup window using a variable
top.mydocument=window.open('','window','toolbar=no,location=no,
status=no,menubar=no,scrollbars=no,resizable=no,
width=520,height=400,left=350,top=100');
and then use document.write to write the content:
top.mydocument.document.write(
'<html><head></head>'
+'<body bgcolor=white onLoad="self.focus()">'
+'imageName/imagePath.png'
+'</body></html>'
)
Make sure you close it.
top.mydocument.document.close()

Categories

Resources