I am using itext to generate a pdf file from an html string. I get this error in my console:
Uncaught Error: Syntax error, unrecognized expression: %PDF-1.4
This is the code in my controller.
#RequestMapping(value = "/print",method = RequestMethod.POST)
public void print(String html,HttpServletResponse response,HttpServletRequest request) throws IOException,DocumentException {
try{
Document document = new Document();
// step 2
ByteArrayOutputStream baos = new ByteArrayOutputStream();
PdfWriter.getInstance(document, baos);
// step 3
document.open();
document.add(new Paragraph(html));
// step 5
document.close();
// setting some response headers
response.setHeader("Expires", "0");
response.setHeader("Cache-Control",
"must-revalidate, post-check=0, pre-check=0");
response.setHeader("Pragma", "public");
// setting the content type
response.setContentType("application/pdf");
// the contentlength
response.setContentLength(baos.size());
// write ByteArrayOutputStream to the ServletOutputStream
OutputStream os = response.getOutputStream();
baos.writeTo(os);
os.flush();
}
catch(DocumentException e) {
throw new IOException(e.getMessage());
}
what you need to do is to stream the PDF file's bytes directly to the output stream and flush the response. In Spring you can do this like this:
#RequestMapping(value="/displayProcessFile/{processInstanceId}", method=RequestMethod.GET)
public ResponseEntity<byte[]> displayProcessFile(#PathVariable String processInstanceId) throws UnauthorizedUserAccessException{
Document processFile=null;
try {
processFile = documentService.retrieveProcessFile(Long.parseLong(processInstanceId));
} catch (ProcessFileNotFoundExpection e) {
e.printStackTrace();
}
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.parseMediaType("application/pdf"));
headers.add("content-disposition", "attachment;filename=" + processFile.getDocName());
ResponseEntity<byte[]> response = new ResponseEntity<byte[]>(processFile.getContent(), headers, HttpStatus.OK);
return response;
}
Related
How should I display this byte code into the WebPage of my app?
#RequestMapping(value="/getPdf", method=RequestMethod.POST)
public ResponseEntity<byte[]> getPDF1() {
String PATH_FILE = "C:\\Users\\rohit\\Downloads\\pdf_view\\sample.pdf";
Path path = Paths.get(PATH_FILE);
byte[] pdfContents = null;
try {
pdfContents =Files.readAllBytes(path);
} catch (IOException e) {
e.printStackTrace();
}
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.parseMediaType("application/pdf"));
String filename = "pdf1.pdf";
headers.add("content-disposition", "inline;filename=" + filename);
headers.setContentDispositionFormData(filename, filename);
headers.setCacheControl("must-revalidate, post-check=0, pre-check=0");
ResponseEntity<byte[]> response = new ResponseEntity<byte[]>(pdfContents, headers, HttpStatus.OK);
return response;
}
I simply want to display my PDF file in my web application.
if you simply want to display your pdf file in your web application you can just drag you pdf into your solution and use href="" to show it I think.
ps: not sure
I'am tying to export a pdf file from html using fly-saucer, but the file is always empty and therefore can not be opened. Can anyone tell me what i am doing wrong.
Here is my current code:
String templateName = "test-pdf";
Context ctx = new Context();
String processedHtml = templateEngine.process(templateName, ctx);
ITextRenderer renderer = new ITextRenderer();
renderer.setDocumentFromString(processedHtml);
renderer.layout();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
renderer.createPDF(baos, false);
// setting some response headers
response.setHeader("Expires", "0");
response.setHeader("Cache-Control",
"must-revalidate, post-check=0, pre-check=0");
response.setHeader("Pragma", "public");
// setting the content type
response.setContentType("application/pdf");
// the contentLength
response.setContentLength(baos.size());
OutputStream os = response.getOutputStream();
baos.writeTo(os);
os.flush();
os.close();
System.out.println("PDF created successfully");
I want to send a file from the server side to the client side using rest service
I'm using spring MVC. I used this service method:
public ResponseEntity<InputStreamResource> postFile() throws Exception {
DocumentDaoImpl dao = new DocumentDaoImpl();
Document docCmis = (Document) dao.getDocument("workspace://SpacesStore/ae6d1722-0f08-49ab-a73b-c07036001318");
byte[] myByteArray = readContent(docCmis.getContentStream().getStream());
ClassPathResource myFile = new ClassPathResource(docCmis.getContentStreamFileName());
//System.out.println("eeeee"+pdfFile);
HttpHeaders headers = new HttpHeaders();
headers.add("Cache-Control", "no-cache, no-store, must-revalidate");
headers.add("Pragma", "no-cache");
headers.add("Expires", "0");
return ResponseEntity
.ok()
.headers(headers)
.contentLength(myByteArray.length)
.contentType(MediaType.parseMediaType("application/octet-stream"))
.body(new InputStreamResource(docCmis.getContentStream().getStream()));
}
and this function in a rest controller class
#RequestMapping(value = "/downloadPDFFile",produces = { "application/json" }, method = RequestMethod.GET)
#ResponseBody
public ResponseEntity downloadPDFFile() throws Exception {
return courriersArrivésServices.postFile();
}
then with a rest call using RestTemplate class,i tryied to get my file
Map<String, Object> selectedCourrier=restTemplate.getForObject(SERVER_URI + "/getCourrierDetails"+"?id="+id, HashMap.class);
But that didn't work for me and gives me this error
org.springframework.web.client.RestClientException: Could not extract response: no suitable HttpMessageConverter found for response type [class org.springframework.http.ResponseEntity] and content type [application/octet-stream]
Server side:
#RequestMapping("/download")
public byte[] download() throws Exception {
File f = new File("C:\\WorkSpace\\Text\\myDoc.txt");
byte[] byteArray = new byte[(int) f.length()];
byteArray = FileUtils.readFileToByteArray(f);
return byteArray;
}
Client side:
private ResponseEntity<byte[]> getDownload(){
URI end = URI.create("http://vmvdi05059:8080/ePaymentsWeb/download");
return rest.getForEntity(end,byte[].class);
}
public static void main(String[] args) throws Exception {
byte[] byteArray = new TestClient().getDownload().getBody();
FileOutputStream fos = new
FileOutputStream("C:\\WorkSpace\\testClient\\abc.txt");
fos.write(byteArray);
fos.close();
System.out.println("file written successfully..");
}
I am done with writing the file content to pdf file on click of view, But it's not opening automatically.Can any one help. Thanks in advance.And please correct me if anything wrong here.
#RequestMapping(value = { "/view" }, method = RequestMethod.GET)
public static byte[] loadFile(#RequestParam("file_path") String file_path,#RequestParam("file_name") String fileName,HttpServletResponse response, HttpServletRequest request,HttpServletResponse resp) throws IOException, DocumentException {
FileInputStream inputStream = null;
try {
String filePath = file_path.replace("/", "\\");
File file = new File(filePath);
inputStream = new FileInputStream(file);
filePath.endsWith(".pdf");
return readFully(inputStream, filePath, fileName, resp, request,
resp);
} finally {
if (inputStream != null) {
inputStream.close();
}
}
}
here i am calling the below method and written the code for opening a file automatically.
#ResponseBody
public static byte[] readFully(FileInputStream inputStream,
#RequestParam("file_path") String file_path,
#RequestParam("file_name") String fileName,
HttpServletResponse response, HttpServletRequest request,
HttpServletResponse resp) throws IOException, DocumentException {
byte[] buffer = new byte[8192];
ByteArrayOutputStream baos = new ByteArrayOutputStream();
int bytesRead;
while ((bytesRead = inputStream.read(buffer)) != -1) {
baos.write(buffer, 0, bytesRead);
}
Document doc = new Document();
PdfWriter.getInstance(doc, baos);
doc.open();
response.setContentType("application/pdf");
response.setHeader("Content-disposition", "attachment; filename="
+ fileName + ".pdf");
response.setHeader("Cache-Control",
"must-revalidate, post-check=0, pre-check=0");
response.setHeader("Expires", "0");
response.setHeader("Pragma", "No-cache");
response.setContentLength(baos.size());
ServletOutputStream outn = response.getOutputStream();
outn.flush();
baos.writeTo(outn);
File f = new File("C:\\Users\\Downloads\\" + fileName + ".pdf");
if (f.exists()) {
if (Desktop.isDesktopSupported()) {
Desktop.getDesktop().open(f);
} else {
System.out.println("Awt Desktop is not supported!");
}
} else {
System.out.println("File is not exists!");
}
System.out.println("Done");
return baos.toByteArray();
}
You can write your inputstream into spring fileInputStream.
You can do this just writing input stream in httpservletResponse.
Please change your all code with below method. You can achieve your goal.
#RequestMapping(value = { "/view" }, method = RequestMethod.GET)
#ResponseBody
public void loadFile(#RequestParam("file_path") String file_path,#RequestParam("file_name") String fileName,HttpServletResponse response, HttpServletRequest request,HttpServletResponse resp) throws IOException, DocumentException {
String filePath = file_path.replace("/", "\\");
File file = new File(filePath);
response.setHeader("Expires", "0");
response.setHeader("Cache-Control", "must-revalidate, post-check=0, pre-check=0");
response.setHeader("Pragma", "public");
response.setHeader("Content-Type", "application/pdf");
response.setHeader("Content-Disposition","attachment;filename="+fileName);
response.setHeader("Content-Length", String.valueOf(file.length()));
try {
FileInputStream fileInputStream = new FileInputStream(file);
FileCopyUtils.copy(fileInputStream, httpServletResponse.getOutputStream());
fileInputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
}
sorry for my bad english. I'm using iText in GAE + GWT.. i made a example app and it works in google! but i have a problem whit the token of URL.
I have this RPC service which create the Document in a Array of Bytes and write this in the HttpSession, then in client onSuccess block i call a Servlet which send to the client the PDF . The String token = "258958395ai53" is a token where the client find the PDF but in this example y made the token static so i need to create the token randomly and make sure that the token don't repeat. Here is de code.
RPC Service:
public String getPdf() {
Document document = new Document();
String token = "258958395ai53";
// generate test PDF
try {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
PdfWriter.getInstance(document, baos);
document.open();
document.add(new Paragraph("¡HOLA PUTO MUNDO!"));
document.close();
byte[] pdf = baos.toByteArray();
HttpServletRequest request = this.getThreadLocalRequest();
HttpSession session = request.getSession();
session.setAttribute(token, pdf);
} catch (Exception e) {
System.out.println("ReportServlet::generatePDF::Exception "
+ e.getMessage());
}
return token;
}
Servlet:
public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
// create output stream from byte array in session
ByteArrayOutputStream baos = new ByteArrayOutputStream();
String token = request.getParameter("token");
byte[] pdf = (byte[]) request.getSession().getAttribute(token);
baos.write(pdf);
// setting some response headers
response.setHeader("Expires", "0");
response.setHeader("Cache-Control", "must-revalidate, post-check=0,pre-check=0");
response.setHeader("Pragma", "public");
response.setContentType("application/pdf");
// content length is needed for MSIE
response.setContentLength(baos.size());
// write ByteArrayOutputStream to ServletOutputStream
ServletOutputStream out = response.getOutputStream();
baos.writeTo(out);
out.flush();
out.close();
}
onSuccess:
public void onSuccess(String lista) {
String token = lista;
//Window.open("hello?token="+ token, "_blank","menubar=yes,location=yes,resizable=yes,scrollbars=yes,status=yes");
Dialog d = new Dialog();
d.setWidth(500);
d.setHeight(700);
d.setUrl(GWT.getModuleBaseURL()+"hello?token="+token);
d.show();
}
});
Any idea? .. Can view my example http://pdfprueba2.appspot.com/
You can use a random generator. There are more advanced random generators available such as SecureRandom (see here how it works). On top of this you can combine multiple unique elements to create an uber unique key. This article gives an overview of some of the methods used in creating such a thing.
Take in account that the more complexity you add, the more resources/time it will take.