0

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 {

    }

}
futureelite7
  • 11,462
  • 10
  • 53
  • 87

3 Answers3

0

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.

LarsBauer
  • 1,539
  • 18
  • 23
0

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)

MoYapro
  • 119
  • 1
  • 8
0

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

David H.
  • 953
  • 1
  • 8
  • 20