多文件追加不起作用

时间:2017-02-10 13:01:05

标签: jsf primefaces

我有一个程序可以将输入表单转换为pdf文件,还有一个选项可以上传另一个pdf并将这两个pdf附加到单个文档中。我已经更改了启用多个文件上传的代码。 但是当上传多个pdf时,它会导致0kb文件。

  

附加代码适用于单个pdf上传

这是我的AgreementsBean。

public void handleFileUpload(FileUploadEvent event) {
    try {
        Class.forName(drivername);
        Connection con = DriverManager.getConnection(urlName, databaseUsername, databasePassword);
        Statement st = con.createStatement();
        String saved_file = "";
        String fileName1 = "";
        if (null != event.getFile().getFileName() && event.getFile().getSize() != 0) {
            fileName1 = event.getFile().getFileName().replaceAll("\\s", "_");
            int mid = fileName1.lastIndexOf(".");
            String fname = fileName1.substring(0, mid);
            InputStream inputStream = event.getFile().getInputstream();
            String ext = fileName1.substring(mid + 1, fileName1.length());
            FileUploadDownload fileUploadDownload = new FileUploadDownload();
            File file1 = new File(LoginBean.uploadPath + "/generatedagreements");
            if (!file1.exists()) {
                if (file1.mkdir()) {
                }
            }
            File file2 = new File(LoginBean.uploadPath + "/generatedagreements");
            if (!file2.exists()) {
                if (file2.mkdir()) {
                }
            }
            String path = "/generatedagreements";
            saved_file = fileUploadDownload.upload(path, fname, ext, inputStream);
            list.add(new FileInputStream(new File(LoginBean.uploadPath + "generatedagreements/" + saved_file)));

        }
        mergeFiles();
        st.close();
        con.close();
    } catch (Exception e) {
        logger.error("Exception"+e.getMessage());
        e.printStackTrace();
        System.out.println("ERROR AT Upload" + e.getLocalizedMessage());
    }
}

public void concatPDFs(List<InputStream> streamOfPDFFiles,
        OutputStream outputStream, boolean paginate) throws DocumentException, IOException {

    Document document = new Document();
    try {
        List<InputStream> pdfs = streamOfPDFFiles;
        List<PdfReader> readers = new ArrayList<PdfReader>();
        int totalPages = 0;
        Iterator<InputStream> iteratorPDFs = pdfs.iterator();

        // Create Readers for the pdfs.
        while (iteratorPDFs.hasNext()) {
            InputStream pdf = iteratorPDFs.next();
            PdfReader pdfReader = new PdfReader(pdf);
            readers.add(pdfReader);
            totalPages += pdfReader.getNumberOfPages();
        }
        // Create a writer for the outputstream
        PdfWriter writer = PdfWriter.getInstance(document, outputStream);

        document.open();
        BaseFont bf = BaseFont.createFont(BaseFont.HELVETICA,
                BaseFont.CP1252, BaseFont.NOT_EMBEDDED);
        PdfContentByte cb = writer.getDirectContent(); // Holds the PDF
        // data

        PdfImportedPage page;
        int currentPageNumber = 0;
        int pageOfCurrentReaderPDF = 0;
        Iterator<PdfReader> iteratorPDFReader = readers.iterator();

        // Loop through the PDF files and add to the output.
        while (iteratorPDFReader.hasNext()) {
            PdfReader pdfReader = iteratorPDFReader.next();

            // Create a new page in the target for each source page.
            while (pageOfCurrentReaderPDF < pdfReader.getNumberOfPages()) {
                document.newPage();
                pageOfCurrentReaderPDF++;
                currentPageNumber++;
                page = writer.getImportedPage(pdfReader,
                        pageOfCurrentReaderPDF);
                cb.addTemplate(page, 0, 0);

                // Code for pagination.
                if (paginate) {
                    cb.beginText();
                    cb.setFontAndSize(bf, 9);
                    cb.showTextAligned(PdfContentByte.ALIGN_CENTER, ""
                            + currentPageNumber + " of " + totalPages, 520,
                            5, 0);
                    cb.endText();
                }
            }
            pageOfCurrentReaderPDF = 0;
        }
        outputStream.flush();
        document.close();
        outputStream.close();
    } catch (Exception e) {
        logger.error("Exception"+e.getMessage());
        e.printStackTrace();
    } finally {
        if (document.isOpen()) {
            document.close();
        }
        try {
            if (outputStream != null) {
                outputStream.close();
            }
        } catch (IOException ioe) {
            logger.error("Exception"+ioe.getMessage());
            ioe.printStackTrace();
        }
    }
}

public void mergeFiles() {
    OutputStream out = null;
    try {

        Date dNow = new Date();
        SimpleDateFormat ft = new SimpleDateFormat("yyyyMMddHHmmss");
        System.out.println("Current Date: " + ft.format(dNow));
        String fileName = ft.format(dNow) + "." + "pdf";
        out = new FileOutputStream(new File(LoginBean.uploadPath + "generatedagreements/" + fileName));
        mergeFile = LoginBean.uploadPath + "generatedagreements/" + fileName;
        try {
            // doMerge(list, out);
            concatPDFs(list, out, true);
            FacesMessage message = new FacesMessage(FacesMessage.SEVERITY_INFO, "Contract Forms", "File Genarated");
            RequestContext.getCurrentInstance().showMessageInDialog(message);
        } catch (DocumentException ex) {
            logger.error("Exception"+ex.getMessage());
            //Logger.getLogger(AgreementsBean.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            logger.error("Exception"+ex.getMessage());
            //Logger.getLogger(AgreementsBean.class.getName()).log(Level.SEVERE, null, ex);
        }
    } catch (FileNotFoundException ex) {
        logger.error("Exception"+ex.getMessage());
        //Logger.getLogger(AgreementsBean.class.getName()).log(Level.SEVERE, null, ex);
    } finally {
        try {
            out.close();
        } catch (IOException ex) {
            logger.error("Exception"+ex.getMessage());
            //Logger.getLogger(AgreementsBean.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}

agreements.xhtml

  <div class="col-md-12">
        <p:fileUpload  mode="advanced" dragDropSupport="false" fileUploadListener="#{agreementsBean.handleFileUpload}"
             multiple="true"  fileLimit="5"  allowTypes="/(\.|\/)(pdf)$/" />
        <p:commandLink   oncomplete="PF('mergepdf').show();" action="#{agreementsBean.mergeFiles}"
             rendered="#{agreementsBean.downloadEnable}" ><i class="fa fa-file-pdf-o fa-3x" aria-hidden="true"></i></p:commandLink>
     </div>

的web.xml

    <filter>
        <filter-name>PrimeFaces FileUpload Filter</filter-name>
        <filter-class>
            org.primefaces.webapp.filter.FileUploadFilter
        </filter-class>
        <init-param>
            <description>Maximum size of stored in memory file</description>
            <param-name>thresholdSize</param-name>
            <param-value>20097152</param-value>
        </init-param>
    </filter>
    <filter-mapping>
        <filter-name>PrimeFaces FileUpload Filter</filter-name>
        <servlet-name>Faces Servlet</servlet-name>
    </filter-mapping>
    <context-param>
        <param-name>primefaces.UPLOADER</param-name>
        <param-value>auto</param-value>
    </context-param>

通过调试,我发现即使上传了两个文件,event参数也只有一个文件。但无法解决问题所在。

0 个答案:

没有答案