Search code examples
itext

NUL character at the end file - iText5.5.13.2


NUL characters are repeatedly written at the end of PDF file when writing a PDF/A3 PDF file using iText5.5.13.2.

End of file sample given below. Any ways to remove this while writing the PDF?

enter image description here


Solution

  • As mentioned by @mkl, This is due to trailing zero/null in your byte Array when the resulting pdf is streamed to any memory byte array.

    You refer to the below code on how to remove the trailing nulls from byte arrays

    public static byte[] getTrimmedBytes(byte[] bytes) {
        int i = bytes.length - 1;
        while (i >= 0 && bytes[i] == 0) {
            --i; // to find the index value from end where value 0 starts
        }
    
        return Arrays.copyOf(bytes, i + 1); 
    }
    

    or if you know the actual size of data in a byte array in advance, apply the below function directly

    byte[] trimmedBytes = Arrays.copyOf(bytes, size);