Search code examples
javapdfpdf-generationitextbytearrayoutputstream

How to put the ByteArrayInputStream content into a PDF using iText?


I have the following situation, into a method I have:

ByteArrayInputStream fis = new ByteArrayInputStream(Bean.getValoreString("PDFmulti", "PDF").getBytes());

As you can see fis varialbe is a ByteArrayInputStream and Bean.getValoreString("PDFmulti", "PDF").getBytes() returns a byte[]

So now I need to put the content of the fis object into a PDF using iText.

What can I do to do it? I think that I have to read this input stream and put its content into a ByteArrayOutputStream, something like this:

public static byte[] readFully(InputStream stream) throws IOException
{
    byte[] buffer = new byte[8192];
    ByteArrayOutputStream baos = new ByteArrayOutputStream();

    int bytesRead;
    while ((bytesRead = stream.read(buffer)) != -1)
    {
        baos.write(buffer, 0, bytesRead);
    }
    return baos.toByteArray();
}

But then?


Solution

  • In a comment to your previous question https://stackoverflow.com/questions/28342714/how-to-convert-a-string-object-representing-a-pdf-into-a-bytearrayinputstream-th, you say I have to concatenate all the PDF to create a single PDF.

    This is crucial information that you are omitting in your new question. If I read your new question, it's as if you want to persist a PDF that exists in a byte[] in some other form. For instance: you want to store it as a file.

    If that is the case, then you don't need iText! Just write the bytes to a FileOutputStream!

    However, now that I know that you need to concatenate files, I know that you need several PdfReader instances and then use these PdfReader instances in combination with PdfCopy (or PdfSmartCopy) to create a single PDF out of a series of different PDFs.

    That's a completely different question! In that case, why would you create a ByteArrayOutputStream? There is a PdfReader contructor that accepts an InputStream as a parameter. Why not pass fis to that constructor?