Convert BLOB to PDF - java

I have a BLOB file which I have got from the DB team. I know that its a PDF document (I opened using Notepad++ and I could see the file name) and I need to convert the same using java. I have checked for few examples and I couldn't find any example where the BLOB file itself is taken as an input instead of taking directly from the DB (Resultset). Can anyone please give some pointers as to how I can accomplish this?
Thanks in advance!
I have tried below,
File file = new File("C:/Users/User1/Desktop/0LK54E33K1477e2MCEU25JV0G8MG418S007N45JU.BLOB0");
FileInputStream fis = new FileInputStream(file);
//System.out.println(file.exists() + "!!");
//InputStream in = resource.openStream();
ByteArrayOutputStream bos = new ByteArrayOutputStream();
byte[] buf = new byte[1024];
try {
for (int readNum; (readNum = fis.read(buf)) != -1;) {
bos.write(buf, 0, readNum); //no doubt here is 0
//Writes len bytes from the specified byte array starting at offset off to this byte array output stream.
System.out.println("read " + readNum + " bytes,");
}
} catch (IOException ex) {
//Logger.getLogger(genJpeg.class.getName()).log(Level.SEVERE, null, ex);
}
byte[] bytes = bos.toByteArray();
//below is the different part
File someFile = new File("C:/Users/User1/Desktop/Test.pdf");
FileOutputStream fos = new FileOutputStream(someFile);
fos.write(bytes);
fos.flush();
fos.close();

Related

Amazon Merchant Fulfilment Create Shipment Label

I am trying to get the shipment label from amazon merchant fulfillment as per the instructions mentioned on the Amazon pages.
"To obtain the actual PDF document, you must decode the Base64-encoded string, save it as a binary file with a “.zip” extension, and then extract the PDF file from the ZIP file."
Has any one got it to work. I have tried couple of things but every time i get blank pdf.
Here is my code. Can please some body guide me if I am doing it correctly
byte[] decodedBytes = Base64.decodeBase64(contents);
ZipOutputStream zos = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream("c:\\output\\asdwd.zip")));
//now create the entry in zip file
ZipEntry entry = new ZipEntry("asd.pdf");
zos.putNextEntry(entry);
zos.write(decodedBytes);
zos.close();
The instructions say to save the bytes as a binary file with the extension .zip.
What you are actually doing is creating a ZIP file with the contents of the byte array as an entry.
According to my reading of the instructions, your code should do this:
byte[] decodedBytes = Base64.decodeBase64(contents);
FileOutputStream fos = new FileOutputStream("c:\\output\\asdwd.zip");
fos.write(decodedBytes);
fos.close();
Or better still:
byte[] decodedBytes = Base64.decodeBase64(contents);
try (FileOutputStream fos = new FileOutputStream("c:\\output\\asdwd.zip")) {
fos.write(decodedBytes);
}
Then using a ZIP tool or a web browser, open asdwd.zip, find the entry containing the PDF, and extract it or print it.
Here is the code to generate a shipping label in case somebody needs it.
byte[] decoded = Base64.decodeBase64(contents);
try (FileOutputStream fos = new FileOutputStream(zipFilePath + amazonOrderId + zipFileName)) {
fos.write(decoded);
fos.close();
}
file = new File(destDirectory + amazonOrderId + pngFile);
if (file.exists()) {
file.delete();
}
try (OutputStream out = new FileOutputStream(destDirectory + amazonOrderId + pngFile)) {
try (InputStream in = new GZIPInputStream(
new FileInputStream(zipFilePath + amazonOrderId + zipFileName))) {
byte[] buffer = new byte[65536];
int noRead;
while ((noRead = in.read(buffer)) != -1) {
out.write(buffer, 0, noRead);
}
}
}

only first few hundred samples are read from input stream into byte array(the rest are zeros)

