Disable auto download of iframe content on iOS Safari - javascript

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.

Related

Next.js download PDF functions open 2 tabs

I'm attempting to trigger a PDF download when landing on a page with next.js. When doing so it's opening another tab with the PDF which i'm fine with, but i'd like to open the PDF on another tab. So I added it with link.target ="_blank" on page load, there are 2 PDF tabs that are open now.
I've attempted get only 1 tab with the PDF to open but I am unable to. Is this an issue with next.js? How can I get my function to only 1 PDF tab.
I think the issue may be related to the server side render? If so how can I only call this function once?
Here is my download file function:
function downloadFile(filePath) {
if(process.browser) {
var link = document.createElement('a');
link.href = filePath;
link.target = "_blank"
link.download = filePath.substr(filePath.lastIndexOf('/') + 1);
link.click();
}
}
downloadFile("http://www.africau.edu/images/default/sample.pdf");
Here is my full next js page:
const Download= () => {
function downloadFile(filePath) {
if(process.browser) {
var link = document.createElement('a');
link.href = filePath;
link.target = "_blank"
link.download = filePath.substr(filePath.lastIndexOf('/') + 1);
link.click();
}
}
downloadFile("http://www.africau.edu/images/default/sample.pdf");
return (
<Layout>
<div> download pdf</div>
</Layout>
);
};
export default Download;

Download PDF From Rest API

I have the following text that i get from java with a get request.
GET: http://localhost:8101/raportet/Cinema.jasper
%PDF-1.4
%âãÏÓ
3 0 obj
<</Filter/FlateDecode/Length 1644>>stream
xœ½œ]SÛF†ïý+ö2½ˆ²_úêUÝ`Rh;étz¡`aDü‘H†ß•Ç
8ïJø5ã³ ôé<^Yþ<ø}20‘ˆÃHL¦ƒÑdð×#‹ãê·JH÷¨¾Ç©“ÅàÕ¡JŠÉåàÅ
..............
I want to download this file in frontend using js.
I tried a lot of methods but i cannot download it. Is there any method i can do it.
I've almost the same problem as this: Opening PDF String in new window with javascript
you can use this method if you want to show and download PDF in ReactJs
axios.get(exportUrl, {responseType:'blob'})
.then(response => {
// Create blob link to download
var blob = new Blob([response.data], { type: 'application/pdf' });
var URL = window.URL || window.webkitURL;
const url = window.URL.createObjectURL(blob);
const link = document.createElement('a');
link.target = '_blank';
link.href = url;
link.setAttribute( //if you just want to preview pdf and dont want download delete this three lines
'download',
`Factor.pdf`,
);
// Append to html link element page
document.body.appendChild(link);
// Start download
link.click();
// Clean up and remove the link
link.parentNode.removeChild(link);
URL.revokeObjectURL(url);
})
}

How to change chrome browsers "download pdf instead of opening" from my web application?

My web application opens a pdf file in a popup or a new tab. Now, when the user has enabled the "Download PDF files instead of automatically opening them in Chrome" under Settings > Advanced >Site Settings, chrome ends up downloading the pdf instead of opening this. How to prevent chrome from downloading the pdf and open it instead. Is there any API that can be called from my web application?
The only way I know of is to use something like PDF.js, to display the PDF in the browser using javascript.
https://mozilla.github.io/pdf.js/
The Online Demo section demonstrates the idea. Included as iframe in a snippet below.
iframe
{
width:610px;
}
<iframe src="https://mozilla.github.io/pdf.js/es5/web/viewer.html">
I have tried many solutions using Javascipt.
But later i knew PDF download thing is bound to browser settings.
Without code when i figured out problem i referred following link :
https://www.howtogeek.com/721441/how-to-download-pdfs-instead-of-previewing-them-in-chrome-firefox-and-edge/ .
And my code was like below
Javascript
/* Helper function */
function download_file(fileURL, fileName) {
// for non-IE
if (!window.ActiveXObject) {
var save = document.createElement('a');
save.href = fileURL;
save.target = '_blank';
var filename = fileURL.substring(fileURL.lastIndexOf('/')+1);
save.download = fileName || filename;
if ( navigator.userAgent.toLowerCase().match(/(ipad|iphone|safari)/) && navigator.userAgent.search("Chrome") < 0) {
document.location = save.href;
// window event not working here
}else{
var evt = new MouseEvent('click', {
'view': window,
'bubbles': true,
'cancelable': false
});
save.dispatchEvent(evt);
(window.URL || window.webkitURL).revokeObjectURL(save.href);
}
}
// for IE < 11
else if ( !! window.ActiveXObject && document.execCommand) {
var _window = window.open(fileURL, '_blank');
_window.document.close();
_window.document.execCommand('SaveAs', true, fileName || fileURL)
_window.close();
}
}
HTML Code
<button onClick="download_file('original_link.pdf','any_name.pdf')">Click</button>

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/

Categories

Resources