Using my spring controller I want to directly open the printing view of generated pdf.By now I am generating a pdf using iTextPDF and put it to the OutputStream (HttpServletResponse.getOutputStream()).It is downloading the pdf. I can open it in browser and print using print button.
What I want is getting the print UI from the controller or without print UI send to the printer.
I have added some of my controller method,
String mimeType = "application/pdf";
System.out.println("MIME type: " + mimeType);
response.setContentType(mimeType);
String headerKey = "Content-Disposition";
String headerValue = String.format("theCoder379.PDF");
response.setHeader(headerKey, headerValue);
OutputStream outStream = response.getOutputStream();
createPdf(outStream, theObject);
outStream.close();
In createPdf(outStream, theObject) method it is adding the generated iText pdf using 'theObject' to the 'outStream'.
How can I achieve this.
It is not possible the way you want (from the server side).
By now I am generating a pdf using iTextPDF and put it to the OutputStream
Good. That's effectively all you can do from the server side code.
I can open it in browser and print using print button
The browser loads an external application (pdf plugin/viewer) and let the plugin display the file you've generated. You have no control over it whatsoever.
However you may create your own page with embedded plugin.
<object data="./pdfServlet" type="application/pdf" width="100%" height="100%">
<p>Alternative text - include a link to the PDF!
</p>
</object>
and try to invoke the print event in the client-side javascript.
window.print();
However - I see some potential issues
it may not work on all browsers and all version you may want
some people (myself included) are sensitive if a web page tries to do thing the are not explicitly asked for (such as printing)
Related
I'm trying to open a PDF file by requesting it from Rest endpoint. But in this case, the file is getting downloaded. I tried opening it in another window. There also it just shows new window and downloads it there.
I used Chrome. So in Chrome by default it downloads the file while in Firefox it shows the dialog box whether to open it or save it. I don't want that dialog box. But want to display the file in new window with all the features like download, print, etc which a normal pdf viewer will show.
Is there some way through which I can avoid downloading of the file by default and just display that file in another window? Content-Disposition is attachment; filename="abc.pdf" when I see the properties of the URL. Also, its content-type is application/pdf;charset=utf-8.
<a target="_blank" data-content-type="application/pdf" onclick="open(this.href, this.target, 'fullscreen=yes'); return false;" data-type="downloadTenPointDocument" href="<c:out value="${resultItem.offer.programInfoUrl}"/>">View 10-point</a>
I changed the properties of pdf file from attachment to inline and set it in response:
response.setContentType("application/pdf");
response.addHeader("Content-Disposition", "inline; filename=" + fileName + ".pdf");
I am requesting the pdf file from server and then reading it and setting it in response, changing the properties of it in response, so that its default behavior of getting downloaded is overwritten.
Thank you everyone. The answer to change the property of pdf file was right.
You won't be able to do it directly from REST endpoint.
Use target="_blank" in anchor element on your page.
go
You should try to erase attachment; property from content disposition header.
i did like that and it worked: (it wont start to download, and it will open in a new tab (target _blank) if same tab, thenit is (target _self)
show pdf in a new tab
How can I grab a page's HTML in java if the page has infinite scroll? I'm currently grabbing a page this way:
URL url = new URL(stringUrl);
URLConnection con = url.openConnection();
InputStream in = con.getInputStream();
String encoding = con.getContentEncoding();
encoding = encoding == null ? "UTF-8" : encoding;
String html = IOUtils.toString(in, encoding);
Document document = Jsoup.parse(html);
But it doesn't return any of the content associated with the infinite scroll section of the page. How can I trigger this scrolling on the HTML page so that my Jsoup document contains this section?
Infinite scroll describes a technique where the page does not contain the content. Some JavaScript code runs in the browser, sends a request to the server for addiional content and adds it to the page. When you scroll towards the end of the available content, the JavaScript code repeats the process: it sends another request and adds the additional content.
Therefore, you need a web browser with a JavaScript engine that can run the JavaScript code and produce the events that cause the code to load content.
#dsh is right, the content is most likely loaded dynmically via AJAX. As an alternative to using a real browser, i.e. selenium webdriver, you may look into the network traffic and idetify the API call that the page triggers. You can maybe call that Api directly with Jsoup. Often the content is however not HTML but JSON, XML or some other format. It still may be very worth while doing this, since using webdriver is often pretty slow and resource-heavy.
I want to setup response for PDF output. How do I achieve this?
I can setup for Excel output and successfully get the desired excel sheet from the browser, but for PDF I could not get the desired output.
For Excel the following code works fine
String excelContent = "an html table..";
getServletResponse().setContentType("“application/vnd.ms-excel");
getServletResponse().setHeader("Content-Disposition","inline; filename=" + pageTitle + ".xls");
PrintWriter ps = getServletResponse().getWriter();
ps.println(excelContent);
But for PDF I tried setting the content type to PDF, but could not get it properly (no content gets displayed even though a PDF file is opened in the browser)
String excelContent = "an html table..";
getServletResponse().setContentType("“application/pdf");
getServletResponse().setHeader("Content-Disposition","inline; filename=" + pageTitle + ".pdf");
PrintWriter ps = getServletResponse().getWriter();
ps.println(excelContent);
Do html tables cannot be displayed as such in PDF?
It's very simple with the Flying Saucer renderer. It takes HTML input and returns PDF. What you have to do is to declare content type as PDF, generate HTML to a string, and call a method from Flying Saucer.
Here is an example
xhtml to pdf servlet with flyingsaucer
You are writing html context to the response stream. You need to write pdf format to the response.
You can use libraries like iText or Apache FOP to create PDF format.
I need to open a pdf file for the user who clicks on a download button.
The download button makes a ajax call to a servlet which gets data from a blob field in the database containing PDF contents, and returns it as a response.
What can I do in order to make the response to be downloaded as a PDF file to the user.
The servlet code is as below:
response.setContentType("application/pdf");
oracle.sql.BLOB blob = (BLOB) rs.getBlob("MYPDF");
byte[] bytes = blob.getBytes(1, (int) blob.length());
ServletOutputStream servletOutputStream = response.getOutputStream();
servletOutputStream.write(bytes, 0, bytes.length);
servletOutputStream.flush();
servletOutputStream.close();
I receive a long response containing characters like the ones below in AJAX when I checked the Fire bug for the response.
�a�J��㔎��ji�2K���y�2��q F�f�9�G��!%�kɂ��W��������mp){h̕�S���NJ_�A����'����2k��j���яR�>wB�e�|=w�p�%w��qǦ>�~�1o�㾙9j�B�;aNx3�`z��طc�O��ï��$�;�N|;�xۇ��;�-�c�f�M��c���(�f�M6K���
I don't want to submit the page or to popup a window for the servlet with the parameters sent for the query showing in the URL
I also don't want to create the file on the server.
Is there a way to take the response of servlet coming in ajax call and display it to a page or Iframe and the browser automatically downloads the file...
Its is NOT possible to download a file using Ajax. However, the same 'effect' can be achieved using a hidden IFRAME. Instead of using XMLHttpRequest, dynamically create a hidden iframe and submit it to the servlet with the proper parameters. When the response comes, the browser will automatically handle the content based on the content-type/extension. If you are using jQuery, then this plugin has this functionality in-built.
Sounds like Rahulmohan knows his stuff but it might be worth trying to add a filename header to your response stream. I do something similar in asp.net but not in an Ajax environment and the only difference between my code and yours is this line:
Response.AddHeader("Content-Disposition", "attachment; filename=" & Filename & ".pdf")
My page doesn't run in an Ajax environment though.
This question already has answers here:
How to retrieve and display images from a database in a JSP page?
(6 answers)
Closed 7 years ago.
I currently have to generate an image that displays the text of a string, i need to make this image on a Servlet and then somehow pass the image to a JSP page so that it can display it. I'm trying to avoid saving the image, and instead somehow stream the image to the JSP.
I haven't found a way of generating the image since i started with finding how to pass an image from the Servlet to the JSP adn got stuck.
EDIT:
The jsp page is already made and isn't created by the servlet, i have to pass the image into an already existing jsp
Any help is appreciated.
You need to write the image as a byte array to the response's output stream. Something like this:
byte[] imageBytes = getImageAsBytes();
response.setContentType("image/jpeg");
response.setContentLength(imageBytes.length);
response.getOutputStream().write(imageBytes);
Then in you JSP you just use a standard img element:
<img src="url to your servlet">
You can't1 return both in the same response, since you're returning different types (an HTML page of type text/html and an image of type image/jpeg, say).
For this sort of thing, I will generate the image during the initial servlet request (for the containing HTML page). I store it in a cache in my servlet, and write the HTML page with the image tag containing a URL to that image with the handle.
e.g. the browser asks for http://whatever/page
The servlet generates the image, and writes an HTML tag in the page like
<img src="http://whatever/image/unique_handle_to_image">
The browser will render the HTML page, and as part of that issue a new request to my servlet with the handle for the image.
e.g. the browser now asks for http://whatever/image/unique_handle_to_image
I then return the image as content type image/jpeg or similar.
So you have two requests going on. One for the page, in which you render the image and store it temporarily, and the second in which you return the image. You have to remember to clear the image cache, but that's all straightforward. I wouldn't worry about storing lots of images, since the two requests from the browser usually (!) come in quick succession.
I guess it's possible to use a data uri provided your browser supports it, and create something like
<img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAoAAAAKCAYAAACNMs+9AAAABGdBTUEAALGPC/xhBQAAAAlwSFlzAAALEwAACxMBAJqcGAAAAAd0SU1FB9YGARc5KB0XV+IAAAAddEVYdENvbW1lbnQAQ3JlYXRlZCB3aXRoIFRoZSBHSU1Q72QlbgAAAF1JREFUGNO9zL0NglAAxPEfdLTs4BZM4DIO4C7OwQg2JoQ9LE1exdlYvBBeZ7jqch9//q1uH4TLzw4d6+ErXMMcXuHWxId3KOETnnXXV6MJpcq2MLaI97CER3N0vr4MkhoXe0rZigAAAABJRU5ErkJggg==" alt="Red dot" />
Note there are a number of caveats surrounding these. See the linked page.
I would do something along this lines to achieve this:
On the JSP page you put a link to an image:
<img src="servlet/path?word=value">the rest</img>
This link points to your servlet, it generates image using request parameters, you do not need to save it, just put it right into response's output stream. You have to remember to disable browser caching for this servlet.
JSP page is displayed first, next all the images are requested, it should work just fine.
Of course, you should not put the text to display in a parameter like this, you should propably encipher it somehow or store it in a HTTP session.
Hope this helps.
If I understand your problem correctly, the sequence of events will be:
You generate an HTML page;
That HTML page is sent to the client; and
The client's browser reads the image URL and requests it as a separate request.
So, you can't generate the image and pass it to the JSP. You can however generate a URL to get the image and put that in the JSP. That's easy enough to pass by the servlet putting it on the HttpServletRequest object (request scope in JSP). For example, generate:
<a href="http://myhost.com/image_servlet?id=1234"/>
You don't really say what that text is or what information is required to generate the image. If you can't encapsulate that in a GET URL, you may need to add extra information and put it in the HttpSession so it can be retrieved on the next get image request.
...
response.setContentType("image/jpeg");
response.setContentLength(imageBytes.length); // imageBytes - image in bytes
response.getOutputStream().write(imageBytes);//
outStream.flush();
outStream.close();