从ftp服务器检索pdf / tiff并将其发送到jsp

时间:2013-10-24 20:19:31

标签: java jsp pdf ftp tiff

我正在尝试从FTP服务器中的特定位置检索多个pdf / tiff文件,加入它们并将它们发送到要显示的jsp页面。到目前为止,这就是我所做的。

在动作类中, a)我尝试在名为pdfbean的bean中检索文件详细信息, b)将pdfbean传递给一个进行ftp连接并从服务器检索文件的方法 c)将其转换为byte []并将其返回以添加到文档中。

现在这个文档存储在C:\中,这不是我想要的。我想将它发送到jsp页面。截至目前,我不知道如何发送它。

            ArrayList<PdfBean> list = msgDH.getFileDtls(hawbString);
            Document doc = new Document();
            PdfWriter write = PdfWriter.getInstance(doc,
                    new FileOutputStream("c://Image.pdf"));
            write.setPdfVersion(PdfWriter.PDF_VERSION_1_5);
            doc.open();

            for (PdfBean pdfBean : list)
            {
                byte[] Image2 = getfile(pdfBean);
                Image img = Image.getInstance(Image2);
                doc.add(img);
                doc.newPage();
            }
            doc.close();
            System.out.println("Done saving");

下面是getfile()方法

private byte[] getfile(PdfBean pdfBean)
{

    byte[] result = null;
    boolean test = false;
    FTPClient ftp = new FTPClient();
    DataSourceReader dsr = new DataSourceReader();
    dsr.getFtpLinks();
    String ftppassword = dsr.getFtppassword();
    String ftpserver = dsr.getFtpserver();
    String ftpusername = dsr.getFtpusername();
    System.out.println("no" + ftpserver + ftpusername + ftppassword);
    try
    {
        ftp.connect(ftpserver);
    } catch (SocketException e1)
    {
        e1.printStackTrace();
    } catch (IOException e1)
    {
        e1.printStackTrace();
    }
    InputStream is = null;
    BufferedInputStream bis = null;
    try
    {
        boolean login = ftp.login(ftpusername, ftppassword);
    } catch (IOException e1)
    {
        e1.printStackTrace();
    }
    try
    {
        int reply;
        reply = ftp.getReplyCode();
        if (!FTPReply.isPositiveCompletion(reply))
        {
            ftp.disconnect();
            System.out.println("FTP server refused connection.");
        } else
        {

            ftp.enterLocalPassiveMode();
            FTPFile[] ftpFiles = ftp.listFiles(pdfBean.getFileLocation());

            String fN = "";
            int i = 0;
          //tiff and pdf files reside in different folders. 
            if (pdfBean.getFileLocation().equals("/hold/TIF"))
            {
                String F = pdfBean.getFileName().replaceAll(".PDF", ".TIF");
                for (FTPFile ftpFile : ftpFiles)
                {
                    if (ftpFile.getName().equals(F))
                    {
                        fN = pdfBean.getFileLocation().concat("/")
                                .concat(F);
                        i = 1;
                    }

                }
                if (i == 0)
                {
                    F = pdfBean.getFileName().replaceAll(".PDF", ".TIFF");
                    for (FTPFile ftpFile : ftpFiles)
                    {
                        if (ftpFile.getName().equals(F))
                        {
                            fN = pdfBean.getFileLocation().concat("/")
                                    .concat(F);
                            i = 1;
                        }

                    }
                }

            } else
            {
                fN = pdfBean.getFileLocation().concat("/")
                        .concat(pdfBean.getFileName());
            }
            InputStream in = ftp.retrieveFileStream(fN);
            BufferedInputStream inbf = new BufferedInputStream(in);
            byte[] buffer = IOUtils.toByteArray(in);// new byte[1024];
            result = buffer;
            /*
             * int readCount;
             * 
             * int lenght = 0;
             * 
             * while( (readCount = inbf.read(buffer)) > 0) { int preLength =
             * lenght; lenght += readCount; byte temp[] = new
             * byte[result.length]; result = new byte[lenght];
             * System.arraycopy(temp,0,result,0,temp.length);
             * System.arraycopy(buffer,0,result,preLength,readCount); }
             */

        }

    } catch (Exception ex)
    {
        System.out.println("Exception ----->" + ex.getMessage());
    } finally
    {
        try
        {
            if (bis != null)
            {
                bis.close();
            }
            if (is != null)
            {
                is.close();
            }
        } catch (IOException e)
        {
            e.printStackTrace();
        }
        try
        {
            ftp.logout();
        } catch (IOException e)
        {
            e.printStackTrace();
        }
        try
        {
            ftp.disconnect();
        } catch (IOException e)
        {
            e.printStackTrace();
        }
    }
    return result;

}

我得到一个java.lang.NegativeArraySizeException我哪里错了。您是否预见到将tif和pdf作为图像添加到同一文档时会出现任何问题。最后,一旦我准备好文件,我该如何将其发送到JSP页面?

1 个答案:

答案 0 :(得分:0)

