简体   繁体   English

在Java中将多个InputStreams写入OutputStream?

[英]Writing multiple InputStreams to OutputStream in Java?

I have a webservice which returns pdf invoices.我有一个返回 pdf 发票的网络服务。 The client code is using HttpURLConnection to consume the service.客户端代码使用 HttpURLConnection 来使用服务。 It reads the invoice in InputStream and then write to the OutputStream.它读取 InputStream 中的发票,然后写入 OutputStream。 All of this is working.所有这些都在起作用。 Now there is a requirement to select multiple invoices and press the download button.现在有要求select 多张发票并按下载按钮。 It should concatenate the selected invoices and open as one browsable document.它应该连接选定的发票并作为一个可浏览的文档打开。

I have tried using the SequenceInputStream as below but it always open the last selected invoice.我尝试使用如下所示的 SequenceInputStream,但它总是打开最后选择的发票。 Here is my code这是我的代码

 for (int i=0; i < docIds.length; i++) {
        URL url = new URL(baseurl + "/invoices/" + docIds[i]);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("GET");
        conn.setRequestProperty("Authorization", Application.get("documentum", "Authorization"));
        conn.setRequestProperty("Accept", "application/pdf");
        conn.setConnectTimeout(20000);
        conn.setReadTimeout(20000);
        conn.connect();
        if (!conn.getContentType().equalsIgnoreCase("application/pdf")) {
            System.out.println("FAILED.\n[Sorry. This is not a PDF.]");
            return false;
        } else {
            response.setContentType("application/pdf");
            response.setHeader("Content-Disposition", "filename=fbau-doc.pdf");
            outputStream = response.getOutputStream();
            InputStream in = conn.getInputStream();
            streams.add(in);

        }
  SequenceInputStream sequenceInputStream = new SequenceInputStream(streams.elements());
    // clean up
    IOUtils.copy(sequenceInputStream, outputStream);
    outputStream.close();

You can't just concatenate PDF files, because the file format is too complex for that.您不能只连接 PDF 文件,因为文件格式太复杂了。

  • The most common solution for downloading multiple files in one operation, is to download them as a ZIP file.在一次操作中下载多个文件的最常见解决方案是将它们下载为 ZIP 文件。 This can be done "live" by using a ZipOutputStream and then writing the individual PDF files to the stream, one at a time.这可以通过使用ZipOutputStream来“实时”完成,然后将各个 PDF 文件写入 stream,一次一个。

    There are many examples of that available on the web. web 上有很多这样的例子。

  • If you truly want/need to merge/combine the PDF files into a new multi-page PDF file, then you need to find a PDF library that can help you to do that.如果您确实想要/需要将 PDF 文件合并/组合成一个新的多页 PDF 文件,那么您需要找到一个可以帮助您的 PDF 库。

I wouldn't recommend the second option.我不会推荐第二种选择。 It is better to keep the invoices separated.最好将发票分开。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM