doc file not displayed in jsp - java

I am doing a JSP site,using hibernate
where I need to display PDF files,doc files etc . I have byte array of PDF/doc file by webservice and I need to display that byte array as PDF file/doc in HTML.i convet this into pdf by using the following code and its correctly shows in html page
byte[] pdf = new byte[] {}; // Load PDF byte[] into here
if (pdf != null) {
// set pdf content
response.setContentType("application/pdf");
// write the content to the output stream
BufferedOutputStream fos1 = new BufferedOutputStream(
response.getOutputStream());
fos1.write(ba1);
fos1.flush();
fos1.close();
}
for doc file i change the response.ContentType from
response.setContentType("application/pdf");
to
response.setContentType( "application/msword" );
but instead of displaying its is showing a down load window.how can i resolve this issue

Try this:
01 response.setContentLength(pdf.length);
Any proxy or antivirus or firewall may guess the download is completed. So inform the browser how many bytes you wish to transfer.

Related

How to read the pdf content from response and write it to another new pdf file

%PDF-1.4
%����
1 0 obj
<<
/Type /Catalog
/Pages 9 0 R
/Outlines 8 0 R
/Names 6 0 R
i am trying to read above pdf content response from rest end point in java class and trying to write it to another file
but the file is getting corrupted and I could not view the pdf generated
File file = new File("Data.pdf");-- trying to write data to this
FileOutputStream out = new FileOutputStream(file)
\\service call to download pdf document
out.write(response.getBody().getBytes());
how to write the pdf content to another file or generate new pdf in a proper way?
Basically you want to read from an InputStream and then write to an OutputStream. This question has been answered several times e.g. here, here and here and there are lots of possible solutions. Since you also tagged ioutils one possible way is to:
File file = new File("Data.pdf");
FileOutputStream out = new FileOutputStream(file)
IOUtils.copy(response.getBody(), out);
This presumes that response.getBody returns an InputStream. If you supply more code we can tell for sure. (This depends on your restclient implementation you are using like JAX-RS, Spring-Rest, Apache httpClient or HttpUrlConnection...
PdfReader class in iText 7 has got an overloaded version that takes InputStream as an argument. Using this method, you can basically read the bytes of your first input pdf using ByteArrayInputStream. iText 7 has got a PDFWriter class that can write to an OutputStream too. Please refer to the following snippet. PdfDocument class then can read the input pdf file and write it to a new file using pdfWriter.
//Pdf bytes returned by some rest API or method
byte[] bytes = {};
ByteArrayInputStream bin = new ByteArrayInputStream(bytes);
//File where you want to write the pdf and update some content
File file = new File("Data.pdf");
FileOutputStream out = new FileOutputStream(file);
PdfDocument dd = new PdfDocument(new PdfReader(bin), new PdfWriter(out));

sending bytes as pdf

EDIT: The data I wanna send is in an rds. I fetch that into an output stream and then try to send it over as a pdf to the user.
The file gets generated but on opening the browser shows 'Failed to load PDF document.'
I have read that setting the ContentType to "application/pdf" helps but it does not in my case. The code is given below
byte[] b = generateFileService
.getDeviceHumidityRecordByPeriod(deviceIdValue, parseUnixTimestamp(startTime), parseUnixTimestamp(endTime));
OutputStream output = response.getOutputStream();
response.setContentType("application/pdf");
response.addHeader("Content-disposition", "attachment;filename=test.pdf");
output.write(b);
output.close();
response.flushBuffer();
}
if I change the file name to test.csv and then use content type as txt/plain, it works perfectly and a csv file is written.
I used Apache PDFBox to write data into a pdf file. The page offset needs to be tracked to add pages dynamically. Then you can convert the pdf into bytes and send it to the client by specifying response.setContentType("application/pdf") and response.addHeader("Content-disposition", "attachment;filename=test.pdf")

How to create a txt file with a String content and download that txt file