i'm trying to convert audio(mp3/wav etc.) to byte array. i did it using inputStream to byte array conversion.
the problem is that after few hundred samples i recieve only zeroes.
at first i thought the problem was with the file so i tried debugging with another file and had the same problem.
I thought the problem was with the code so i tried using IOUtils and got the exact same resualts.
can anyone tell me what i'm doing wrong?
the code i used:
File file = new File(path);
final InputStream inputStream = new FileInputStream(file);
byte[] byteSamples = inputStreamToByteArray(inputStream);
public byte[] inputStreamToByteArray(InputStream inStream) throws IOException {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] buffer = new byte[8192];
int bytesRead;
while ((bytesRead = inStream.read(buffer)) > 0) {
baos.write(buffer, 0, bytesRead);
}
return baos.toByteArray();
}
the alternate version using IOUtils:
byte[] byteSamples = IOUtils.toByteArray(inputStream);
update : i tried doing it using BufferedInputStream, still the exact same results.
byte[] byteSamples = new byte[(int)file.length()];
try {
BufferedInputStream buf = new BufferedInputStream(new FileInputStream(file));
buf.read(byteSamples, 0, byteSamples.length);
buf.close();
} catch (FileNotFoundException e) {
e.printStackTrace();}
You need to close the streams when done.

Android File To Base64 using streaming sometimes missed 2 bytes

i am writing to ask for the proper solution for solving the following difficulties:
I am required to encode the file in Base64 format, and there is no way for me to make the file small, as a result, i will surely suffered from OutOfMemory Exception, that why i used Streaming approach for solving it.
After the file is encoded, i have decoded it immediately by code and also online-tools. The decoded content was found missing 2 bytes at the end of the file sometimes, but not always. It did affected further processing to the file.
Hope someone could help and may be caused by an idiot mistake. Still thanks.
Here is the Code:
FileOutputStream fout = new FileOutputStream(path + ".txt");
//this is for printing out the base64 content
FileInputStream fin = new FileInputStream(path);
System.out.println("File Size:" + path.getTotalSpace());
ByteArrayOutputStream os = new ByteArrayOutputStream();
Base64OutputStream base64out = new Base64OutputStream(os,Base64.NO_WRAP);
byte[] buffer = new byte[3 * 512];
int len = 0;
while ((len = fin.read(buffer)) >= 0) {
base64out.write(buffer, 0, len);
}
System.out.println("Encoded Size:" + os.size());
String result = new String(os.toByteArray(), "UTF-8");
fout.write(os.toByteArray());
fout.close();
base64out.close();
os.close();
fin.close();
return result;
Here is the solution that works in the case of using Base64OutputStream. I will explain some of them after code:
Here is the Code:
FileOutputStream fout = new FileOutputStream(path + ".txt");
FileInputStream fin = new FileInputStream(path);
System.out.println("File Size:" + path.length());
ByteArrayOutputStream os = new ByteArrayOutputStream();
Base64OutputStream base64out = new Base64OutputStream(os,Base64.NO_WRAP);
byte[] buffer = new byte[3 * 512];
int len = 0;
while ((len = fin.read(buffer)) >= 0) {
base64out.write(buffer, 0, len);
}
System.out.println("Encoded Size:" + os.size());
base64out.flush();
base64out.close();//this did the tricks. Please see explanation.
String result = new String(os.toByteArray(), "UTF-8");
fout.write(os.toByteArray());
fout.flush();
fout.close();
os.close();
fin.close();
return result;
Actually, after using the suggestion from Dawnkeeper by added flush(), i have moved one line of code only.
The tricks is did in the base64out.close() before processing any data. As closing the Base64OutputStream might write Ending Padding of Base64 to the Output.
I got my idea from org.apache.myfaces.trinidad.util.Base64OutputStream close() method. That's why i tried.
It might seems strange closing the OutputStream before data processing, but it only close Base64OutputStream but not ByteArrayOutputStream at the same time in this case. Therefore, the data could still retrieve from ByteArrayOutputStream.
Thanks Dawnkeeper efforts, and hope this question could helps other suffered in OutOfMemory Exception.
Your streams should be flushed before using them for other operations and before closing them:
FileOutputStream fout = new FileOutputStream(path + ".txt");
//this is for printing out the base64 content
FileInputStream fin = new FileInputStream(path);
System.out.println("File Size:" + path.length()); // path.getTotalSpace() is the filesystem size
ByteArrayOutputStream os = new ByteArrayOutputStream();
Base64OutputStream base64out = new Base64OutputStream(os,Base64.NO_WRAP);
byte[] buffer = new byte[3 * 512];
int len = 0;
while ((len = fin.read(buffer)) >= 0) {
base64out.write(buffer, 0, len);
}
System.out.println("Encoded Size:" + os.size());
base64out.write(System.lineSeparator().getBytes());
base64out.flush(); // to be sure that everything is in the byte array
String result = new String(os.toByteArray(), "UTF-8");
fout.write(os.toByteArray());
fout.flush(); // make sure everything is written
fout.close();
base64out.close();
os.close();
fin.close();
System.out.println("new File Size:" + new File(path + ".txt").length()); // prints out the size of the finished file
return result;

