Displaying PDF content in a new browser tab by utilizing JavaScript

Currently, I am utilizing the struts2 framework alongside dojo for the UI. My goal is to display a PDF in a new browser window. The PDF inputstream is obtained from the server through a standard AJAX call using the GET method (not utilizing a Dojo AJAX call but instead opting for a native JS AJAX call). How can I go about displaying the PDF string in a new browser window?

JS Code:

// Two inputs to retrieve the PDF file //

var selectedFileSlot={"END407":"report_28_03_13.pdf","END408":"[B@cef121c","END409":"*.pdf;*.doc;*.docx;*.odt;*.ods","END410":"5242880"}
var selectedNode=   {"objectID":"22df1b2601a3552f24e5f011abc27f86","specID":"2001","entityConcreteID":"11000"}

var xmlhttp;
if (window.XMLHttpRequest) {
    xmlhttp=new XMLHttpRequest();
} 
xmlhttp.onreadystatechange=function() {
  if (xmlhttp.readyState==4 && xmlhttp.status==200)  {
      alert(xmlhttp.response);
      window.open(xmlhttp.response);//Unable to open in new browser window
  }
}
xmlhttp.open("GET","downloadDocument.action?selectedNode=" + JSON.stringify(selectedNode) + "&selectedFileSlot=" + JSON.stringify(selectedFileSlot),true);
xmlhttp.send();

struts.xml Code:

<action name="downloadDocument" class="commonAction" method="downloadDocument">
    <interceptor-ref name="sessionStack"></interceptor-ref>
    <interceptor-ref name="cachingStack"></interceptor-ref>
    <result name="success" type="stream">
    <param name="contentType">application/octet-stream</param>
    <param name="inputName">inputStream</param>
    <param name="contentDisposition">attachment;filename="${fileFileName}"</param>
    <param name="bufferSize">1024</param>
    </result>
    </action>

Action Class Code:

commonDTO.setSelectedNode(this.selectedNode);
commonDTO.setSelectedFileSlot(this.selectedFileSlot);
byte[] bytes = commonDAO.getDownloadDocument(commonDTO); //Obtaining PDF as a byte array
inputStream = new ByteArrayInputStream(bytes);

Answer №1

The information contained in the PDF file is in binary format, which cannot be processed by Javascript. To properly handle this data, you must return it with a Content-type of application/pdf, rather than text/html or application/octet-stream. This can be achieved using a Stream result as detailed on the Apache Struts documentation.

Instead of attempting to load the file in a new window via AJAX, consider utilizing one of the alternative methods outlined in this answer on Stack Overflow.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Creating an app using Ionic 1 that features scrollable tabs with the ability to handle overflow

My current code snippet is displayed below. On smaller mobile screens, all 7 tabs are not visible at once and instead appear in two rows which looks messy. I want to modify the display so that only 3 tabs are visible at a time and can be scrolled through. ...

Add the element to a fresh collection of objects using an associative array

Can you help me figure out what's causing an issue when attempting to add a new element to an associative array of objects? var storeData3 = [ { 'key1' : 'value1' }, { 'key2' : 'value2' }, { 'key3&ap ...

What are the steps for creating a dropdown menu that allows for easy selection of the correct item

I am dealing with a dropdown menu as shown below. <select name="slt"> <option value="1">One</option> <option value="2">Two</option> <option value="3">Three</option> <option value="3">Three +</option&g ...

What is the best way to display just one record that has the lowest score out of all the records?

I need help with displaying only 1 record from the DL list that has the lowest score, instead of showing all records. In the example on stackblitz, you can see that for the first record, the DL scores are: 54, 20, and updated. Instead of displaying all 3 ...

Only when the user has successfully completed the reCAPTCHA and checked the checkbox, Vue will be able to

For my new project developed with VueJs, I am implementing a Single Page Application (SPA). The objective is to incorporate a simple if statement functionality. When the user checks a checkbox and successfully solves the reCaptcha, Vue should send an email ...

Navigate to the same destination with React Router Dom while passing state as a parameter

