I have a JSF2 commandlink with an image. When the image is clicked, the server will download a PDF file. While the file is downloaded after the image link is clicked, it also causes the entire page to scroll to the top of the page. the code snippet for the link is as follows:
<p:commandLink ajax="false"
action="#{refereeAssessmentSummaryBean.stateLatestFormInPAVer(project.appId)}">
<p:graphicImage name="images/pdf.png"
title="#{msg['label.downloadpdf']}" />
</p:commandLink>
How can I use the commandlink to download the PDF file, without the webpage scrolling to the top of the page every time I click on it?
Edit: FWIW, added PDF download code. This code is called as a shared method from the backing bean. As you can see, the code will set the content type before streaming the PDF data to the client.
public void downloadEformPdf(Integer appId, Integer revNo, Integer meetingId,
String password, boolean showSaveDialog, boolean getEditedIfAvailable, boolean showVersionInfo) {
User user = WebUtils.getCurrentUser();
PermissionResult permissionResult = ServiceProxy.getPermissionService().checkViewOnlineProposalPermission(user, appId, meetingId);
if (permissionResult != PermissionResult.GRANTED) {
if (!(permissionResult == PermissionResult.REJECTED_GRBE_COI_NOT_APPROVED
|| permissionResult == PermissionResult.REJECTED_GRBE_COI_NOT_DECLARED)) {
throw new PermissionDeniedException("Permission Denied");
}
}
Application appl = ServiceProxy.getAppService().getApplication(appId);
String scheme = appl.getScheme();
boolean withNomination = false;
boolean isEditedVersion = false;
byte[] pdfData;
if (getEditedIfAvailable) {
if (revNo == null) {
Appmatching appMatching = ServiceProxy.getAppFormService().getLatestAppMatching(appId,false);
revNo = appMatching.getMainRevno();
}
Appattacheditedeform editedEntry = ServiceProxy.getAppService().getEditedProposalForApplication(appId, revNo, true);
// give GRB, ER the edited version if it exists
if (editedEntry != null) {
Filestorage storage = editedEntry.getFilestorage();
pdfData = storage.getContent();
isEditedVersion = true;
} else {
pdfData = ServiceProxy.getReportService().getHMRFReportContentByRevNo(
appId.intValue(), revNo, withNomination);
}
} else { //Get the unedited version
//Get latest rev no.
if (revNo == null) {
Appmatching appMatching = ServiceProxy.getAppFormService().getLatestAppMatching(appId,false);
revNo = appMatching.getMainRevno();
}
pdfData = ServiceProxy.getReportService().getHMRFReportContentByRevNo(
appId.intValue(), revNo, withNomination);
}
FacesContext context = FacesContext.getCurrentInstance();
ExternalContext extContext = context.getExternalContext();
extContext.responseReset();
PDDocument doc = null;
try {
if (pdfData != null) {
PDFParser parser = new PDFParser(new ByteArrayInputStream(pdfData));
parser.parse();
doc = parser.getPDDocument();
AccessPermission ap = new AccessPermission();
ap.setReadOnly();
if (password != null) {
StandardProtectionPolicy spp = new StandardProtectionPolicy(password, password, ap);
spp.setEncryptionKeyLength(128);
doc.protect(spp);
}
ByteArrayOutputStream bos = new ByteArrayOutputStream();
doc.save(bos);
doc.close();
byte[] docbuff = bos.toByteArray();
String refNo = appl.getRefNo();
String filename = null;
if (showVersionInfo) {
if (isEditedVersion) {
filename = scheme.toLowerCase() + "_eform_" + refNo + "_(v" + revNo + ")_(Edited).pdf";
} else {
filename = scheme.toLowerCase() + "_eform_" + refNo + "_(v" + revNo + ")_(PA).pdf";
}
} else {
filename = scheme.toLowerCase() + "_eform_" + refNo + ".pdf";
}
extContext.setResponseContentType("application/pdf");
extContext.setResponseContentLength(docbuff.length);
extContext.setResponseHeader("Content-Disposition", (!showSaveDialog) ? "inline"
: "attachment" + "; filename=\"" + filename + "\"");
OutputStream os = extContext.getResponseOutputStream();
os.write(docbuff);
os.close();
context.responseComplete();
} else {
extContext.setResponseContentType("text/html");
Writer writer = extContext.getResponseOutputWriter();
writer.write("Cannot retrieve PDF form for this proposal.");
writer.close();
context.responseComplete();
}
} catch (IOException e) {
logger.log(Level.ERROR, e.getMessage(), e);
} catch (COSVisitorException e) {
logger.log(Level.ERROR, e.getMessage(), e);
} catch (BadSecurityHandlerException e) {
logger.log(Level.ERROR, e.getMessage(), e);
} finally {
}
}
How do you generate the PDF?
Did you set a mimetype so that the brower will recognize that you respond with a pdf?
Did you also prevent primefaces from continuing the response after you have written your PDF file to it? (use facesContext.responseComplete(); for that)
When you use the default HTML link tag <a />, you have to set href='javascript:void(0)' to avoid the current page to scroll to the top.
Maybe there is a way with a p:commandLink to do the same thing
<p:commandLink url="javascript:void(0)" ... /> ??
Hope this will help you to resolve your problem
I think it's because you are using ajax=false.
If you are not using ajax the whole page will be reloaded.
Either remove it or change to ajax=true and give it a try.
Edit:
I was wrong. ajax=false is required when downloading files.
Related
My English Hope you can understand me.
Hello guys, im developing a web program using Apache Velocity, but i meet a problem, i cannot return view after output a file by OutPutStream, following is my code:
#Get("test")
public String getPdfInfoByTestId(Invocation invocation, #Param("testIds") String testIds) throws Exception {
HttpServletResponse response = invocation.getResponse();
if (testIds.length() == 0) {
invocation.addModel("status", PdfStatusEnum.NOT_FOUND.getType());
return "admin_pdf_info";
}
String[] idArray = testIds.split(",");
List<Long> idList = string2LongList(testIds);
List<ContestOneTest> contestOneTestList = contestOneTestService.getByIdList(idList);
if (contestOneTestList.size() == 0) {
invocation.addModel("status", PdfStatusEnum.NOT_FOUND.getType());
//response.sendRedirect("index");
return "admin_pdf_info";
}
List<PdfInfo> pdfInfos = new ArrayList<>(contestOneTestList.size() + 1);
//填充表格需要的数据
for (ContestOneTest contestOneTest : contestOneTestList) {
PdfInfo pdfInfo = new PdfInfo();
CtsTestUser ctsTestUser = ctsTestUserService.getUserById(contestOneTest.getActorId());
pdfInfo.setActorName(ctsTestUser.getName());
pdfInfo.setTestId(contestOneTest.getId());
pdfInfo.setPaperName(contestOneTest.getPaperName());
pdfInfo.setPaperId(contestOneTest.getPaperId());
if (contestOneTest.getStatus() == OneTestStatusEnum.FINISHED.getValue() && StringUtils.isNotBlank(contestOneTest.getPdfUrl())) {
pdfInfo.setGenStatus("已处理");
pdfInfo.setRank("无需排队");
pdfInfo.setPdfUrl(contestOneTest.getPdfUrl());
} else {
pdfInfo.setGenStatus("未处理");
Long rank = JedisAdapter.zRank(RedisKeyUtil.getNewContestPdfGenQueue(),
contestOneTest.getId() + "");
pdfInfo.setRank(String.valueOf(rank));
pdfInfo.setPdfUrl("暂无");
}
}
XSSFWorkbook workbook;
String fileName = new StringBuilder().append(contestOneTestList.size())
.append("位考试的PDF生成进度").toString();
try {
//生成表格并作为下载文件输出
workbook = ExcelUtils.buildWorkbook(pdfInfos);
invocation.addModel("status", PdfStatusEnum.HAS_GENERATED);
invocation.addModel("resultCount", contestOneTestList.size());
response.setHeader("Content-Disposition", "attachment;filename=" + fileName + ".xlsx");
response.setHeader("Content-Type",
"application/vnd.ms-excel");
OutputStream out = response.getOutputStream();
workbook.write(out);
} catch (Exception e) {
e.printStackTrace();
invocation.addModel("status", PdfStatusEnum.ExcelGenFailed.getType());
}
return "admin_pdf_info";
}
Is there any way to solve my problem?
Very grateful for all answers or suggesstions!
I have a Jhipster application that generate PDF with iText library, this PDF is saved in the computer in the route that I indicated.
I would like that when generating the pdf, a dialog box will appear to download the pdf. I am indifferent if the pdf is saved in the project folder or not saved in any place.
I have seen many posts giving possible answers on this page and on the internet, but many are already obsolete and others have not worked for me.
generatePDF
public void generatePDF(User u) {
String dest = "D:/PDF/result.pdf";
String src = "D:/PDF/template.pdf";
try {
PdfDocument pdf = new PdfDocument(new PdfReader(src), new PdfWriter(dest));
PdfAcroForm form = PdfAcroForm.getAcroForm(pdf, true);
Map<String, PdfFormField> fields = form.getFormFields();
fields.get("name").setValue(u.getFirstName());
fields.get("surname").setValue(u.getLastName());
fields.get("email").setValue(u.getEmail());
pdf.close();
} catch (IOException e) {
log.debug(e.getMessage());
}
}
UserResource
#GetMapping("/print-user/{id}")
#Timed
public ResponseEntity<User> printUserTemplate(#PathVariable Long id) {
User user = userRepository.findOne(id);
userService.generatePDF(user);
return ResponseUtil.wrapOrNotFound(Optional.ofNullable(user));
}
EDIT
entity.component.ts
downloadFile() {
this.entityService.downloadFile().subscribe();
}
entity.service.ts
downloadFile(): Observable<any> {
return this.http.get(SERVER_API_URL + 'api/downloadFile');
}
Use this to download the file:
#GetMapping("/downloadFile")
public ResponseEntity<Resource> downloadFile(HttpServletRequest request) {
// Load file as Resource
Resource resource = testService.loadFileAsResource();
// Try to determine file's content type
String contentType = null;
try {
contentType = request.getServletContext().getMimeType(resource.getFile().getAbsolutePath());
} catch (IOException ex) {
log.info("Could not determine file type.");
}
// Fallback to the default content type if type could not be determined
if (contentType == null) {
contentType = "application/octet-stream";
}
return ResponseEntity.ok().contentType(MediaType.parseMediaType(contentType)).header(
HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + resource.getFilename() + "\"").body(resource);
}
And this to generate the file:
public Resource loadFileAsResource() {
try {
Path path = Paths.get("D:\\PDF\\template.pdf");
Path filePath = path.normalize();
Resource resource = new UrlResource(filePath.toUri());
if (resource.exists()) {
return resource;
} else {
return null;
}
} catch (MalformedURLException ex) {
ex.printStackTrace();
return null;
}
}
References:
https://www.callicoder.com/spring-boot-file-upload-download-rest-api-example/
download a file from Spring boot rest service
I try to use a Wicket Modal Window to set the PropertyModel of an Entity. The problem is this Entity has a FIleUploadFields that i read non work nice with Ajax. I need to use AjaxSubmitLink inside the modal and i don't be able to get this work fine.
setMultiPart(true);
setMaxSize(Bytes.megabytes(100));
fileUpload = new FileUploadField("fileUpload");
fileUpload.setOutputMarkupId(true);
fileUpload.setOutputMarkupPlaceholderTag(true);
add(fileUpload);
save_btn = new AjaxLink("save_btn") {
#Override
public void onClick(AjaxRequestTarget art) {
final FileUpload uploadedFile = fileUpload.getFileUpload();
if (uploadedFile != null && uploadedFile.getSize() > 0) {
try {
if (GestioneDocumentiDcs.isTextDocument(uploadedFile)) {
String ext = GestioneDocumentiDcs.getTextExtension(uploadedFile.getContentType());
String nomeFile = "c_" + _corso.getId() + "_m_" + materialeCorso.getId() + ext;
byte[] b = ByteStreams.toByteArray(uploadedFile.getInputStream());
gd.salvaFile(b, gd.getPathCorso(_corso) + "/" + nomeFile);
materialeCorso.setPercorso(nomeFile);
materialeCorso.setDimensione(uploadedFile.getSize());
materialeCorso.setDataUpload(LocalDate.now());
}
} catch (Exception e) {
System.out.println("ERRORE: " + Utils.StampaStackError(e));
}
}
this is my code inside the Modal
AjaxLink does not submit the form, so nothing will be transferred to the server. You need either AjaxButton or AjaxSubmitLink.
This question already has an answer here:
Android send mail with PDF file
(1 answer)
Closed 7 years ago.
I need send a PDF file attach on a message, I have a button that calls a function that open a Intent with message, email address and subject filled, but I need that the PDF file has been attached too.
This is my code and I can not find my error, someone can help me please?
public void initializeWebView() {
// Initialize the webview
webView.setResourceClient(new XWalkResourceClient(webView) {
#Override
public boolean shouldOverrideUrlLoading(XWalkView view, String stringUrl) {
if(stringUrl.equals(baseUrl)) {
return false;
}
// mailto links will be handled by the OS.
if (stringUrl.startsWith("mailto:")) {
Uri uri = Uri.parse(stringUrl);
Intent intent = new Intent(Intent.ACTION_VIEW, uri);
String fileName = "bouhnik.pdf";
String filePath = (Configuration.getMagazineAssetPath()).toString()+ File.separator + fileName;
Context c = getActivity().getApplicationContext();
File file = null;
FileOutputStream fos = null;
try {
InputStream is = c.getAssets().open(filePath);
int size = is.available();
byte[] buffer = new byte[size];
is.read(buffer);
is.close();
fos = new FileOutputStream(file);
fos.write(buffer);
fos.close();
} catch (IOException e) {
Log.i("Ferrou",e.toString());
e.printStackTrace();
}
if (!file.exists() || !file.canRead()) {
return false;
}
intent.putExtra(intent.EXTRA_STREAM, file.getPath());
intent.setClassName("com.android.email", "com.android.mail.compose.ComposeActivity");
intent .putExtra(Intent.EXTRA_SUBJECT, "Subject");
WebViewFragment.this.startActivity(Intent.createChooser(intent, "Send email..."));
} else {
try {
URL url = new URL(stringUrl);
// We try to remove the referrer string to avoid passing it to the server in case the URL is an external link.
String referrer = "";
if (url.getQuery() != null) {
Map<String, String> variables = Configuration.splitUrlQueryString(url);
String finalQueryString = "";
for (Map.Entry<String, String> entry : variables.entrySet()) {
if (entry.getKey().equals("referrer")) {
referrer = entry.getValue();
} else {
finalQueryString += entry.getKey() + "=" + entry.getValue() + "&";
}
}
if (!finalQueryString.isEmpty()) {
finalQueryString = "?" + finalQueryString.substring(0, finalQueryString.length() - 1);
}
stringUrl = stringUrl.replace("?" + url.getQuery(), finalQueryString);
}
// Remove referrer from query string
if (!url.getProtocol().equals("file")) {
if (referrer.equals(WebViewFragment.this.getActivity().getString(R.string.url_external_referrer))) {
Uri uri = Uri.parse(stringUrl);
Intent intent = new Intent(Intent.ACTION_VIEW, uri);
WebViewFragment.this.startActivity(intent);
} else if (referrer.toLowerCase().equals(WebViewFragment.this.getActivity().getString(R.string.url_baker_referrer))) {
((IssueActivity) WebViewFragment.this.getActivity()).openLinkInModal(stringUrl);
return true;
} else {
return false;
}
} else {
stringUrl = url.getPath().substring(url.getPath().lastIndexOf("/") + 1);
int index = ((IssueActivity) WebViewFragment.this.getActivity()).getJsonBook().getContents().indexOf(stringUrl);
if (index != -1) {
Log.d(this.getClass().toString(), "Index to load: " + index + ", page: " + stringUrl);
((IssueActivity) WebViewFragment.this.getActivity()).getViewPager().setCurrentItem(index);
view.setVisibility(View.GONE);
} else {
// If the file DOES NOT exist, we won't load it.
File htmlFile = new File(url.getPath());
if (htmlFile.exists()) {
return false;
}
}
}
} catch (MalformedURLException | UnsupportedEncodingException ex) {
Log.d(">>>URL_DATA", ex.getMessage());
}
}
return true;
}
});
// Set UI Client (Start stop animations)
webView.setUIClient(new XWalkUIClient(webView) {
#Override
public void onPageLoadStopped(XWalkView view, String url, LoadStatus status) {
if(!url.isEmpty() && status == LoadStatus.FINISHED) {
if(isUserVisible) {
webView.resumeTimers();
}else{
webView.pauseTimers();
}
}
}
});
webView.load(baseUrl, null);
}
Thank's so much for everyone!!
I solve my problem change the type of Intent to:
Intent emailIntent = new Intent(Intent.ACTION_SEND);
Because this is better to email commands, and I define a emailUri where:
emailUri = Uri.fromFile(file.getAbsoluteFile());
because this get a absolute path with a file inside, and when the email client open, it open this file, not a path.
I add a type at my intent but I select the type of my attachment, so I define:
emailIntent.setType("application/pdf");
And finally:
emailIntent.putExtra(Intent.EXTRA_STREAM, uriMail);
startActivity(emailIntent);
It's works now!! Thanks :D
It looks like something is might be going wrong with your file path. Double check it. Then
1 - You need to add the package name of your application with context.getPackageName()
private String path = Environment.getExternalStorageDirectory().getPath() + context.getPackageName() + "books/"+fileName;
2 - Declare the permission inside your AndroidManifest.xml
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
This question already has answers here:
Recommended way to save uploaded files in a servlet application
(2 answers)
Closed 6 years ago.
<body>
<form method="post" action="DemoServlet" enctype="multipart/form-data" name="form1">
<input type="file" name="file" />
Image_Name:<input type="text" name="file"/>
<input type="submit" value="Go"/>
</form>
</body>
this is my index.jsp page.
This Servlet is DemoServlet when user click on submit button it will go here.while in jsp page suppose Image_Name given by user is IPL and actual name of image is funny.jpg then while saving the image it should store as IPL.png,here i'm able to upload image correctly with funny.jpg,but i need to save image as given name in text field of index.jsp page
public class DemoServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
Date date = new Date();
response.setContentType("text/html");
PrintWriter out = response.getWriter();
boolean isMultiPart = ServletFileUpload.isMultipartContent(request);
if (isMultiPart) {
ServletFileUpload upload = new ServletFileUpload();
try {
FileItemIterator itr = upload.getItemIterator(request);
while (itr.hasNext()) {
FileItemStream item = itr.next();
if (item.isFormField()) {
String fieldname = item.getFieldName();
InputStream is = item.openStream();
byte[] b = new byte[is.available()];
is.read(b);
String value = new String(b);
response.getWriter().println(fieldname + ":" + value + "</br>");
} else {
String TempPath = getServletContext().getRealPath("");
String path = TempPath.substring(0, TempPath.indexOf("build"));
if (FileUpload.processFile(path, item)) {
out.println("File Uploaded on:" + date + "<br>");
response.getWriter().println("Image Upload Successfully");
} else {
response.getWriter().println("Failed.....Try again");
}
}
}
} catch (FileUploadException fue) {
fue.printStackTrace();
}
}
}
}
and this is java class
public class FileUpload {
public static boolean processFile(String path, FileItemStream item) {
try {
File f = new File(path + File.separator + "web/images");
if (!f.exists()) {
f.mkdir();
}
File savedFile = new File(f.getAbsolutePath() + File.separator + item.getName());
FileOutputStream fos = new FileOutputStream(savedFile);
InputStream is = item.openStream();
int x = 0;
byte[] b = new byte[1024];
while ((x = is.read(b)) != -1) {
fos.write(b, 0, x);
}
fos.flush();
fos.close();
return true;
} catch (Exception e) {
e.printStackTrace();
}
return false;
}
}
Could anybody guide me how to change this dynamically.Thanks in advance.
I don't know how Servlet's and the like work however i can give you a rundown of what you need to do.
In DemoServlet you need to take in the input of the Image_Name field and make that one of your parameters of FileUpload
public static boolean processFile(String path, FileItemStream item, String fileName){
//Method Code
}
Because currently your processFile method is taking the name of the file from your FileItemStream. You need to change it from that to your actual fileName
File savedFile = new File(f.getAbsolutePath() + File.separator + item.getName());
to
File savedFile = new File(f.getAbsolutePath() + File.separator + fileName + ".png");
You can change the name of image in your java class code.
public class FileUpload {
public static boolean processFile(String path, FileItemStream item , String name) {
try {
File f = new File(path + File.separator + "web/images");
if (!f.exists()) {
f.mkdir();
}
File savedFile = new File(f.getAbsolutePath() + File.separator + item.getName()); // instead of item.getName() you can give your name.
FileOutputStream fos = new FileOutputStream(savedFile);
InputStream is = item.openStream();
int x = 0;
byte[] b = new byte[1024];
while ((x = is.read(b)) != -1) {
fos.write(b, 0, x);
}
fos.flush();
fos.close();
return true;
} catch (Exception e) {
e.printStackTrace();
}
return false;
}
you will have to pass the file name in the method.
instead of item.getName() you can give your name.
List fileItems = upload.parseRequest(request);
Iterator i = fileItems.iterator();
System.out.println("In >>>>>>>>>>>>>>> :: "+fileItems);
while(i.hasNext()){
FileItem fi = (FileItem) i.next();
System.out.println("Val <<<<>>>>>>:: "+fi);
if(fi.isFormField()){
String fieldName = fi.getFieldName();
String val = fi.getString();
System.out.println(fieldName+" :: Val :: "+val);
}else{
String fileName = fi.getName();
String root = getServletContext().getRealPath("/");
File path = new File(root+"/uploads");
if (!path.exists()) {
boolean status = path.mkdir();
}
File uploadFile = new File(path+"/"+fileName);
fi.write(uploadFile);
}
In the code above you can change the file name at any time and it will automatically save with this name.
//How does not work in this way?Please tell me another way.
import java.io.File;
public class RenameFileExample {
public static void main(String[] args)
{
File oldfile =new File("oldfile.txt");
File newfile =new File("newfile.txt");
File file = new File("oldfilename.png");
file.renameTo(new File("newfilename.png"));
System.out.println("Rename To:"+file.getName());
if(oldfile.renameTo(newfile)){
System.out.println("Rename succesful");
}else{
System.out.println("Rename failed");
}
}
}