I am using java and struts. I have a scenario where there is 'Download' link in the page. After clicking on this link the control goes to the Action class, where I have String content which I need to write to a .txt file and then download that txt file.
Eventually whenever we click on the download link, we should be able to download a txt file having content a particular string.
I used below piece of code,
FileOutputStream outputStream = new FileOutputStream(fileNameWithDirectory);
outputStream.write(fileContentString.getBytes());
outputStream.close();
ActionForward forward = new ActionForward("doc/" + filename);
forward.setName(filename);
forward.setRedirect(true);
return forward;
Also I tried with FileWriter in place of FileOutputStream like,
FileWriter fileWriter = new FileWriter(fileNameWithDirectory);
fileWriter.write(fileContentString);
fileWriter.flush();
fileWriter.close();
But always instead of downloading the txt file, the control opens a new window where the String content is written.
Please suggest me, how would I able to download that .txt file.
You should add Content-Disposition: attachment to say browser, that it should download the file, not to open it.
See more details here
Also Struts has DownloadAction, you may use it as well.
You don't need to write the file and then redirect to it. You can set a http response header called Content-Disposition and then print your data into the http response body.
use it like this
response.addHeader("Content-Disposition", "Content-Disposition: attachment; filename=\""+filename+"\"");
of course this depends on which technology stack you're using.
Convert your text file to stream. and set content type as you wanted to download.
response.setContentType("application/pdf");
try {
// get your file as InputStream
InputStream is = ...;
// copy it to response's OutputStream
org.apache.commons.io.IOUtils.copy(is, convertedTextFiletoStream);
} catch (IOException ex) {
log.info("Error writing file to output stream. Filename was '{}'", fileName, ex);
throw new RuntimeException("IOError writing file to output stream");
}

How to convert InputStream to a PDF in Java, without damaging the file?

I have an InputStream which I would like to convert to a PDF, and save that PDF in a directory. Currently, my code is able to convert the InputStream to a PDF and the PDF does show up in the correct directory. However, when I try to open it, the file is damaged.
Here is the current code:
InputStream pAdESStream = signingServiceConnector.getDirectClient().getPAdES(this.statusReader.getStatusResponse().getpAdESUrl());
byte[] buffer = new byte[pAdESStream.available()];
pAdESStream.read(buffer);
File targetFile = new File(System.getProperty("user.dir") + "targetFile2.pdf");
OutputStream outStream = new FileOutputStream(targetFile);
outStream.write(buffer);
Originally, the InputStream was a pAdES-file (https://en.wikipedia.org/wiki/PAdES). However, it should be able to be read as just a regular PDF.
Does anyone know how to convert the InputStream to a PDF, without getting a damaged PDF as a result?
Hello it might be a bit late but you can use PDFBOX api (or itextpdf)
https://www.tutorialkart.com/pdfbox/create-write-text-pdf-file-using-pdfbox/
here is a tuto of the process gl

Append full PDF file to FOP PDF

I have an xml file already being created and rendered as a PDF sent over a servlet:
TraxInputHandler input = new TraxInputHandler(
new File(XML_LOCATION+xmlFile+".xml"),
new File(XSLT_LOCATION)
);
ByteArrayOutputStream out = new ByteArrayOutputStream();
//driver is just `new Driver()`
synchronized (driver) {
driver.reset();
driver.setRenderer(Driver.RENDER_PDF);
driver.setOutputStream(out);
input.run(driver);
}
//response is HttpServletResponse
byte[] content = out.toByteArray();
response.setContentType("application/pdf");
response.setContentLength(content.length);
response.getOutputStream().write(content);
response.getOutputStream().flush();
This is all working perfectly fine.
However, I now have another PDF file that I need to include in the output. This is just a totally separate .pdf file that I was given. Is there any way that I can append this file either to the response, the driver, out, or anything else to include it in the response to the client? Will that even work? Or is there something else I need to do?
We also use FOP to generate some documents, and we accept uploaded documents, all of which we eventually combine into a single PDF.
You can't just send them sequentially out the stream, because the combined result needs a proper PDF file header, metadata, etc.
We use the iText library to combine the files, starting off with
PdfReader reader = new PdfReader(/*String*/fileName);
reader.consolidateNamedDestinations();
We later loop through adding pages from each pdf to the new combined destination pdf, adjusting the bookmark / page numbers as we go.
AFAIK, FOP doesn't provide this sort of functionality.

Categories