Display PDF in webpage - java

To follow up to this post I change the code to this:
#RequestMapping( value = "/{prePath:^tutor$|^admin$}/module/{file_id}" )
public void getModule( #PathVariable( "file_id" )
int fileId, Model model, HttpServletResponse response, HttpServletRequest request )
{
model.addAttribute( "id", fileId );
File test = new File( "C:\\resource\\pdf\\test.pdf" );
response.setHeader( "Content-Type", "application/pdf" );
response.setHeader( "Content-Length", String.valueOf( test.length() ) );
response.setHeader( "Content-Disposition", "inline; filename=\"test.pdf\"" );
System.out.println( test.toPath() );
try
{
Files.copy( test.toPath(), response.getOutputStream() );
}
catch( IOException e )
{
e.printStackTrace();
}
}
And finally able to display PDF in the webpage. The URL is accessed by:
<a href="../admin/module/${ file_id }.do?test" >Spring Tutorial</a>
But the PDF file is displaying on the whole page. My PDF is from my local I want to display it with just a portion of webpage. Maybe a <div> or anything that suit the approach best. Any thoughts of how can I do this?

Just iframe it if the user has adobe pdf then they will be able.to see in in there browser

<?php
$file = "file.pdf";
$read = file_get_contents($file);
echo $read;
?>

Related

Convert UTF-8 to windows-1252 and write into csv in gwt 2.7.0 on tomcat v7

I am facing a problem with converting UTF-8 to windows-1252. I have to output symbols like ²,³,°. The customer wants to open the file in Excel without importing the file by double clicking.
System:
Frontend in gwt 2.7.0 with massive usage of gxt 3.1.4
Server on customer side is a tomcat v7
Testing is done on gwt build in server
The problem right now is, that the application supports Japanese symbols, which are displayed perfectly fine in UTF-8 but not in windows-1252. On the other hand, the ²,³,° symbols are displayed. The current solution is to collect the rows of the csv and put them in hidden fields inside a FormPanel. The FormPanel is then encoded and submitted.
public void postCsvForExcel( String url, Map<String, String> postData )
{
setSize( "0px", "0px" );
setVisible( false );
sinkEvents( Event.ONLOAD );
setMethod( FormPanel.METHOD_POST );
setEncoding( FormPanel.ENCODING_URLENCODED );
VerticalPanel panel = new VerticalPanel();
add( panel );
for( Entry<String, String> data : postData.entrySet() )
{
Hidden hiddenField = new Hidden( data.getKey(), data.getValue() );
panel.add( hiddenField );
}
SubmitButton submit = new SubmitButton();
panel.add( submit );
setAction( url );
FormElement.as( this.getElement() ).setAcceptCharset( "Cp1252" );
RootPanel.get().add( this );
submit();
}
The Japanese characters are only displayed in the header. Facing this problem, I have extended the HttpServlet for POST operations to translate the UTF-8 like following and removed the FormElement.as( this.getElement() ).setAcceptCharset( "Cp1252" ); part from the method above.
public class ExporterServlet extends HttpServlet {
public ExporterServlet() {
}
#Override
protected void service(HttpServletRequest arg0, HttpServletResponse arg1)
throws ServletException, IOException {
super.service(arg0, arg1);
}
#Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
String filename = req.getParameter("filename");
String content = req.getParameter("content");
if(filename != null) {
//resp.setContentType( getContentType( filename ) + "; charset=utf-8" );
resp.setContentType( "text/csv" + "; charset=windows-1252" );
resp.setHeader( "Content-Disposition", "attachment;filename=\"" + filename + "\"" );
resp.setIntHeader("Expires", 0);
resp.setContentLength(content.length());
resp.setStatus(200);
//resp.setCharacterEncoding( "UTF-8" );
resp.setCharacterEncoding( "windows-1252" );
//byte[] destinationBytes = content.getBytes( "utf-8" );
ByteBuffer bb = ByteBuffer.wrap( content.getBytes() );
CharBuffer cb = Charset.forName( "UTF-8" ).decode( bb );
bb = Charset.forName( "windows-1252" ).encode( cb );
resp.getOutputStream().write( bb.array() );
resp.getOutputStream().flush();
}
}
}
But this seems not to work. Am I missing sth.
Further information: I have observed one strange thing. The doPost method, although being called has no effect on the encoding of the file. I have tried to encode it in UTF-8 but the output was still windows-1252. When I removed the encoding of the FormPanel in the method before, the result was UTF-8.
Another question is, what is the correct encoding for windows-1252, I have tried both versions, cp1252 and windows-1252, I cant spot a difference in the result.
Japanese characters cant be displayed in cp1252. The instruction itself was not investigated properly. The customer doesn't know what cp1252 is capable of. Should have checked that before working on a solution.
You can add the following code, and try it again:
filename = new String(filename.getBytes(), "ISO-8859-1");

Calling a jsp multiple times from single doPost() method

