Converting byte array to PDF and display in JSP page - java

I am doing a JSP site, where I need to display PDF files.
I have byte array of PDF file by webservice and I need to display that byte array as PDF file in HTML. My question is how to covert that byte array as PDF and display that PDF in new tab.

save these bytes on the disk by using output stream.
FileOutputStream fos = new FileOutputStream(new File(latest.pdf));
//create an object of BufferedOutputStream
bos = new BufferedOutputStream(fos);
byte[] pdfContent = //your bytes[]
bos.write(pdfContent);
Then send its link to client side to be opened from there.
like http://myexamply.com/files/latest.pdf

better is to use a servlet for this, since you do not want to present some html, but you want to stream an byte[]:
public class PdfStreamingServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
#Override
protected void doGet(final HttpServletRequest request,
final HttpServletResponse response) throws ServletException,
IOException {
processRequest(request, response);
}
public void processRequest(final HttpServletRequest request,
final HttpServletResponse response) throws ServletException,
IOException {
// fetch pdf
byte[] pdf = new byte[] {}; // Load PDF byte[] into here
if (pdf != null) {
String contentType = "application/pdf";
byte[] ba1 = new byte[1024];
String fileName = "pdffile.pdf";
// set pdf content
response.setContentType("application/pdf");
// if you want to download instead of opening inline
// response.addHeader("Content-Disposition", "attachment; filename=" + fileName);
// write the content to the output stream
BufferedOutputStream fos1 = new BufferedOutputStream(
response.getOutputStream());
fos1.write(ba1);
fos1.flush();
fos1.close();
}
}
}

Sadly, you do not tell us what technology you use.
With Spring MVC, use #ResponseBody as an annotation for your controller method and simply return the bytes like so:
#ResponseBody
#RequestMapping(value = "/pdf/shopping-list.pdf", produces = "application/pdf", method=RequestMethod.POST)
public byte[] downloadShoppingListPdf() {
return new byte[0];
}
Opening in a new tab is an unrelated matter that has to be handled in the HTML.

Related

Downloading multiple pdf files using Spring Boot RestController

I am trying to use a Spring Boot RestController to download multiple pdf files.But for some reason only the first file is downloaded.The program does not throw any error.Not sure what the issue is.Is Multipart needed for this?
#RequestMapping(value = "downloadAgain", method = RequestMethod.GET)
#ResponseBody
public void newRun(HttpServletResponse response) {
String fileName1="pdf1.pdf";
String fullName1="C://Users//pdf1.pdf";
newDownloadRun(response,fileName1,fullName1);
String fileName2="pdf2.pdf";
String fullName2="C://Users//pdf2.pdf";
newDownloadRun(response,fileName2,fullName2);
}
public void newDownloadRun(HttpServletResponse response,String fileName,String fullName) {
response.setContentType("application/pdf");
response.setHeader( "Content-Disposition", "attachment;filename="+ fileName );
response.setHeader("Content-disposition", "attachment; filename=" + fileName);
try {
BufferedOutputStream bos = new BufferedOutputStream(response.getOutputStream());
FileInputStream fis = new FileInputStream(fullName);
int len;
byte[] buf = new byte[1024];
while((len=fis.read(buf))> 0) {
bos.write(buf,0,len);
}
bos.close();
response.flushBuffer();
}catch(Exception ex) {
ex.printStackTrace();
}
}
Http protocol designed to send one file per request. if you want to send multiple files you need to prepare it as multipart/related. Look into this article https://www.motobit.com/tips/detpg_multiple-files-one-request/

HttpServletResponse not overriding the parameters I set up

