Convert PDF to byte array

Convert PDF to byte array

To Convert PDF to byte array instantiate InputStream and pass PDF file path to FileInputStream constructor then read this stream and write it to ByteArrayOutputStream object once process complete convert it to byte array. Below is java sample program:

package com.javahonk;

import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;

public class ConvertPDFToByteArray {

    /**
     * @param args
     */
    public static void main(String[] args) {

        byte data[] = convertPDFToByteArray();

    }

    private static byte[] convertPDFToByteArray() {

        InputStream inputStream = null;
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        try {

            inputStream = new FileInputStream("sourcePath_of_pdf.pdf");

            byte[] buffer = new byte[1024];
            baos = new ByteArrayOutputStream();

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

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return baos.toByteArray();
        }

}

Leave a Reply

Your email address will not be published. Required fields are marked *