Ingesting a PDF stream into a JSP document

How can I display a PDF report inside a JSP?

  1. I have the PDFstream available using the following code

    private void generatePDFReport(OutputStream stream, JasperPrint jasperPrint) throws JRException {
    JRPdfExporter jrpdfexporter = new JRPdfExporter();
    jrpdfexporter.setExporterInput(new SimpleExporterInput(jasperPrint));
    jrpdfexporter.setExporterOutput(new SimpleOutputStreamExporterOutput(stream));
    SimplePdfExporterConfiguration configuration = new SimplePdfExporterConfiguration();
    jrpdfexporter.setConfiguration(configuration);
    jrpdfexporter.exportReport();
    

    }

Now I have an outputstream which is essentially a PDF Stream that I want to display in a JSP. I don't want to set the whole response content type as application/pdf, but I want to embed the PDF into part of the JSP output

So, I converted the pdfstream output into a byte array and am trying to display it using the following

<script language="Javascript">
function loadDoc() {
    alert('called loadDoc');
    var xhr = new XMLHttpRequest();
    alert('called xhr');

    xhr.responseType = 'arraybuffer';
    alert('called responseType');

    alert('called xhr.onload ');

    // Create the Blob URL:
    var buffer = xhr.response;
    var blob = new Blob([<%=byteCharSet%>], {
        type: 'application/pdf'
    });
    var objectURL = URL.createObjectURL(blob);
    alert(objectURL);

    // Create an iframe to demonstrate it:
    var iframe = document.createElement('iframe');
    iframe.className = 'sample-iframe';
    iframe.src = objectURL;
    document.body.appendChild(iframe);
    console.log(objectURL);

    //xhr.open('GET', 'https://cors-anywhere.herokuapp.com/http://www.xmlpdf.com/manualfiles/hello-world.pdf', true);
    //xhr.send();
}
</script>

However, when I try to execute JavaScript, it couldn't understand the byte array output and simply fails. The blob value gets displayed as shown below in the view page source

     var blob = new Blob([%PDF-1.4
    %
    3 0 obj
   <</Filter/FlateDecode/Length 625>>stream
   xM0@>um'vC
   ^VĶH3?}     qD3
   q`e˼'Do?1(Ξh2sS(^gĈ^/bar"\"_ГLw

Answer №1

To address the issue at hand, I made use of an Iframe implementation.

Within the iframe tag, I specified another jsp file as the source.

       out.write("<iframe src= displayPDF.jsp" + " " + "type=application/pdf width=100% height=600px ");
            out.write("</iframe>");

The content of the displayPDF.jsp is as follows:

    <%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%><%
    byte[] pdfByteArray = (byte[]) session.getAttribute("PDFbyteArray");
    if (pdfByteArray == null)
        System.out.println("pdfByteArray is null");
    response.setHeader("Content-Disposition", "inline; filename=\"MyFile.pdf\"");
    response.setContentType("application/pdf; name=\"MyFile.pdf\"");
    ServletOutputStream serv_out = response.getOutputStream();
    serv_out.write(pdfByteArray);
    serv_out.flush();
    serv_out.close();
    out.clear();
    session.removeAttribute("PDFbyteArray");%>

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

How can you load elements via AJAX?

Using AJAX, I successfully load content from a PHP page. Now, my challenge is to access and interact with the dynamically loaded elements (such as buttons, forms, or divs). The code snippet that is causing issues: jQuery(document).ready(function() { $( ...

Fade background when the youtube video in the iframe begins playing

Hey there! I'm looking to create a cool effect on my (wordpress) site where the background dims when a YouTube video starts playing. The video is embedded in this way: <iframe frameborder="0" width="660" height="371" allowfullscreen="" src="https ...

Using jQuery to retrieve a value from a single class and numerous links

I'm facing a problem where I have a list of names and when a name is clicked, I want jQuery to pass the variable to another page. The current code I have only pulls the first name: $('.nameLink').live('click', function() { v ...

What is the best way to repair a react filter?

Recently, I successfully created a database in Firebase and managed to fetch it in React. However, my current challenge is to integrate a search bar for filtering elements. The issue arises when I search for an element - everything functions as expected. ...

Interactive JavaScript Linkage

Recently, I came across some code that I inherited (definitely not mine!) which uses a session variable in the HTML header to link to a specific javascript file. For example: <SCRIPT language="javascript" src="../JavaScript/<%=Session("jsFileName") ...

Guide to retrieving a .txt file from a separate domain using server-side JavaScript and transferring it to the client side

My goal is to retrieve a .txt file from a web server on a different domain that does not have CORS or web services enabled. I believe I will need to handle this task on the server side using Node.js and JQuery, but I am unsure of where to begin. Currently, ...

Creating dynamic layouts using Handlebars.js recursion

I'm working with a basic object hierarchy that includes: Category String name List childCategories; My goal is to use handlebars to represent this structure in a generic manner, but I'm struggling on how to nest layouts. Here's the curre ...

When using Node.js, you may encounter the error message: "TypeError: brevo.ApiClient is not a constructor

My goal is to set up an automatic email sending system that, upon receiving details like name and email, will send a confirmation email to the provided email address with the message "subscribed." I've been working on this task for about 7 hours strai ...

Increase the time of a Date by 10 seconds

Is there a way to increase the time of a JavaScript date object by 10 seconds? For example: var currentTime = new Date(); var currentSeconds = currentTime.getSeconds() + 10; currentTime.setSeconds(currentTime.getSeconds() + currentSeconds); ...

Is there a discrepancy in speed between Node.js http.get and Google Chrome's $.get function?

Recently, while experimenting with node.js, I decided to test out the following code snippet: var http = require("http"); function get() { var headers = { 'Accept-Encoding': 'gzip' }; var startedAt = new Date().get ...

Having trouble implementing Bootstrap Progress Bar with AJAX in webpy

I am currently working on a web application using webpy and dealing with a Bootstrap progress bar in the template HTML file. To update this progress bar dynamically, I aim to utilize jQuery AJAX calls to fetch data from the server. In order to achieve thi ...

Encountering a mixed content error in Internet Explorer 8 due to the Nivo slider jQuery?

I am encountering an issue with the Nivo jQuery slider on my HTTPS website, as it appears to be generating a mixed content error in Internet Explorer 8. Despite posting on the Dev7 Studios forum and conducting extensive research on the IE 8 mixed content ...

Sending a multi-dimensional array to the server using PHP via POST

Similar Question: multi-dimensional array post from form I am looking to transfer data from the client to the PHP server using jQuery's $.post() method. Once the data reaches the server, I want the $_POST['myList'] variable to be in one ...

Ways to dynamically assign a class to a single element within a group of identical elements

I have three identical items in the DOM. Specifically, I am referring to a moving line <span class="caret"></span> <ul> <li class="nav-item-1"> <a href="#">ITEM 1</a> <span class="caret"></span> ...

Revamping repetitive JavaScript code for the pagination of Instagram Stories

I'm currently developing a website that utilizes fullpage.js and includes a section with multiple slides. These slides automatically transition every 10 seconds. I wanted to implement progress bars similar to those on Instagram, where each bar fills ...

The window.open() function is malfunctioning on Google Chrome

Within my vue.js application, I have encountered an issue when attempting to utilize window.open() to open a new tab. Strangely, whenever I use this method, the new tab opens briefly before immediately closing without loading any content. Surprisingly, win ...

Implementing Ajax functionality in Ruby on Rails

I wish to send the selected drop-down menu value to a controller using ajax panel_controller.rb class PanelController < ApplicationController def insert @selected_city_ids = params[:city] end panel.js.erb $(document).ready(fun ...

Determine whether the regex pattern is positioned at the start of the string or following a designated character

I am working with a regex pattern and need to verify if it matches at the start of a string, after a new line, or after a white space. Additionally, I want to ensure that the pattern also matches the end of the string, after a new line, or a white space. ...

What is the best way to receive several responses from a PHP file using AJAX?

My PHP file is handling 2 operations: 1. Submitting data from a form into a database table, and 2. Sending an email. I am looking to display status messages through ajax. For instance, showing "First operation done, please wait for the second" and then di ...

Hear and register keypress in Angular service

I offer a dialog service Check it out below @Injectable() export class HomeDialogService { public constructor(private readonly dialogService: DialogService, private readonly userAgent: UserAgentService) {} @HostListener('document:keydown.escape ...