I am working with JasperReprots. This is part of my code:
ServletContext context = this.getServletConfig().getServletContext();
File reportF = new File(context.getRealPath(rF));
byte[] bytes = null;
ServletOutputStream servletOutputStream = resp.getOutputStream();
InputStream reportStream = new FileInputStream(reportF.getPath());
reportF.delete();
bytes = JasperRunManager.runReportToPdf(reportStream, new HashMap(),new JREmptyDataSource());
resp.setContentType("application/pdf");
resp.setContentLength(bytes.length);
servletOutputStream.write(bytes, 0, bytes.length);
servletOutputStream.flush();
servletOutputStream.close();
After this I can see pdf in my browser, but when I try to save it, the file has no extension pdf. How to add this extension without saving report on my server?
This should probably do the trick:
resp.setHeader("Content-Disposition", "attachment;filename=report.pdf");
Related
I am using java - Apache FOP to generate a PDF and here is the code inside an execute method of struts ActionFroward.
{
Random randomGenerator = new Random();
String generatedfile = "generatedfile"+"_"+sessionId+randomGenerator.nextInt(100)+".xml";
File file = new File(getServlet().getServletContext().getResource("/ttf/").getPath(),generatedfile);
FileOutputStream fStream = new FileOutputStream(file);
ByteArrayOutputStream out = new ByteArrayOutputStream();
byte[] b = reportXML.getBytes("UTF-8");
OutputStream outstream = fStream;
outstream.write(b);
outstream = new java.io.BufferedOutputStream(outstream);
String filePath = getServlet().getServletContext().getResource("/ttf/").getPath()+generatedfile;
xmlfile = new File(filePath);
Fop fop = fopFactory.newFop(MimeConstants.MIME_PDF, foUserAgent,out);
Source src = new StreamSource(xmlfile);
TransformerFactory factory = TransformerFactory.newInstance();
File xsltfile = new File(printStylesheetURI.getPath());
Transformer transformer = factory.newTransformer( new StreamSource(xsltfile));
Result res = new SAXResult(fop.getDefaultHandler());
transformer.transform(src, res);
byte[] pdfBytes = out.toByteArray();
response.setHeader("Pragma", "public");
response.setHeader("Expires", "0");
response.setHeader("Content-Disposition", "attachment; filename=\"" + generatedfile + ".pdf\"");
response.setContentType(MimeConstants.MIME_PDF);
response.setContentLength(pdfBytes.length);
outstream.close();
out.close();
response.getOutputStream().write(pdfBytes);
}
The PDF file is generated fine for the first time at the first request with PDF size 22KB. But for the second request, the PDF is getting corrupted and the size is only 15bytes. Again for the third request, the file is generated fine with 22KB as file size. Again for the 4th time it fails...
Am I doing anything wrong here? I tried debugging in the local, it is working file for all the requests. But after deploying on the server/environments, I am facing the issue.
Thanks in advance.
I am trying to write in an existing pdf file and want to open it in new browser at clients machine. I saw many post related this and i tried all answers but still i am not getting result. File can be generated on my disk but i want to open it at new window once created.
Code :
response.setContentType("application/pdf");
ByteArrayOutputStream baos = new ByteArrayOutputStream();
InputStream is = new FileInputStream("Challan.pdf");
PdfReader pdfReader = new PdfReader(is, null);
PdfStamper pdfStamper = new PdfStamper(pdfReader, baos);
for(int i=1; i<= pdfReader.getNumberOfPages(); i++){
Phrase Namephrase = new Phrase("John Smith");
Phrase Idphrase = new Phrase("DPG10001");
Phrase Datephrase = new Phrase("11/10/1980");
PdfContentByte pdfcontent = pdfStamper.getUnderContent(i);
pdfcontent.beginText();
ColumnText.showTextAligned(pdfcontent, Element.ALIGN_JUSTIFIED_ALL, Idphrase, 500, 428, 0); /*Do not change this values*/
ColumnText.showTextAligned(pdfcontent, Element.ALIGN_JUSTIFIED, Namephrase, 500, 407, 0);
ColumnText.showTextAligned(pdfcontent, Element.ALIGN_JUSTIFIED, Datephrase, 500, 386, 0);
pdfcontent.endText();
}
pdfStamper.close();
pdfReader.close();
// write ByteArrayOutputStream to the ServletOutputStream
response.setHeader("Content-Disposition", "inline;filename=ChallanStamped.pdf");
// the contentlength
response.setContentLength(baos.size());
ServletOutputStream sos = response.getOutputStream();
baos.writeTo(sos);
sos.flush();
sos.close();
In this i am trying to read challan.pdf and want to update file and create new one.From jsp i am calling this servlet.
Please help me.
Update:
I tried with some changes but still not working. My updated code is
` ByteArrayOutputStream baos = new ByteArrayOutputStream();
BufferedInputStream is = new BufferedInputStream(new FileInputStream("Challan.pdf"));
PdfReader pdfReader = new PdfReader(is, null);
PdfStamper pdfStamper = new PdfStamper(pdfReader, baos);
-----------Some Code -------------
pdfStamper.close();
pdfReader.close();
response.setHeader("Content-Disposition", "inline;filename=ChallanStamped.pdf");
response.setContentLength(baos.size());
output = new BufferedOutputStream(response.getOutputStream());
byte[] buffer = new byte[4096];
int length;
while ((length = input.read(buffer)) != -1) {
output.write(buffer, 0, length);
}
output.flush();
output.close();
input.close();
I am calling servlet from jsp through Ajax(sending lot of data).
And also i am getting java.io.IOException: Stream closed exception with this updated code.
In order to open the pdf file in new window you need to do some changes in your jsp form.
<form action="yourServletURLPattern" method="post" target="_blank">
-- Some Fields--
-- Submit Button--
</form>
target=_blank will do the needful.
Now coming to your servlet code :
ByteArrayOutputStream baos = new ByteArrayOutputStream();
---------- Some Code in between-----------------------
ServletOutputStream sos = response.getOutputStream();
baos.writeTo(sos);
But this do nothing since your ByteArrayOutputStream Object contains nothing so what will you write to ServletOutputStream
I will not write code for you but can guide, So that you can achieve it yourself
Read File after editing using BufferedInputStream
Write it on OutputStream of Response using BufferedOutputStream (Simply Loop
through the file)
Flush the Response's Output Stream
When I try upload the file from server, I use this code. I get the file size of 500kb, when the original file size about 300kb.
What am I doing wrong?
attachmentContent = applicationApi.getApplicationAttachmentContent(applicationame);
InputStream in = new BufferedInputStream(attachmentContent.getAttachmentContent().getInputStream());
ByteArrayOutputStream out = new ByteArrayOutputStream();
byte[] buf = new byte[1024];
int n=0;
while (-1 !=(n=in.read(buf)))
{
out.write(buf,0,n);
}
out.close();
in.close();
byte[] response = out.toByteArray();
File transferredFile = new File(attachmentName);
FileOutputStream outStream = new FileOutputStream(transferredFile);
attachmentContent.getAttachmentContent().writeTo(outStream);
outStream.write(response);
outStream.close();
Simplify. The same result:
File transferredFile = new File(attachmentName);
FileOutputStream outStream = new FileOutputStream(transferredFile);
attachmentContent.getAttachmentContent().writeTo(outStream);
outStream.close();
The ByteArrayOutputStream is a complete waste of time and space. You're reading the attachment twice, and writing it twice too. Just read from the attachment and write directly to the file. Simplify, simplify. You don't need 90% of this.
i try to download a pdf file from url using the code below. It works fine when the file size is under 8k and if the file is up to 8k, it downloads the pdf file but the file is not readable.
Code
InputStream in = new BufferedInputStream(url.openStream());
ByteArrayOutputStream out = new ByteArrayOutputStream();
byte[] buf = new byte[1024];
int n = 0;
while (-1!=(n=in.read(buf)))
{
out.write(buf, 0, n);
}
out.close();
in.close();
byte[] response = out.toByteArray();
FileOutputStream fos = new FileOutputStream(new File("C:\\temp\\TEST.pdf"));
fos.write(response);
fos.close();
System.out.println("Download Finished");
You may try using the IOUtils.copy(InputStream input, OutputStream output)
You can minimize the lines of code.
Apache IOUtils
When I try to view a video in the jwplayer from a file in the webcontent directory it shows up and I can play it, but when I read the same file from a database and respond with an flv via servlet it doesn't show up. Can any one help me?
In Html file :
<script type='text/javascript' src='/ThoughRecord18-8/jwplayer.js'></script>
<script type='text/javascript'>
jwplayer('mediaspace').setup({
'flashplayer': '/ThoughRecord18-8/player.swf',
'file': '/ThoughRecord18-8/videoss?videoId=1',
'controlbar': 'bottom',
'width': '470',
'height': '320'
});
</script>
and the servlet is
String videoId = request.getParameter("videoId");
if (videoId != null || !videoId.equals("")) {
VideoDao dao = new VideoDao();
Video video = dao.getVideo(videoId);
Blob blob = video.getVideoBlob();
byte[] buf = new byte[1024];
ByteArrayOutputStream baos = new ByteArrayOutputStream();
InputStream in = null;
int len;
try {
len = (int) blob.length();
byte[] rb = new byte[len];
InputStream readImg = blob.getBinaryStream();
int index = readImg.read(rb, 0, len);
...
response.reset();
response.setBufferSize(DEFAULT_BUFFER_SIZE);
response.setContentType("video/x-flv");
response.setContentLength(rb.length);
response.setHeader("Content-Disposition", "inline; filename=file.flv");
byte[] content = new byte[DEFAULT_BUFFER_SIZE];
BufferedInputStream is = new BufferedInputStream(
new ByteArrayInputStream(rb));
OutputStream os = response.getOutputStream();
while (is.read(content) != -1) {
os.write(content);
}
is.close();
os.close();**
This isn't a java issue, JW Player only supports HTTP Psuedo Streaming and RTMP Streaming. They're both their own protocols - you can't just stream the pure content at it. Take a look at this page: http://www.longtailvideo.com/support/jw-player/jw-player-for-flash-v5/12534/video-delivery-http-pseudo-streaming, and this page: http://www.longtailvideo.com/support/jw-player/jw-player-for-flash-v5/12535/video-delivery-rtmp-streaming for info on how JW Player does streaming.
If you don't want the user to have to wait to get all of the content, you'll need to go with one of those streaming mechanisms. If that's not an issue, you could consider changing your servlet to write the file somewhere in your webcontent directory and then do a redirect to the file or something, but I don't think writing to the response stream like that is going to do the trick.