Next.js download PDF functions open 2 tabs - javascript

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;

Related

How to download PDF automatically on click instead of opening it in new tab using js?

I have an input URL with which I want to download pdf file directly without viewing it in a new tab or on the same tab, I have tried following things till now but nothing is helping. Frist tried with this
http.success(function (data) {
var link = document.createElement('a');
link.href = data.results[0].value.url;
link.download = data.results[0].value.url.substr(data.results[0].value.url.lastIndexOf('/') + 1);
link.click();
document.body.appendChild(link);
setTimeout(function () {
document.body.removeChild(link);
}, 100);
}.bind(this));
This script is not downloading the file. It opens the file in the same tab.
Have tried all the answers in these previously answered questions. But nothing worked for me.
How can I download a pdf from a url using javascript?
How to download PDF automatically using js?
Download pdf without opening in browser
Then I tried with this Blob. Added the blob to my script and then tried again.
http.success(function (data) {
var blob=new Blob([data.results[0].value.url],{ type: "application/pdf" });
var link = document.createElement('a');
link.href = window.URL.createObjectURL(blob);
link.download = data.results[0].value.url.substr(data.results[0].value.url.lastIndexOf('/') + 1);
link.click();
document.body.appendChild(link);
setTimeout(function () {
document.body.removeChild(link);
}, 100);
}.bind(this));
But this time it downloads the file. But can't able to open it. The downloaded file is corrupted.
Have tried the answers in these questions. But nothing worked for me.
PDF is corrupted after reconstructing it using URL.createObjectURL
Problem downloading a PDF blob in JavaScript
Blob from buffer returns corrupted pdf
please let me know if there are any other ways to download the pdf file directly. Thanks in advance.
What is stored in data.results[0].value.url?
Is it just a link to the PDF? If that's the case you will need to fetch the pdf document first.
Try this
http.success(function (data) {
fetch(data.results[0].value.url)
.then((response) => response.arrayBuffer())
.then((pdfFile) => {
const blob = new Blob([pdfFile], { type: "application/pdf" });
const anchor = document.createElement("a");
anchor.href = window.URL.createObjectURL(blob);
anchor.download = "SOME FILENAME.PDF";
// some browser needs the anchor to be in the doc
document.body.append(anchor);
anchor.click();
anchor.remove();
// in case the Blob uses a lot of memory
window.addEventListener(
"focus",
() => {
URL.revokeObjectURL(anchor.href);
},
{
once: true,
}
)
});
})
First, I would recommend trying the simplest example.
const pdfLink = data.results[0].value.url
const download = (url) => {
const link = document.createElement('a');
link.setAttribute('download', 'fileName.pdf');
link.setAttribute('href', url);
link.click();
}
downloadBlob = (blob) => download(URL.createObjectURL(blob))
fetch(pdfLink)
.then(response => response.blob())
.then(downloadBlob)
I share you a piece of code using MUI + JS
<IconButton variant="contained"
sx={{
fontSize: '1rem',
fontWeight: 'normal',
color:'silver',
}}
component='label'
size={'small'}
onClick={() => {
const url = 'https:.....'
fetch(url)
.then((res) => { return res.blob(); })
.then((data) => {
const a = document.createElement("a")
a.href = window.URL.createObjectURL(data)
a.download = formValues[id]
a.click()
});
}}>
<VisibilityIcon />
</IconButton>

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

Image showing downloaded but not getting opened from browser when clicked

Image showing downloaded after i click on download image its showing Failed-No file in browser.I have done something wrong in providing download path may be. Here is my code:
<button id="download-button" class="btn--success">Download</button>
<script>
document.getElementById('download-button').addEventListener('click', function () {
var link = document.createElement('a');
link.setAttribute('href', '/Downloads');
link.setAttribute('download', 'https://tinyjpg.com/images/social/website.jpg');
link.style.display = 'none';
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
});
</script>
this final a tag should look like this:
<a href="https://tinyjpg.com/images/social/website.jpg" download>
<img src="https://tinyjpg.com/images/social/website.jpg">
</a>
but you set link
link.setAttribute('href', '/Downloads');
link.setAttribute('download', 'https://tinyjpg.com/images/social/website.jpg');
Try to create a downloadable link to achieve dynamically downloading functionality. For more reference refer createObjectURL
UPDATE
First, you need to convert the requested Image to base64 format
To achieve this, we need to download the requested image.
To download image, Implement Fetch and Promise together
After, Image get downloaded, convert it into blob res.blob()
FInally your code for dynamically creating link with little code change.
The entire code snippet is below
async function getBase64ImageFromUrl(imageUrl) {
var res = await fetch(imageUrl);
var blob = await res.blob();
return new Promise((resolve, reject) => {
var reader = new FileReader();
reader.addEventListener("load", function () {
resolve(reader.result);
}, false);
reader.onerror = () => {
return reject(this);
};
reader.readAsDataURL(blob);
})
}
getBase64ImageFromUrl('https://cors-anywhere.herokuapp.com/'+'https://tinyjpg.com/images/social/website.jpg')
.then(function(result) {
var link = document.createElement('a')
link.href = result
link.style.display = 'none';
link.setAttribute('download','');
document.body.appendChild(link);
link.click();
document.body.removeChild(link)}
)
.catch(err => console.error(err));
Note - to avoid CORS issue, I have attached the 'https://cors-anywhere.herokuapp.com/' URL at the beginning of the image URL.
Try this instead
document.getElementById('download-button').addEventListener('click', function () {
var link = document.createElement('a');
link.setAttribute('href', 'https://tinyjpg.com/images/social/website.jpg');
link.style.display = 'none';
link.setAttribute('download', '');
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
}
The resulting a tag will be like this
<a href='https://tinyjpg.com/images/social/website.jpg' download style="display:none;" />
html download attribute will work, only those case when image and html file both are in same server . it means as per your image path your html file must be in https://tinyjpg.com/ server
you can update your script by this
document.getElementById('download-button').addEventListener('click', function () {
var link = document.createElement('a');
link.setAttribute('href', 'https://tinyjpg.com/images/social/website.jpg');
link.setAttribute('download',"download");
link.style.display = 'none';
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
});

How to show download as prompt on new window from bootstrap model?

For a normal HTML page I tried the below code which starts download in a separate window. When I use the same code for bootstrap modal form then it's not working. What else I need to do for implement same functionality in bootstrap modal ?
var newwin=window.open("",'newwindow','width=700,height=700, left=100,top=100,resizable=yes','_blank').document;
var link =newwin.createElement('a');
link.href = window.URL.createObjectURL(blob);
link.download = fileName;
link.click();
you have used blob in window.URL.createObjectURL, which is undefined.
you can use this solution.
use code like this :
var newwin=window.open("",'newwindow','width=700,height=700, left=100,top=100,resizable=yes','_blank').document;
var link =newwin.createElement('a');
var blob = new Blob([json], {type: "octet/stream"});
link.href = window.URL.createObjectURL(blob);
link.download = fileName
window.location.assign(url);

Excel export not working on Firefox but working fine in google crome

The below given event is called to export the data in the table into an EXCEL , The code works like a charm in Chrome . In IE and Firefox i am not getting anything(File, error etc).
Kindly assist me to go forward and export the file in all the browsers
$("[id$=myButtonControlID]").click(function(e) {
var result = 'data:application/vnd.ms-excel,' + encodeURIComponent($('div[id$=printHead]').html());
var link = document.createElement("a");
link.download = "Reports";
link.href = result;
link.click();
});
With Firefox you have to explicitly add the link element to the DOM before you can execute .click():
$("[id$=myButtonControlID]").click(function(e) {
var result = 'data:application/vnd.ms-excel,' + encodeURIComponent($('div[id$=printHead]').html());
var link = document.createElement("a");
document.body.appendChild(link); // You need to add this line
link.download = "Reports";
link.href = result;
link.click();
});
The data: URI is supported from IE8. But it "cannot be used for navigation [...]" so I assume it will not work in an <a href="...">. See this link.

Categories

Resources