how to convert image to byte array in java?(With out using buffered image)

Hi could anyone please explain me how to convert the image data to byte array in java I am trying like this.I do not need to use buffered image here.
File file = new File("D:/img.jpg");
FileInputStream imageInFile = new FileInputStream(file);
byte imageData[] = new byte[(int) file.length()];
imageInFile.read(imageData);
You can convert your image data using FileInputStream also.
File file = new File("D:\\img.jpg");
FileInputStream fis = new FileInputStream(file);
//Now try to create FileInputStream which obtains input bytes from a file.
//FileInputStream is meant for reading streams of raw bytes,in this case its image data.
//For reading streams of characters, consider using FileReader.
ByteArrayOutputStream bos = new ByteArrayOutputStream();
byte[] buf = new byte[1024];
try {
for (int readNum; (readNum = fis.read(buf)) != -1;) {
//Now Write to this byte array output stream
bos.write(buf, 0, readNum);
System.out.println("read " + readNum + " bytes,");
}
} catch (IOException ex) {
Logger.getLogger(ConvertImage.class.getName()).log(Level.SEVERE, null, ex);
}
byte[] bytes = bos.toByteArray();
or you could use:
Image image = Toolkit.getDefaultToolkit().getImage("D:/img.jpg");
byte[] imageBytes = getImageBytes(image);
private byte[] getImageBytes(Image image) throws IOException {
try (ByteArrayOutputStream baos = new ByteArrayOutputStream()) {
ImageIO.write(image, "bmp", baos);
baos.flush();
return baos.toByteArray();
}
}

Java: Need to create PDF from byte-Array

From a DB2 table I've got blob which I'm converting to a byte array so I can work with it. I need to take the byte array and create a PDF out of it.
This is what I have:
static void byteArrayToFile(byte[] bArray) {
try {
// Create file
FileWriter fstream = new FileWriter("out.pdf");
BufferedWriter out = new BufferedWriter(fstream);
for (Byte b: bArray) {
out.write(b);
}
out.close();
} catch (Exception e) {
System.err.println("Error: " + e.getMessage());
}
}
But the PDF it creates is not right, it has a bunch of black lines running from top to bottom on it.
I was actually able to create the correct PDF by writing a web application using essentially the same process. The primary difference between the web application and the code about was this line:
response.setContentType("application/pdf");
So I know the byte array is a PDF and it can be done, but my code in byteArrayToFile won't create a clean PDF.
Any ideas on how I can make it work?
Sending your output through a FileWriter is corrupting it because the data is bytes, and FileWriters are for writing characters. All you need is:
OutputStream out = new FileOutputStream("out.pdf");
out.write(bArray);
out.close();
One can utilize the autoclosable interface that was introduced in java 7.
try (OutputStream out = new FileOutputStream("out.pdf")) {
out.write(bArray);
}
Read from file or string to bytearray.
byte[] filedata = null;
String content = new String(bytearray);
content = content.replace("\r", "").replace("\uf8ff", "").replace("'", "").replace("\"", "").replace("`", "");
String[] arrOfStr = content.split("\n");
PDDocument document = new PDDocument();
PDPage page = new PDPage();
document.addPage(page);
try (PDPageContentStream cs = new PDPageContentStream(document, page)) {
// setting font family and font size
cs.beginText();
cs.setFont(PDType1Font.HELVETICA, 14);
cs.setNonStrokingColor(Color.BLACK);
cs.newLineAtOffset(20, 750);
for (String str: arrOfStr) {
cs.newLineAtOffset(0, -15);
cs.showText(str);
}
cs.newLine();
cs.endText();
}
document.save(znaFile);
document.close();
public static String getPDF() throws IOException {
File file = new File("give complete path of file which must be read");
FileInputStream stream = new FileInputStream(file);
byte[] buffer = new byte[8192];
ByteArrayOutputStream baos = new ByteArrayOutputStream();
int bytesRead;enter code here
while ((bytesRead = stream.read(buffer)) != -1) {
baos.write(buffer, 0, bytesRead);
}
System.out.println("it came back"+baos);
byte[] buffer1= baos.toByteArray();
String fileName = "give your filename with location";
//stream.close();
FileOutputStream outputStream =
new FileOutputStream(fileName);
outputStream.write(buffer1);
return fileName;
}

Categories

Resources