iText (latest version) appears to work slightly better as non-Acrobat pdf viewers can see it. Skim & Preview using PDFBox only show blank page w/o prompting for pass. That said I have an issue with iText after encrypting an existing file - Android, when Content-Disposition = inline shows garble. I'm still testing CD = attachment.
What I want in either iText or PDFBox is to grab a file from the filesystem/db(future), encrypt it, then send it back through the web app server (jBoss 7.1.1.Final). The browser should then determine whether to inline viewer if it has a pdf viewer or download it for another app. This works fine in iOS, btw. Below is my code for both iText & PDFBox tests.
#RequestMapping (value = "/pdf/{page}.pdf", method = RequestMethod.GET)
public void doDownload(#PathVariable("page") String paramString,
HttpServletRequest request, HttpServletResponse response) throws IOException {
// get absolute path of the application
ServletContext context = request.getServletContext();
String appPath = context.getRealPath("");
System.out.println("appPath = " + appPath);
// construct the complete absolute path of the file
String fullPath = appPath + "/pdf/" + paramString + ".pdf";
File downloadFile = new File(fullPath);
PDDocument mypdf = PDDocument.load(downloadFile);
// try {
// mypdf.encrypt("demo", "demo");
// } catch (CryptographyException e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
// }
// FileInputStream inputStream = new FileInputStream(downloadFile);
// get MIME type of the file
String mimeType = context.getMimeType(fullPath);
if (mimeType == null) {
// set to binary type if MIME mapping not found
mimeType = "application/pdf";
}
System.out.println("MIME type: " + mimeType);
// set content attributes for the response
// response.setContentType(mimeType);
// response.setContentLength((int) downloadFile.length());
//
// set headers for the response
response.addHeader("Content-Disposition", "inline; filename=notice.pdf");
// response.addHeader("Content-Transfer-Encoding", "binary");
// get output stream of the response
OutputStream outStream = response.getOutputStream();
try {
mypdf.save(outStream);
mypdf.close();
} catch (COSVisitorException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// byte[] buffer = new byte[BUFFER_SIZE];
// int bytesRead = -1;
//
// // write bytes read from the input stream into the output stream
// while ((bytesRead = inputStream.read(buffer)) != -1) {
// outStream.write(buffer, 0, bytesRead);
// }
// inputStream.close();
// outStream.flush();
// outStream.close();
// return "pages-authenticated/pdf";
}
//}
// PDFBox
#RequestMapping (value = "pages-authenticated/pdf.html", method = RequestMethod.POST)
public String doDownload(Model model, #ModelAttribute("PDFForm") PDFForm form,
HttpServletRequest request, HttpServletResponse response) throws IOException {
// get absolute path of the application
ServletContext context = request.getServletContext();
String appPath = context.getRealPath("");
String fullPath;
System.out.println("appPath = " + appPath);
System.out.println("pass:" + form.getPass());
// Return if no password given
if (form.getPass() == null || form.getPass().equalsIgnoreCase("")) {
model.addAttribute("noPass", true);
return "pages-authenticated/pdf";
}
// construct the complete absolute path of the file
fullPath = appPath + "/pdf/notice.pdf";
File downloadFile = new File(fullPath);
PDDocument mypdf = PDDocument.load(downloadFile);
try {
mypdf.encrypt(form.getPass(),form.getPass());
} catch (CryptographyException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// FileInputStream inputStream = new FileInputStream(downloadFile);
// get MIME type of the file
String mimeType = context.getMimeType(fullPath);
if (mimeType == null) {
// set to binary type if MIME mapping not found
mimeType = "application/pdf";
}
System.out.println("MIME type: " + mimeType);
// set headers for the response
response.setContentType("application/pdf");
// response.addHeader("Content-Disposition", "inline; filename=notice.pdf");
// get output stream of the response
OutputStream outStream = response.getOutputStream();
try {
mypdf.save(outStream);
outStream.flush();
outStream.close();
mypdf.close();
} catch (COSVisitorException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
// iText
//#RequestMapping (value = "pages-authenticated/pdf.html", method = RequestMethod.POST)
//public String doDownload(Model model, #ModelAttribute("PDFForm") PDFForm form,
// HttpServletRequest request, HttpServletResponse response) throws IOException {
// // get absolute path of the application
// ServletContext context = request.getServletContext();
// String appPath = context.getRealPath("");
// String fullPath;
// System.out.println("appPath = " + appPath);
//
//
// System.out.println("pass:" + form.getPass());
//
//// // set headers for the response
// response.setContentType("application/pdf");
// response.addHeader("Content-Disposition", "inline; filename=notice.pdf");
//
//
// // Return if no password given
// if (form.getPass() == null || form.getPass().equalsIgnoreCase("")) {
// model.addAttribute("noPass", true);
////
//// fullPath = appPath + "/WEB-INF/pages-authenticated/pdf.html";
//// File downloadFile = new File(fullPath);
////
//// FileInputStream inputStream = new FileInputStream(downloadFile);
////
////// set content attributes for the response
//// response.setContentType("text/html");
//// response.setContentLength((int) downloadFile.length());
////
//// byte[] buffer = new byte[BUFFER_SIZE];
//// int bytesRead = -1;
////
//// // write bytes read from the input stream into the output stream
//// while ((bytesRead = inputStream.read(buffer)) != -1) {
//// outStream.write(buffer, 0, bytesRead);
//// }
////
////
//// inputStream.close();
//// outStream.flush();
//// outStream.close();
//
// return "pages-authenticated/pdf";
//
// }
// // construct the complete absolute path of the file
// fullPath = appPath + "/pdf/notice.pdf";
//
// PdfReader mypdf = new PdfReader(fullPath);
// PdfStamper myPdfStamper;
// try {
// myPdfStamper = new PdfStamper(mypdf, response.getOutputStream());
// myPdfStamper.setEncryption(form.getPass().getBytes(), form.getPass().getBytes(),
// PdfWriter.ALLOW_PRINTING, PdfWriter.ENCRYPTION_AES_256);
// myPdfStamper.close();
// mypdf.close();
// } catch (DocumentException e1) {
// // TODO Auto-generated catch block
// e1.printStackTrace();
// }
//
//
//// FileInputStream inputStream = new FileInputStream(downloadFile);
//
// // get MIME type of the file
//// String mimeType = context.getMimeType(fullPath);
//// if (mimeType == null) {
//// // set to binary type if MIME mapping not found
//// mimeType = "application/pdf";
//// }
//// System.out.println("MIME type: " + mimeType);
////
//// // set headers for the response
//// response.setContentType("application/pdf");
//// response.addHeader("Content-Disposition", "inline; filename=notice.pdf");
////
//// // get output stream of the response
//// OutputStream outStream = response.getOutputStream();
////
//// try {
//// mypdf.save(outStream);
//// outStream.flush();
//// mypdf.close();
////
//// } catch (COSVisitorException e) {
//// // TODO Auto-generated catch block
//// e.printStackTrace();
//// }
////
// return null;
// }
}
Here is what I finally got to work (Android issues):
1. Cannot use AES 256, but AES 128 works
2. Cannot use POST, must use GET
Related
i'm using the below code to get the file length and using which i display progress bar till i download the total file but i get an error from firebase crash report like below
java.lang.RuntimeException: An error occured while executing doInBackground()
at android.os.AsyncTask$3.done(AsyncTask.java:304)
#Override
protected String doInBackground(String...Url) {
try {
URL url = new URL(Url[0]);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("HEAD");
connection.connect();
// Detect the file lenghth
fileLength = connection.getContentLength();
} else {
URLConnection connection = url.openConnection();
connection.connect();
// Detect the file lenghth
fileLength = connection.getContentLength();
}
/*
HttpURLConnection connection = (HttpURLConnection)url.openConnection();
connection.setRequestMethod("HEAD");
connection.connect();
int fileLength = connection.getContentLength();*/
// Locate storage location
// String filepath = Environment.getExternalStorageDirectory().getPath();
String filepath = getFilesDirectory(getApplicationContext()).getPath();
// File fo = getFilesDirectory(getApplicationContext());
// Download the file
InputStream input = new BufferedInputStream(url.openStream());
// Save the downloaded file
if (lang_slector == 0) {
// input stream to read file - with 8k buffer
File folder = new File(filepath, "/offlinedata/");
folder.mkdir();
File pdfFile = new File(folder, englishpdffilename);
try {
pdfFile.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
OutputStream output = new FileOutputStream(filepath + "/offlinedata/" +
pdffilename);
byte data[] = new byte[1024];
long total = 0;
int count;
while ((count = input.read(data)) != -1) {
total += count;
// Publish the progress
publishProgress((int)(total * 100 / fileLength));
output.write(data, 0, count);
}
// Close connection
output.flush();
output.close();
input.close();
} else if (lang_slector == 1) {
// input stream to read file - with 8k buffer
File folder = new File(filepath, "/offlinedata/");
folder.mkdir();
File pdfFile = new File(folder, englishpdffilename);
try {
pdfFile.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
OutputStream output = new FileOutputStream(filepath + "/offlinedata/" +
englishpdffilename);
byte data[] = new byte[1024];
long total = 0;
int count;
while ((count = input.read(data)) != -1) {
total += count;
// Publish the progress
publishProgress((int)(total * 100 / fileLength));
output.write(data, 0, count);
}
// Close connection
output.flush();
output.close();
input.close();
}
} catch (Exception e) {
// Error Log
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return null;
}
I am generating a powerpoint file(.pptx) and i would like to return back this file when a REST call happens. But now am able to get only .File type extension.
#RequestMapping(value = "/ImageManagerPpt/{accessionId}", method = RequestMethod.GET, produces = "application/ppt")
public ResponseEntity<InputStreamResource> createPptforAccessionId(#PathVariable("accessionId") String accessionId,HttpServletResponse response) throws IOException** {
System.out.println("Creating PPT for Patient Details with id " + accessionId);
File pptFile = imageManagerService.getPptForAccessionId(accessionId);
if (pptFile == null) {
System.out.println("Patient Id with id " + accessionId + " not found");
return new ResponseEntity<InputStreamResource>(HttpStatus.NOT_FOUND);
}
InputStream stream = null;
try {
stream = new FileInputStream(pptFile);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
ClassPathResource classpathfile = new ClassPathResource("Titlelayout3.pptx");
InputStreamResource inputStreamResource = new InputStreamResource(stream);
return ResponseEntity.ok().contentLength(classpathfile.contentLength())
.contentType(MediaType.parseMediaType("application/octet-stream"))
.body(new InputStreamResource(classpathfile.getInputStream()));
}
-Bharat
Have you tried, this?
InputStream stream = new InputStream(pptFile);
org.apache.commons.io.IOUtils.copy(is, response.getOutputStream());
response.flushBuffer();
You will get file as you put into the InputStream.
boolean isMultipart = ServletFileUpload.isMultipartContent(request);
if (isMultipart) {
System.out.println("multipart2");
// Create a factory for disk-based file items
FileItemFactory factory = new DiskFileItemFactory();
// Create a new file upload handler
ServletFileUpload upload = new ServletFileUpload(factory);
try {
// Parse the request
List /* FileItem */ items = upload.parseRequest(request);
Iterator iterator = items.iterator();
while (iterator.hasNext()) {
FileItem item = (FileItem) iterator.next();
if (item.isFormField()) //your code for getting form fields
{
if (item.getFieldName().equals("btn")) {
if (item.getString().equals("Submit")) {
String name = item.getFieldName();
String value = item.getString();
System.out.println("test2" + name + value);
}
if (item.getString().equals("Save as Draft")) {
System.out.println("hii hii2");
String name = item.getFieldName();
String value = item.getString();
}
}
} if (!item.isFormField()) {
String fileName = item.getName();
System.out.println("File Upload Named : " + fileName);
String root = getServletContext().getRealPath("/");
File path = new File(root + "/uploads");
if (!path.exists()) {
boolean status = path.mkdirs();
}
File uploadedFile = new File(path + "/" + fileName);
// System.out.println(uploadedFile.getAbsolutePath());
item.write(uploadedFile);
}
}
} catch (FileUploadException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
response.sendRedirect("/EventCalendar-war/pages/user_pages/user_create_event.jsp");
}
This is my code.When there is no file to upload I got java.io.FileNotFoundException .If file is upload with form data it's work fine.What is wrong with my code?
I am using GWT.
I have to download a file file from server to client.
Document is in the external repository.
Client sends the id of the document through a Servlet.
On server side: Using this ID document is retrieved:
Document document = (Document)session.getObject(docId);
ContentStream contentStream = document.getContentStream();
ByteArrayInputStream inputStream = (ByteArrayInputStream) contentStream.getStream();
int c;
while ((c = inputStream.read()) != -1) {
System.out.print((char) c);
}
String mime = contentStream.getMimeType();
String name = contentStream.getFileName();
InputStream strm = contentStream.getStream();
Here I can read the document.
I want to send this to the client.
How do I make this a file and send it back to the client?
In Your Servlet:
Document document =(Document)session.getObject(docId);
ContentStream contentStream = document.getContentStream();
String name = contentStream.getFileName();
response.setHeader("Content-Type", "application/octet-stream;");
response.setHeader("Content-Disposition", "attachment;filename=\"" + name + "\"");
OutputStream os = response.getOutputStream();
InputStream is =
(ByteArrayInputStream) contentStream.getStream();
BufferedInputStream buf = new BufferedInputStream(is);
int readBytes=0;
while((readBytes=buf.read())!=-1) {
os.write(readBytes);
}
os.flush();
os.close();// *important*
return;
You can create a standard servlet (which extends HttpServlet and not RemoteServiceServlet) on server side and opportunity to submit the id as servlet parameter on client side.
Now you need after getting request create the excel file and send it to the client. Browser shows automatically popup with download dialog box.
But you should make sure that you set the right content-type response headers. This header will instruct the browser which type of file is it.
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String fileId = reguest.getParameter("fileId"); // value of file id from request
File file = CreatorExel.getFile(fileId); // your method to create file from helper class
// setting response headers
response.setHeader("Content-Type", getServletContext().getMimeType(file.getName()));
response.setHeader("Content-Length", file.length());
response.setHeader("Content-Disposition", "inline; filename=\"" + file.getName() + "\"");
BufferedInputStream input = null;
BufferedOutputStream output = null;
try {
InputStream inputStream = new FileInputStream(file);
ServletOutputStream outputStream = response.getOutputStream();
input = new BufferedInputStream(fileInput);
output = new BufferedOutputStream(outputStream);
int count;
byte[] buffer = new byte[8192]; // buffer size is 512*16
while ((count = input.read(buffer)) > 0) {
output.write(buffer, 0, count);
}
} finally {
if (output != null) {
try {
output.close();
} catch (IOException ex) {
}
}
if (input != null) {
try {
input.close();
} catch (IOException ex) {
}
}
}
I have this servlet I call using GWT FileUpload (I don't thing it matters so much that it is GWT):
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter writer = response.getWriter();
try {
User user = ServerUtil.validateUser(request);
ServletFileUpload upload = new ServletFileUpload();
try {
FileItemIterator iter = upload.getItemIterator(request);
while (iter.hasNext()) {
FileItemStream item = iter.next();
String saveFile = item.getName();
InputStream stream = item.openStream();
// Process the input stream
ByteArrayOutputStream out = new ByteArrayOutputStream();
int len;
byte[] buffer = new byte[8192];
while ((len = stream.read(buffer, 0, buffer.length)) != -1) {
out.write(buffer, 0, len);
}
int maxFileSize = 10 * (1024 * 1024); //10 megs max
if (out.size() > maxFileSize) {
throw new RuntimeException("File is > than " + maxFileSize);
}
// save file data
String fileName = user.getUsername() + "_" + new Date().getTime() + "_" + saveFile;
// store to S3
String imageUrl = S3PhotoUtil.storeThumbnailImage(out.toByteArray(), fileName, 100);
// return the url of the file
writer.println(imageUrl);
response.flushBuffer();
return;
}
} catch (RuntimeException e) {
writer.println(("error=" + e.getMessage()).getBytes());
} catch (FileUploadException e) {
writer.println(("error=Could not read file").getBytes());
} catch(IOException e) {
writer.println(("error=Image type not supported!").getBytes());
}
} catch (EIException e) {
e.printStackTrace();
writer.println(("error=Not logged in").getBytes());
}
}
When called the POST hangs, I check on firebug, it looks like it never gets a response. If I debug I see that all instructions are executed without any problem and the method is ran fine. The files are stored on my S3 bucket.
Now if I remove the call relating to the S3 storage it stops hanging, although obviously it doesn't do anything anymore... My conclusion is that there is something in this S3 storage that messes up with my servlet. The code itself is taken from the travel log example application # http://aws.amazon.com/code/1264287584622066
It does say needs tomcat and I'm using jetty... could that be a problem?
Thanks,
Thomas