How to open generated pdf using jspdf in new window - javascript

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');

Related

Disable auto download of iframe content on iOS Safari

I have a modal that displays a PDF with two option, one to print and one to download.
The download option is using a blob with content-type: application/octet-stream.
The print option is using a blob with content-type: application/pdf.
The download button works perfectly, but when I open the modal in Safari on iOS, the prompt to download is automatically showing and the file is downloaded automatically. It is working on desktop devices and in chrome.
const downloadBlob = new Blob([int8Array], { type: 'data:application/octet-stream;' });
const printBlob = new Blob([int8Array], { type: 'application/pdf;' });
const downloadFileURL = URL.createObjectURL(downloadBlob);
const printFileURL = URL.createObjectURL(printBlob);
When I remove the src attribute from the iframe, the auto download prompt doesn't show. Any ideas how to resolve this?
{fileType === 'application/pdf' ? (
<>
<div id="wrapperDiv" ref={wrapperRef}></div>
<iframe id="documentObject" src={`${fileSrc}#view=fitH`} title={fileName} style={{ display: 'none' }}>
This browser does not support this document type. Please download the document to view it:
</iframe>
</>
Print button:
const element: Window = window.frames;
element[0].focus();
element[0].print();
For printing use:
printPDF(pdfUrl)
{
var w = window.open(pdfUrl);
w.print();
}
For downloading:
downloadPDF(pdfUrl)
{
var anchor = document.createElement('a');
anchor.href = pdfUrl;
anchor.target = '_blank';
anchor.download = "filename.pdf";
anchor.click();
}
Browser support: http://caniuse.com/#feat=download
If the download attribute is not supported, it should fallback to just opening the PDF in a new tab.

Fire javascript function after download asp.net

I have a method in code behind which downloads a file from server to the client. And after that I want to run a javascript function. But it does not work. It works only if the javascript function is in the button click event.
string imageFilePath = Server.MapPath("~/TireLabel.png");
Bitmap bitmap = (Bitmap)Image.FromFile(imageFilePath);//load the image file
Graphics g = Graphics.FromImage(bitmap);
string text = "215/45 R 20";
g.DrawString(text, drawFontArial26Bold, drawBrush, new RectangleF(x, y, width, height), drawFormatCenter);
text = "013";
g.DrawString(text, drawFontArial20Regular, drawBrush, new RectangleF(70, 45, 0, 0), drawFormatRight);
text = "1";
g.DrawString(text, drawFontArial20Regular, drawBrush, new RectangleF(100F, 80, 0, 0), drawFormatRight);
text = "2";
g.DrawString(text, drawFontArial20Regular, drawBrush, new RectangleF(240, 80, 0, 0), drawFormatRight);
Bitmap bit = new Bitmap(bitmap);
bit.Save(Server.MapPath("~/TireLabel.bmp"), System.Drawing.Imaging.ImageFormat.Bmp);
Response.ContentType = "application/jpeg";
Response.AddHeader("content-disposition", "attachment; filename=" + Server.MapPath("~/TireLabel") + ".bmp");
Response.WriteFile(Server.MapPath("~/TireLabel.bmp" + ""));
ClientScript.RegisterStartupScript(GetType(), "key", "runPrint();", true); // THIS does not fire.
//Javascript function
function runPrint() {
var objShell = new ActiveXObject("WScript.Shell");
var strCommand = "C:\\Program Files (x86)\\Google\\Chrome\\Application\\chrome.exe";
//var strCommand = "C:\\PrintLabel.exe";
objShell.Exec(strCommand);
//objShell.ShellExecute(strCommand, "","","open","1");
}
How I can make the javascript fire.
This is a hard problem, because the browser normally doesn't tell you when a download is finished. Have a look at jQuery.filedownload that allows you to download files through AJAX.
-- Edit --
Here is the code to attach jQuery filedownload to all links with the class "fileDownload":
$(document).on('click', 'a.fileDownload', function() {
$.fileDownload($(this).prop('href'))
.done(function () { alert('File download a success!'); })
.fail(function () { alert('File download failed!'); });
return false; //this is critical to stop the click event which will trigger a normal file download
});
This assumes that the URL to the controller action is given in the href attribute of the link, and this action returns a file with return File().
The response must also contain a cookie /fileDownload to inform jquery.fileDownload that a successful file download has occured.
//jquery.fileDownload uses this cookie to determine that a file download has completed successfully
response.AppendCookie(new HttpCookie("fileDownload", "true") {
Path = "/"
});
-- Edit 2 - Changed source to show simpler example with less dependendies. Use the .done promise to trigger an action after the download was done

set a Blob as the "src" of an iframe

The following code work perfectly in Chrome
<script>
function myFunction() {
var blob = new Blob(['<a id="a"><b id="b">hey!</b></a>'], {type : 'text/html'});
var newurl = window.URL.createObjectURL(blob);
document.getElementById("myFrame").src = newurl;
}
</script>
But it is not working with IE. Can some one please tell me what is wrong here.
The iframe "src" also set to the blob as shown below.
<iframe id="myFrame" src="blob:0827B944-D600-410D-8356-96E71F316FE4"></iframe>
Note:
I went on the window.navigator.msSaveOrOpenBlob(newBlob) path as well but no luck so far.
According to http://caniuse.com/#feat=datauri IE 11 has only got partial support for Data URI's. It states support is limited to images and linked resources like CSS or JS, not HTML files.
Non-base64-encoded SVG data URIs need to be uriencoded to work in IE and Firefox as according to this specification.
An example I did for Blob as a source of iFrame and working great with one important CAUTION / WARNING:
const blobContent = new Blob([getIFrameContent()], {type: "text/html"});
var iFrame = document.createElement("iframe");
iFrame.src = URL.createObjectURL(blobContent);
parent.appendChild(iFrame);
iFrame with Blob is not auto redirect protocol, meaning, having <script src="//domain.com/script.js"</script> inside the iframe head or body won't load the JS script at all even on Chrome 61 (current version).
it doesn't know what to do with source "blob" as protocol. this is a BIG warning here.
Solution: This code will solve the issue, it runs mostly for VPAID ads and working for auto-protocol:
function createIFrame(iframeContent) {
let iFrame = document.createElement("iframe");
iFrame.src = "about:blank";
iFrameContainer.innerHTML = ""; // (optional) Totally Clear it if needed
iFrameContainer.appendChild(iFrame);
let iFrameDoc = iFrame.contentWindow && iFrame.contentWindow.document;
if (!iFrameDoc) {
console.log("iFrame security.");
return;
}
iFrameDoc.write(iframeContent);
iFrameDoc.close();
}
I've run into the same problem with IE. However, I've been able to get the download/save as piece working in IE 10+ using filesaver.js.
function onClick(e) {
var data = { x: 42, s: "hello, world", d: new Date() },
fileName = "my-download.json";
var json = JSON.stringify(data),
blob = new Blob([json], {type: "octet/stream"});
saveAs(blob, fileName);
e.preventDefault();
return false;
};
$('#download').click(onClick);
See http://jsfiddle.net/o0wk71n2/ (based on answer by #kol to JavaScript blob filename without link)

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/

Standalone CKFinder: how to only select images in file dialog popup?

I'm using CKFinder in combination with CKEditor, but also as standalone file input image popup window. So when someone clicks the "upload"-button, a new popup window appears in which someone could select an image / file / Flash-file to upload.
For the field "avatar" I need to only select image files. It shouldn't be possible to select another filetype. How can I get this working? In the documentation I can't find very helpful information.
In CKEditor it's possible to only select an image or a file from within the CKFinder-popup, but it looks like the same option has been forgotten in the standalone version of CKFinder.
I need to achieve "ckfinder.html?type=Image", but I don't want to modify ckfinder.js because that will affect also other file popup dialogs in which someone should be able to select even images as files.
I'm including CKFinder like in the popup sample:
var finder = new CKFinder();
finder.basePath = '../'; // The path for the installation of CKFinder (default = "/ckfinder/").
finder.selectActionFunction = SetFileField;
finder.popup();
Thanks in advance for your help!
you should try it,
*
LoadImage
is id of button select file,
picUrl
is id of text link
$('#LoadImage').click(function () {
var finder = new CKFinder();
finder.selectActionFunction = function (fileUrl) {
fileUrl = fileUrl.substring(fileUrl.lastIndexOf("/") + 1);
$('#picUrl').val = (fileUrl);
}
selectFileWithCKFinder('picUrl');
})
function selectFileWithCKFinder(elementId) {
CKFinder.popup({
chooseFiles: true,
width: 800,
height: 600,
onInit: function (finder) {
finder.on('files:choose', function (evt) {
var file = evt.data.files.first();
var output = document.getElementById(elementId);
output.value = file.getUrl();
});
finder.on('file:choose:resizedImage', function (evt) {
var output = document.getElementById(elementId);
output.value = evt.data.resizedUrl;
});
}
});
}

Categories

Resources