I have a web service app in Java and I'm trying to do an export functionality to export some data from the database to an excel file
For this I'm using HttpServletResponse, but even I set up a filename and a encoding type, the file exported is not using those.
I need to set up the name of the file with the corresponding export date and the encoding type to allow UTF-8 characters like á,ó,ñ, etc --> This was fixed, see Edit 1 below.
Below you have my code:
#RequestMapping(value = "/export", method = RequestMethod.GET)
public #ResponseBody
void export(HttpServletRequest request, HttpServletResponse r) {
Response response = new Response();
try {
response = service.export();
if(response.isSuccess()){
r.setHeader( "Content-Disposition","attachment; filename=export_20171216.xls");
r.setContentType("application/vnd.ms-excel");
r.setCharacterEncoding("UTF-8");
OutputStream out = r.getOutputStream();
byte[] buffer = new byte[4096];
int length;
while ((length = ((InputStream) response.getData()).read(buffer)) > 0){
out.write(buffer, 0, length);
}
out.flush();
out.close();
}
else{
r.sendError(801, response.toString());
}
} catch (Exception e) {
e.printStackTrace();;
}
}
As the result, I'm getting files with the name like 2ea4a24e-b0b4-4d50-9604-4fcdb3713b90.xls and inside the file words like: Número instead of Número
--- Edit 1
I fixed the stress vowels with the follwing code when creating the ByteArray
new ByteArrayInputStream(sb.toString().getBytes("ISO-8859-15"));
If I got your issue correctly you are trying to keep filenames with symbols that have to be encoded. According setHeaders method docs:
the header value If it contains octet string, it should be
* encoded according to RFC 2047
* (http://www.ietf.org/rfc/rfc2047.txt)
And more likely your input filenames are in ASCII that are octets. Try to use java.nio.charset.CharsetDecoder with appropriate decoding when you set header with your fancy symbols.
A bit more explanations: ISO-8859-15 is not Unicode format and any symbol above of it leads to encoding the whole string for HTTP attributes.
public static void sendResponse (InputStream inputData, String fileName, HttpServletResponse res)
throws IOException {
try {
String contenttype = new ConfigurableMimeFileTypeMap().getContentType(fileName);
res.reset();
res.setContentType(contenttype);
res.addHeader("Content-Disposition", String.format("attachment;filename=\"%s\"", name));
ByteStreams.copy(inputData, res.getOutputStream());
} catch (Exception e) {
throw new IOException(e);
}
}
Please try with this:-I have used this in my code it works..
Let me know if still problem perisists
public void downloadFile(String fileName, String paramName,
HttpServletResponse response) {
File fileToBeDownloaded = null;
InputStream fileInputStream = null;
ServletOutputStream servletOutputStream;
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
response.addHeader("Content-Disposition", "attachment; filename=" +
fileName);
servletOutputStream = response.getOutputStream();
IOUtil.copyCompletely(fileInputStream, servletOutputStream);
servletOutputStream.flush();
servletOutputStream.close();
}

Java Convert byte array to PDF returns "undefined"

I'm trying to convert a byte array to a PDF document, but the the PDF file seems to be corrupted. And if open the file with a text reader the file just say "Undefined" I have searched through various stack topics but no luck. And the way i do it should work according to other topics. Below is my code. The code is executed trough a rest controller. Would really appreciate if someone could help me :).
//Controller
#ResponseBody
#RequestMapping(value = "/orders/{orderCode}/receipt", method = RequestMethod.GET, produces = "application/pdf")
public void getOrderReceiptConroller(#PathVariable("orderCode") final String orderCode, final HttpServletResponse response)
{
response.setContentType(CoreConstants.MIME_TYPE_APPLICATION_PDF);
final InputStream inputStream = new ByteArrayInputStream(OrderFacade.getReceiptPdf(orderCode));
OutputStream outputStream = null;
try
{
outputStream = response.getOutputStream();
IOUtils.copy(inputStream, outputStream);
}
catch (final IOException e)
{
}
finally
{
IOUtils.closeQuietly(inputStream);
IOUtils.closeQuietly(outputStream);
}
}
// calls this code that returns the byteArray.
private byte[] getReceiptPdf()
{
Gson gson = new Gson();
Edwresults edwResult = gson.fromJson(new FileReader(mockResponsePath), Edwresults.class);
String response = edwResult.getResults().get(0).getData().get(0).getDigitalReceipt();
byte[] byteData = response.getBytes();
return byteData;
}

Display Pdf file in browser using Servlet

I am using intellij Idea and I have saved my pdf file in resources folder. I want to display that pdf file in browser.
public class GetDocumentation extends HttpServlet {
private static final Logger log = Logger.getLogger(GetDocumentation.class);
#Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
InputStream pdf_path = this.getClass().getResourceAsStream(ApplicationProperties.getProperty("PDF_PATH"));
resp.setContentType("application/pdf");
resp.addHeader("Content-Disposition", "attachment; filename=Documentation.pdf");
OutputStream responseOutputStream = resp.getOutputStream();
byte[] buf = new byte[4096];
int len = -1;
while ((len = pdf_path.read(buf)) != -1) {
responseOutputStream.write(buf, 0, len);
}
responseOutputStream.flush();
responseOutputStream.close();
}
}
Documentation
I am using Jsp servlet and I am calling "/documentation". And my file is getting rendered but it's blank. Am I doing anything wrong?
inline Content-Disposition should be used to display the document. Replace "attachment" with "inline":
resp.addHeader("Content-Disposition", "inline; filename=Documentation.pdf");

How to convert byte[] to PDF in java servlet?

I am trying to create a PDF file out of a byte array. Before writing the bytes to the file I print them as a string and the contents get printed correctly but when I open the automatically downloaded PDF file, it won't open as the file is somehow damaged.
#Override
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
long logFileId = Long.valueOf(request.getParameter(REQUEST_PARAM_DOCUMENT_ID));
MappingInfo mapping = documentService.getMapping(logFileId);
byte[] file = mapping.getImportLogs();
System.out.println(new String(file));
response.setContentType("application/pdf");
response.setContentLength(file.length);
// response.reset();
response.setContentType("application/pdf");
String headerKey = "Content-Disposition";
String headerValue = String.format("attachment; filename=ImportLog.pdf");
response.setHeader(headerKey, headerValue);
OutputStream outStream = response.getOutputStream();
outStream.write(file);
outStream.flush();
outStream.close();
}
Can someone please point out the mistake I am making here? I am also trying not to use any third party APIs.
Thanks
You can check this example from JavaPoint.
http://www.javatpoint.com/how-to-write-data-into-PDF-using-servlet
I am not sure that we must use a third party API for this. I am able to achieve this using iText API. Might help someone else.
#Override
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
long logFileId = Long.valueOf(request.getParameter(REQUEST_PARAM_DOCUMENT_ID));
MappingInfo mapping = documentService.getMapping(logFileId);
byte[] file = mapping.getImportLogs();
OutputStream outStream = response.getOutputStream();
Document document = new Document();
try {
PdfWriter.getInstance(document, outStream);
document.open();
document.add(new Paragraph(new String(file)));
document.add(Chunk.NEWLINE);
document.add(new Paragraph("a paragraph"));
} catch (DocumentException e) {
e.printStackTrace();
}
document.close();
response.setContentLength(file.length);
response.setContentType("application/pdf");
String headerKey = "Content-Disposition";
String headerValue = String.format("attachment; filename=ImportLog.pdf");
response.setHeader(headerKey, headerValue);
outStream.write(file);
outStream.flush();
outStream.close();
}

Categories

Resources