write to a pdf file from a servlet response
888525Apr 15 2013 — edited Apr 16 2013I have a servlet which is connecting to a url.i want to display the contents of this url which is a pdf file
in the browser.How do I achieve this in the servlet?
I was thinking if I could write to a sample pdf file placed at a location the response from the servlet and then show that file in the browser.Is there any direct way to display the pdf directly from the servlet in the browser.
B elow the servlet code I am using. I am sure i am missing something.I am geting the response back but nothing is written to the test.pdf file.How can I use the response I am geting back from the url to show as a pdf file?
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
try {
DefaultHttpClient http = new DefaultHttpClient();
final String username = "doamin\\userid";
final String password = "password";
UsernamePasswordCredentials c = new UsernamePasswordCredentials(username, password);
BasicCredentialsProvider cP = new BasicCredentialsProvider();
cP.setCredentials(AuthScope.ANY, c);
http.setCredentialsProvider(cP);
String urlString = "http://mymachine/TestServer/Pages/ReportViewer.aspx?"
+ "/TestReport&rs:Command=Render¶m1=1"
+ "&rs:format=pdf";
URL url = new URL(urlString);
HttpPost post = new HttpPost(url.toURI());
HttpResponse response1 = http.execute(post);
HttpEntity entity = response1.getEntity();
System.out.println(" The statusline is" + response1.getStatusLine());
System.out.println("the content is" + entity.getContent());
File tempPDFFile = new File("//mymachine//testreports/test.pdf");
try {
FileInputStream fileInputStream = new FileInputStream(tempPDFFile);
OutputStream responseOutputStream = response.getOutputStream();
int bytes;
while ((bytes = fileInputStream.read()) != -1) {
responseOutputStream.write(bytes);
}
System.out.println("Servlet sucessfully completed");
} catch (Exception e) {
e.printStackTrace();
System.err.println("document: " + e.getMessage());
}
} catch (Exception ex) {
System.out.println("The exception is" + ex);
}
}
Please help.
Thanks,