I am using PD4ML libraries for converting my .jsp to pdf files and I need to call the same jsp file for a List of values.
I am doing this in my doPost()
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String [] posSelected = request.getParameterValues("selectPOs");
for(String eachPO: posSelected){
request.getRequestDispatcher("CreateInvoices.jsp").forward(request,response);
//This does not work as can not create multiple instances of servlet.
}}
I get java.lang.IllegalStateException: Cannot forward after response has been committed exception.
How can I invoke same JSP multiple times?
Thanks
MekaM
How can I invoke same JSP multiple times?
By including it multiple times.
request.getRequestDispatcher("CreateInvoices.jsp").include(request, response);
By using Include instead of Forward on Request Dispatcher.
You can call same jsp multiple time suing include.
It will look something like this.
request.getRequestDispatcher("CreateInvoices.jsp").include(request,response);
As mentioned by others you can send only one response per request in HTTP protocol hence you need to try another approach.
In your case since pd4ml is mandatory and here you need multiple pdfs hence creating multiple jsp is not the ideal way. Hence rather than converting the jsp to pdf you should create the multiple pdf through the code as shown in the link
http://pd4ml.com/examples.
private void runConverter(String urlstring, File output) throws IOException {
if (urlstring.length() > 0) {
if (!urlstring.startsWith("http://") && !urlstring.startsWith("file:")) {
urlstring = "http://" + urlstring;
}
4 java.io.FileOutputStream fos = new java.io.FileOutputStream(output);
5 if ( proxyHost != null && proxyHost.length() != 0 && proxyPort != 0 ) {
System.getProperties().setProperty("proxySet", "true");
System.getProperties().setProperty("proxyHost", proxyHost);
System.getProperties().setProperty("proxyPort", "" + proxyPort);
}
6 PD4ML pd4ml = new PD4ML();
7 try {
pd4ml.setPageSize( landscapeValue ? pd4ml.changePageOrientation( format ): format );
} catch (Exception e) {
e.printStackTrace();
}
if ( unitsValue.equals("mm") ) {
pd4ml.setPageInsetsMM( new Insets(topValue, leftValue,
bottomValue, rightValue) );
} else {
pd4ml.setPageInsets( new Insets(topValue, leftValue,
bottomValue, rightValue) );
}
pd4ml.setHtmlWidth( userSpaceWidth );
8 pd4ml.render( urlstring, fos );
}
}
I have used jsoup.connect().get() to achieve what I wanted.

Displaying streamed pdf in iframe

I have a servlet that streams a pdf as such:
ServletOutputStream out = response.getOutputStream();
byte[] pdfByteArray = JasperExportManager.exportReportToPdf(jasperPrintObject);
response.reset();
response.setContentType("application/pdf");
response.addHeader("Content-Disposition","inline;filename=temp.pdf");
out.write(pdfByteArray, 0, pdfByteArray.length);
out.flush();
out.close();
This works fine when I call the servlet. Now I use ajax to call the servlet and display the pdf in an iframe. I try to do that as such:
$('#form1').on('submit', function(e) {
$form = $(this);
$.post($form.attr('action'), $form.serialize(), function(responseText) {
$('#frm').attr('srcdoc', responseText);
});
return false;
});
The iframe however ends up with the following data:
%PDF-1.4 %���� 4 0 obj <>stream x���Ko7� �P#�>,َ����I���W{襐m�"K�I�S�(�C{���p� ۝Yv�� �z~��[�á�W��U7-�QT����Uw�M�K�hDpѷ�, Vݓ�8��`�{�����Z��(������((�QX��%A\��E���_����X]�wj����^M��Q'j�nԭ��(����'��+����.��<�Fa�Jx�~T<.¸��(����}g��Bx�~ ���!�0ɟR�g�i����,���o'�( ��>:I�������B����pt捎J5.�k�����R㢪B]�u{�Oj��:jT��f)Lj�X\�IKN63���o��T���4g��n�9\��dhIˊ�������s}#�
and it ends with %EOF. In the servlet I have reset the response and set the content type. What else should I do so that the pdf displays properly?
I found a solution to the above problem. I kept the servlet code as is but changed the query to the following:
$('#form1').on('submit', function(e) {
$form = $(this);
$.post($form.attr('action'), $form.serialize(), function(responseText) {
$('#processing2').fadeOut();
$('#frm').attr('src', 'theServlet?x=' + $('#x').val() + '&y=' + $('#y').val());
});
return false;
});
So basically instead of using the data in responseText, I re-call the servlet while passing the parameters. Of course, this means that the actual code has to be in the doGet method of the servlet.

Testing writing into a csv file using JUnit [duplicate]

This question already has an answer here:
JUnit testing for IO
(1 answer)
Closed 8 years ago.
I am new to junit testing and I want to write unit tests. Actually the methods does not return anything. It take the a list of signals and write it to a csv file. I am not sure how to test methods with void return types.
Anyone can help me ?
public void createCSV ( final ArrayList< Signal > messages, File file )
{
try
{
// Use FileWriter constructor that specifies open for appending
csvOutput = new MyWriter( new FileWriter( file, false ), ',' );
// Create Header for CSV
csvOutput.writeRecord( "Message Source" );
csvOutput.writeRecord( "Message Name" );
csvOutput.writeRecord( "Component" );
csvOutput.writeRecord( "Occurance" );
csvOutput.writeRecord( "Message Payload with Header" );
csvOutput.writeRecord( "Bandwidth(with Header %)" );
csvOutput.writeRecord( "Message Payload" );
csvOutput.writeRecord( "Bandwidth(%)" );
csvOutput.endOfRecord();
for ( Signal signal : messages )
{
csvOutput.writeRecord( signal.getSource() );
csvOutput.writeRecord( signal.getName() );
csvOutput.writeRecord( signal.getComponent() );
csvOutput.writeRecord( Integer.toString( signal.getOccurance() ) );
csvOutput.writeRecord( Integer.toString( signal
.getSizewithHeader() ) );
csvOutput.writeRecord( Float.toString( signal
.getBandwidthWithHeader() ) );
csvOutput.writeRecord( Integer.toString( signal.getSize() ) );
csvOutput.writeRecord( Float.toString( signal.getBandwidth() ) );
csvOutput.endOfRecord();
}
}
catch ( IOException e )
{
logger.error( "Error in writing CSV file for messages", e );
}
finally
{
try
{
if ( csvOutput != null )
{
csvOutput.flush();
csvOutput.close();
}
messages.clear();
}
catch ( IOException ex )
{
ex.printStackTrace();
}
}
}
}
One takes a map and sort it.
Pass in a map with known, unsorted values. Verify the map has been sorted after the method was called.
The other take the sorted map and write it to a csv file. I am not sure how to test methods with void return types.
Two options:
Pass in a temporary file path, e.g. see JUnit temporary folders, then read that file after the method has been called and test it for correctness.
Adjust your method to accept an OutputStream instead of a File. Then you can pass a ByteArrayOutputStream and verify its contents by calling toByteArray() and inspecting the bytes.
Unit test for File
If you dont want to change the src code:
In the unit test I would pass a file to a temp path, call that create csv method and
then open the file and dependendent of how many effort you want to invest:
check
1) if the file exists (use a filename genereated that contains the current time)
2) check that the length is more than 0 bytes
3) read the first and last line and check for expected content
But in most cases, an OutputStream is more flexible than a File parameter.
In productive code you pass a FileOutputStream, in your unit test a ByteArrayOutputStream, which you can parse using an ByteArrayInputStream.
This is the cleaner solution, since it does not create files which should be cleaned up, and it runs faster.
Unit test for sorting
Just create an unsorted map. call you sort, and check the result to be sorted:
Iterate and check that each next element is e.g greater than the previous one (or smaller depending on the sort order)
Just

sendind an image URL from servlet to web document

I'm trying to send an image url to the browswer using javascript and servlet.
I'm doing the following
In html :
<script type="text/javascript" src="../licenta/WebRoot/Scripts/choosebanner.js"></script>
In javascript :
window.onload = Onload;
function OnLoad()
{
var requestURI = window.location;
var resolution = screen.width + 'x' + screen.height;
var colorDepth = screen.colorDepth;
var query = '?requestURI=' + encodeURIComponent(requestURI)
+ '&resolution=' + encodeURIComponent(resolution);
document.getElementById("body").innerHTML = "<img src ='http://dan-vaio:8080/licenta/ bannerimg.gif'" + query + " width = 500 height = 200 />";
}
in servlet:
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
HttpSession session = request.getSession();
String requestURI = request.getParameter("requestURI");
String resolution = request.getParameter("resolution");
response.setContentType("text/html; charset=UTF-8");
String img = "http://dan-vaio:8080/licenta/advertiser/banners/leader.jpg";
PrintWriter out = response.getWriter();
out.print(img);
out.close();
}
The problem is that i can't get the image to be displayed. Javascript works fine, calls the server, the servers prints the respsone, but the jpg isn't showed in the html page.Any hints on how to get this working ?
Thanks a lot
I think you want to deliver the image itself, not its path. Read the image file in the servlet and write the binary to the response. Another way would be to set the src in the javascript to the response of the servlet. But then you need an Ajax call to the servlet, read the response and write it in the img src tag. The way you are doing it, you point the img src to a string and that of course won't display an image.
It's about your content type. You should set the content type of the response to image/jpeg. This way your navigator will understand that it's an image. You should change it like this :
response.setContentType("image/jpeg");
That's if you're serving jpeg images, Otherwise please follow this like to find your convenient content type : http://www.w3schools.com/media/media_mimeref.asp
Steps:
You need to convert image to FileInputStream.
Then set response.setContentType("image/jpeg");
Example:
FileInputStream fileIS = new FileInputStream("sample.jpg");
response.setContentLength(fileIS.available());
int i = 0;
while ((i = fileIS.read()) != -1) {
out.write(i);
}
fileIS.close();

Categories

Resources