0

I have a webservice which returns pdf invoices. The client code is using HttpURLConnection to consume the service. It reads the invoice in InputStream and then write to the OutputStream. All of this is working. Now there is a requirement to select multiple invoices and press the download button. 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. 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();

1 Answer 1

2

You can't just concatenate PDF files, because the file format is too complex for that.

  • The most common solution for downloading multiple files in one operation, is to download them as a ZIP file. This can be done "live" by using a ZipOutputStream and then writing the individual PDF files to the stream, one at a time.

    There are many examples of that available on the 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.

I wouldn't recommend the second option. It is better to keep the invoices separated.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.