I have one Python API that returns a PDF file which when called directly from my terminal downloads the PDF fine and it all looks good when opened. However, I have a Nuxt web app supported by an Express backend which I want to use to open the PDF file in a new tab and to be downloadable. All I am getting in response from the Python API is a string which looks like this:
'%PDF-1.4\n'
'1 0 obj\n'
'<<\n'
'/Title (��\x00F\x00l\x00o\x00o\x00d\x00S\x00m\x00a\x00r\x00t)\n'
plus a few thousand more chars.
This string is what opens in the new tab. It looks like some encoded data, but I am not really sure which makes proceeding a bit harder.
I am assuming the Python API is fine, so I am thinking I need to do more with Express/Nuxt to make it work. The call to the Python API in Express is:
const response = await axios.get(
url, { headers: { "X-API-Key": process.env.FS_UPRN_API_KEY } }
);
res.setHeader("Content-type", "application/pdf")
res.setHeader('Content-Transfer-Encoding', 'binary');
res.setHeader('Accept-Ranges', 'bytes');
res.send(response.data)
In the Nuxt frontend:
this.$axios.get(`/api/uprn?uprn=${this.clickedUprn}`)
.then(response => {
window.open("", "_blank").document.write(response.data);
I have tried numerous configurations with different headers but haven't had any luck. How do I achieve the desired outcome?
CodePudding user response:
What worked for me was encoding the contents of the file to base64 and then proceeding with the answer to this question: Opening PDF String in new window with javascript
CodePudding user response:
To open a PDF in a new tab with Nuxt, you can use the window.open()
method in JavaScript. This method allows you to open a new window or tab in the browser, and to specify the URL of the PDF file that you want to open.
For example, if you have a PDF file at the URL http://example.com/my-pdf.pdf, you can use the following code to open the PDF in a new tab:
window.open("http://example.com/my-pdf.pdf");
This code will open the PDF in a new tab in the same browser window. If you want to open the PDF in a new window instead, you can use the target attribute of the window.open()
method to specify the _blank
value, like this:
window.open("http://example.com/my-pdf.pdf", "_blank");
This code will open the PDF in a new window instead of a new tab.
Overall, to open a PDF in a new tab with Nuxt, you can use the window.open()
method in JavaScript and specify the URL of the PDF file that you want to open. This will open the PDF in a new tab or window in the browser, allowing the user to view the PDF file.