Convert PDF to ByteArrayOutputStream

Convert PDF to ByteArrayOutputStream

To Convert PDF to ByteArrayOutputStream first you have to create InputStream object and pass path of PDF file then read InputStream object and write to ByteArrayOutputStream object. Below is detail java code:

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 ConvertPDFToByteArrayOutputStream {

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

    ByteArrayOutputStream baos = convertPDFToByteArrayOutputStream();       

    }

    private static ByteArrayOutputStream 
            convertPDFToByteArrayOutputStream() {

    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;
    }

}

 

Leave a Reply

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

I am not Robot *