for (PdfBean pdfBean : list)
            {
                if(!pdfBean.getFileName().isEmpty()&&!pdfBean.getFileLocation().isEmpty()){


                msgDH.InsertUserHistDtls(pdfBean.getHawb(), userId, pdfBean.getCustomer(), pdfBean.getFileName(), pdfBean.getProduct(), pdfBean.getDocType(), "Print");
                msgDH.InsertLogDtls(pdfBean.getFileName(), pdfBean.getProduct(), pdfBean.getCustomer(), userId);

                FTPClient ftp = new FTPClient();
                int tiffPages = 0;
                try
                {
                    ftp.connect(ftpserver);
                } catch (SocketException e1)
                {
                    // TODO Auto-generated catch block
                    e1.printStackTrace();
                } catch (IOException e1)
                {
                    // TODO Auto-generated catch block
                    e1.printStackTrace();
                }

                try
                {
                    boolean login = ftp.login(ftpusername, ftppassword);
                } catch (IOException e1)
                {
                    // TODO Auto-generated catch block
                    e1.printStackTrace();
                }
                int reply;
                reply = ftp.getReplyCode();
                if (!FTPReply.isPositiveCompletion(reply))
                {
                    ftp.disconnect();
                    System.out.println("FTP server refused connection.");
                } else
                {
                    // ftp.enterLocalPassiveMode();
                    ftp.enterLocalActiveMode();
                    ftp.setFileType(FTPClient.BINARY_FILE_TYPE);
                    ftp.changeWorkingDirectory(pdfBean.getFileLocation());
                    /* FTPFile[] */
                    ftpFiles = ftp.listFiles();
                    /* FTPFile[] */// ftpFiles = ftp.listFiles();
                    // ftp.completePendingCommand();
                }

                String fileName = pdfBean.getFileLocation() + "/"
                        + pdfBean.getFileName();
                if ("/interface/oracle/dds/generic/hold/TIF"
                        .equalsIgnoreCase(pdfBean.getFileLocation()))
                {
                    int i = 0;
                    String F = pdfBean.getFileName().replaceAll(".PDF",
                            ".TIF");
                    // FTPFile[] ftpFiles =
                    // ftp.listFiles(pdfBean.getFileLocation());
                    for (FTPFile ftpFile : ftpFiles)
                    {
                        if (ftpFile.getName().equals(F))
                        {
                            fileName = pdfBean.getFileLocation()
                                    .concat("/").concat(F);
                            i = 1;
                        }

                    }
                    if (i == 0)
                    {
                        F = pdfBean.getFileName().replaceAll(".PDF",
                                ".TIFF");
                        for (FTPFile ftpFile : ftpFiles)
                        {
                            if (ftpFile.getName().equals(F))
                            {
                                fileName = pdfBean.getFileLocation()
                                        .concat("/").concat(F);
                                i = 1;
                            }

                        }
                    }
                    int Repcode = ftp.getReplyCode();
                    //
                    // System.out.println(Repcode);
                    /* if(fileName.endsWith(".TIF")) */

                    InputStream is = (InputStream) ftp.retrieveFileStream(fileName);
                    Repcode = ftp.getReplyCode();
                    System.out.println(Repcode);
                    // ftp.completePendingCommand();
                    Repcode = ftp.getReplyCode();
                    System.out.println(Repcode);
                    ra1 = new RandomAccessFileOrArray(is);
                    tiffPages = TiffImage.getNumberOfPages(ra1);
                    System.out.println("No of pages in image is : "
                            + tiffPages);
                    for (int a = 1; a <= tiffPages; a++)
                    {
                        try
                        {
                            Image img = TiffImage.getTiffImage(ra1, a);
                            if (img != null)
                            {
                                if (img.getScaledWidth() > 500
                                        || img.getScaledHeight() > 700)
                                {
                                    img.scaleToFit(800, 800);
                                }
                                doc.setPageSize(new Rectangle(img
                                        .getScaledWidth(), img
                                        .getScaledHeight()));
                                img.setAbsolutePosition(0, 0);
                                cb.addImage(img);
                                // doc.
                                doc.newPage();
                                // ++pages;
                            }
                        } catch (Throwable e)
                        {
                            System.out.println("Exception " + " page "
                                    + (a + 1) + " " + e.getMessage());
                        }
                    }
                    is.close();
                    ra1.close();

                }
                else{

                    InputStream pdf = ftp.retrieveFileStream(fileName);
                    if(pdf != null) {
                        PdfReader pdfRea = new PdfReader(pdf);
                        readers.add(pdfRea);
                        totalPages += pdfRea.getNumberOfPages();   
                    }


                    /*totalPages += pdfRea.getNumberOfPages();


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

                    BaseFont bf = BaseFont.createFont(BaseFont.HELVETICA,
                            BaseFont.CP1252, BaseFont.NOT_EMBEDDED);
                   // 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()) {
                           doc.newPage();
                           pageOfCurrentReaderPDF++;
                           currentPageNumber++;
                           page = write.getImportedPage(pdfReader, pageOfCurrentReaderPDF);
                           cb.addTemplate(page, 0, 0);

                           // Code for pagination.
                           cb.beginText();
                           cb.setFontAndSize(bf, 9);
                           cb.showTextAligned(PdfContentByte.ALIGN_CENTER, ""
                                   + currentPageNumber + " of " + totalPages, 520, 5, 0);
                           cb.endText();
                       }
                       pageOfCurrentReaderPDF = 0;
                   }*/
                }

                ftp.logout();
                ftp.disconnect();
                ftp = null;
            }}



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

            BaseFont bf = BaseFont.createFont(BaseFont.HELVETICA,
                    BaseFont.CP1252, BaseFont.NOT_EMBEDDED);
           // 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()) {
                   doc.newPage();
                   pageOfCurrentReaderPDF++;
                   currentPageNumber++;
                   page = write.getImportedPage(pdfReader, pageOfCurrentReaderPDF);
                   cb.addTemplate(page, 0, 0);

                   // Code for pagination.
                   cb.beginText();
                   cb.setFontAndSize(bf, 9);
                   cb.showTextAligned(PdfContentByte.ALIGN_CENTER, ""
                           + currentPageNumber + " of " + totalPages, 520, 5, 0);
                   cb.endText();
               }
               pageOfCurrentReaderPDF = 0;
           }
        }
        doc.close();
        write.flush();
        write.close();
        System.out.println("done printing");

    }


    FileInputStream fiss = new FileInputStream(temp);  
    bis = new BufferedInputStream(fiss);
    response.reset();