Let's talk about a scenario with a Link setup like this: <Link to={`/samelocation/${id}`} state={{ state1: 'hello' }}> This link is nested in a sub-component within the main component situated at /samelocation/:id. To ensure that the ...

Combining two arrays in JavaScript and saving the result as an XLS file

I have a question that I couldn't find an answer to. I need to merge two arrays and export them to an Excel file using only JavaScript/jQuery. Let's say we have two arrays: Array 1 : ["Item 1", "Item 2"] Array 2 : ["Item 3", "Item 4"] When the ...

Ways to make a jQuery function more concise

I need help with optimizing this jQuery function. It's repetitive and I want to find a way to shorten it while achieving the same result. Can someone assist me in streamlining this code? $(".c1").delay(5000).fadeOut("slow", function() { $("#phone ...

Converting XML to JSON using UTF-8 Encoding

I am currently working with xml2js to convert an XML feed into JSON format. However, I'm facing an issue where certain characters like Æ, Ø & Å are displayed as expected in the XML but appear differently after parsing. After parsing, I receive ...

Accessing the Bootstrap tab form from an external source

I currently have Bootstrap tabs on a page and they are functioning correctly. However, I am looking to open these tabs from an external page. Is this feasible? <div role="tabpanel"> <ul class="nav nav-tabs" role="tablist"> ...

Obtaining JSON data from a PHP script using AngularJS

I've been exploring an AngularJS tutorial on a popular website called w3schools. Check out the tutorial on w3schools After following the tutorial, I modified the script to work with one of my PHP scripts: <!DOCTYPE html> <html > <sty ...

What could be causing my TreeSet to only accept the first element and not add any additional ones?

In my program, I am working with multiple arrays defined like this: private static String[] patientNames = { "John Lennon", "Paul McCartney", "George Harrison", "Ringo Starr" }; Next, I create a TreeSet instance: TreeSet<Patient> patTreeSet = new ...

The form is not being submitted when I click on the submit button because I have two buttons that trigger AJAX requests

I am facing an issue with a form where there is a submit button inside it, as well as another button within the form that has attributes type=button and onclick=somefunction(). The button with the onclick function works perfectly fine, but the other button ...

The system encountered an error when attempting to convert the data '19-10-2002' into a date format

I am trying to pass a date parameter in the format (dd-MM-yyyy) and then convert it into the format (yyyy-MM-dd) before sending it via API. Here is my code: convert(date:string){ date //is in the format(dd-MM-yyyy) date = formatDate(date , " ...

Tips for incorporating "are you sure you want to delete" into Reactjs

I am currently working with Reactjs and Nextjs. I have a list of blogs and the functionality to delete any blog. However, I would like to display a confirmation message before deleting each item that says "Are you sure you want to delete this item?" How ...

Can you explain the functionality of this JavaScript registration code?

I am working on an ajax/jquery 1.3.2 based sign up form and I am looking to gain a deeper understanding of how to incorporate jquery into my projects by analyzing the code line by line. Could someone provide a detailed explanation of this code and break d ...

Sending target information as a property argument

I have encountered an issue with my app's two Bootstrap modals. It seems that many people are facing problems with opening the second modal. Is it possible to pass data-target and modal id properties as props in this manner: data-target={props.da ...

using the post-increment operator on a class instance variable

The result of running this code snippet is: c: 1 , id: 0 I am curious as to why the expected output is not: c: 0 , id: 1 class A { private static long counter; private final long identifier = counter++; public A() { print("c: " + cou ...

KnockoutJS - Struggling to bind model from simple JSON array

I've been working on an application that relies on a static JSON array, without the support of a backend service. I've been attempting to bind this JSON array to the page using KnockoutJS. Although I can successfully load the JSON array and creat ...

Updating HTML input fields via AJAXIncorporating AJAX

Let's take a look at our database: ID Name Price 1 product1 200 2 product2 300 3 product3 400 Now, onto my form: <form action="test.php" method="post" /> <input type="text" name="search" id="search" placeholder="enter ...