I was trying to generate PDf from byte array in Java which was returned through webservice, But the PDF cannot be opened. It shows its corrupted, I have attached my code. Anyone pls help about where i got wrong?
JSONObject o = new JSONObject(outjson);
JSONObject jsonob = o.optJSONObject("PDF details");
byte[] pdfbyte=jsonob.optString("pdf bytearray").toString().getBytes();
String str1 = new String(pdfbyte);
File someFile = new File("C:/Users/acer/Desktop/test1.pdf");
FileOutputStream fos = new FileOutputStream(someFile);
byte[] byteData = str1.getBytes();
byte[] byteData1 = test.getBytes();
fos.write(pdfbyte);
fos.flush();
fos.close();
Following is my JSON from webservice:
{"PDF details": {
"id":"121",
"pdf bytearray":"[B#62a58cd"
}
}
Following is my webservice code which outputs bytearray in json:
public Response getPdf( )
{
String flag=null;
File file = new File("C:/Users/acer/Desktop/Report.pdf");
FileInputStream fileInputStream;
byte[] data = null;
byte[] finalData = null;
ByteArrayOutputStream byteArrayOutputStream = null;
fileInputStream = new FileInputStream(file);
data = new byte[(int)file.length()];
finalData = new byte[(int)file.length()];
byteArrayOutputStream = new ByteArrayOutputStream();
fileInputStream.read(data);
byteArrayOutputStream.write(data);
finalData = byteArrayOutputStream.toByteArray();
fileInputStream.close();
System.out.println(finalData);
JSONObject jsonObject = new JSONObject();
JSONObject mainjsonObject = new JSONObject();
jsonObject.put("id","121");
jsonObject.put("pdf bytearray",finalData);
mainjsonObject.put("PDF details",jsonObject);
flag = "" + mainjsonObject;
return Response.status(200).entity(flag).build();
}
i got it right with following chnge in my webservice:
public Response getPdf( )
{
String flag=null;
File file = new File("C:/Users/acer/Desktop/Report.pdf");
FileInputStream fileInputStreamReader = new FileInputStream(file);
byte[] bytes = new byte[(int)file.length()];
fileInputStreamReader.read(bytes);
String encodedBase64 = new String(Base64.encodeBase64(bytes));
JSONObject jsonObject = new JSONObject();
JSONObject mainjsonObject = new JSONObject();
jsonObject.put("id","121");
jsonObject.put("pdf bytearray",encodedBase64);
mainjsonObject.put("PDF details",jsonObject);
flag = "" + mainjsonObject;
return Response.status(200).entity(flag).build();
}
my Client:
String encodedBase64=jsonob.optString("pdf bytearray");
byte[] decodedBytes = Base64.decodeBase64(encodedBase64);
System.out.println("decbyte "+decodedBytes);
File someFile = new File("C:/Users/acer/Desktop/test.pdf");
OutputStream fos = new FileOutputStream(someFile);
fos.write(decodedBytes);
fos.flush();
fos.close();
Related
Generating pdf with base64 String which generated through jasper report,I can make password protected in jrxml as well but i have different requirement so i can't keep there.
I want to make protected pdf while sending attachment only so i tried many possibilities like (pdf writer,streamer and all) but nothing worked.
Below code i used to generate pdf as attachment , i want to make that attachment as password protected.*
MimeMessage message = mailSenderImpl.createMimeMessage();
MimeMessageHelper helper;
helper = new MimeMessageHelper(message, true);
helper.setFrom(CacheUtils.getConfig(ApplicationConstant.
DEFAULT_FROM_EMAIL));
helper.setTo(request.getToEmail());
helper.setSubject(request.getSendSubject());
helper.setText("", request.getSendMessage());
String sendAttachment = request.getSendAttachment();
JSONObject jsonRec = new JSONObject(sendAttachment);
JSONArray jArray = jsonRec.getJSONArray("Attachment");
DataSource dataSource;
String sAttachName;
String sAttachBase64;
JSONObject jsonRec = new JSONObject(sendAttachment);
JSONArray jArray = jsonRec.getJSONArray("Attachment");
DataSource dataSource;
String sAttachName;
String sAttachBase64;
sAttachName = jArray.getJSONObject(i).has("AttachName") ?jArray.getJSONObject(i).getString("AttachName") : null;
sAttachBase64 = jArray.getJSONObject(i).has("AttachBase64") ? jArray.getJSONObject(i).getString("AttachBase64") : null;
dataSource = sAttachBase64 !=null ? new
ByteArrayDataSource(Base64.getDecoder().decode(sAttachBase64.getBytes()), "application/pdf") : null;
helper.addAttachment(sAttachName, dataSource);
The pdf writer class in the java is able to make encrypted pdf files. You can create with it. PDF Writer class provides encrypt with username, password and also encryption type, permission etc... You can find more detail on there: PDF Writer Class
byteStream = Base64.getDecoder().decode(sAttachBase64);
inputStream = new ByteArrayInputStream(byteStream);
byte[] buffer = new byte[1024];
baos = new ByteArrayOutputStream();
int bytesRead;
while ((bytesRead = inputStream.read(buffer)) != -1) {
baos.write(buffer, 0, bytesRead);
}
reader = new PdfReader(byteStream);
stamper = new PdfStamper(reader, baos);
stamper.setEncryption("test".getBytes(), "test".getBytes(),PdfWriter.ALLOW_PRINTING, PdfWriter.ENCRYPTION_AES_128 | PdfWriter.DO_NOT_ENCRYPT_METADATA);
stamper.close();
dataSource = new ByteArrayDataSource(baos.toByteArray(), "application/pdf");
I'm using Base91 to store an image as a String in a mysql database. When I retrieve the string to convert it back to an image, the string seems to have been corrupted by the database.
I'm sure it's being corrupted in the database because I did an isolated test on a single device of taking a picture, converting it to a Base91 byte[], converting the byte[] to a string (using Latin1), converting the string back to byte[], then to an image, and it worked. When I try that with a server in the middle, the images end up broken.
I've tried changing the collation on the specific column on the database from utf8 to ascii to latin1, no luck.
Code:
Encoding Picture:
File file1 = new File(path);
FileInputStream in = new FileInputStream(file1);
byte[] imagesBytes = new byte[(int) file1.length()];
in.read(imagesBytes, 0, (int) file1.length());
_picture = new String(Base91.encode(imagesBytes), Base91.CHARSET);
//appointment.addPicture(new String(Base91.encode(imagesBytes), Base91.CHARSET));
Storing encoded image:
JsonObject jsonx = new JsonObject();
jsonx.addProperty("picture", request.getParameter("picture"));
db.insert("AppointmentPicture",
"(AppointmentID, picture)values(?,?)",
new Object[]{appointment.getDbID(), jsonx.toString()},
false);
Retrieving the image:
ResultSet rSet = db.query("AppointmentPicture", new String[]{"picture"}, "AppointmentID = ?", new Object[]{appointmentID});
System.out.println("pictures grabbed");
JsonObject json = new JsonObject();
int counter = 0;
while (rSet.next()) {
counter++;
json.addProperty(String.valueOf(counter), rSet.getString("picture"));
}
json.addProperty("count", String.valueOf(counter));
response.getWriter().write(json.toString());
System.out.println("pictures returned");
Decoding Image:
String serverResponse = in.readLine();
JSONObject json = new JSONObject(serverResponse);
int count = Integer.parseInt(json.getString("count"));
for(int i = 0; i < count; i++){
JSONObject j = new JSONObject(json.getString(String.valueOf(i + 1)));
byte[] picBytes = j.getString("picture").getBytes(Base91.CHARSET);
File file = new File(imageDirectory, String.valueOf(System.currentTimeMillis()) + ".jpeg");
BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(file));
out.write(picBytes, 0, picBytes.length);
}
I want to put multiple images in JSON object using byte stream format, i wrote the following code.
FileInputStream fin = new FileInputStream(pathToImages+"//"+"01.jpg");
BufferedInputStream bin = new BufferedInputStream(fin);
BufferedOutputStream bout = new BufferedOutputStream(out);
int ch =0; ;
sun.misc.BASE64Encoder encoder= new sun.misc.BASE64Encoder();
byte[] contents = new byte[5000000];
int bytesRead = 0;
String strFileContents;
while ((bytesRead = bin.read(contents)) != -1) {
bout.write(encoder.encode(contents).getBytes());
}
JsonObject myObj = new JsonObject();
I want to put encoded byte stream in myObj,but dont know how to do it.
Thanks
JSONObject myObj = new JSONObject();
myObj.put("1",encoder.encode(contents).getBytes());
I think this will work.
Assuming you are using Java 8, and the javax.json package:
Path path = Paths.get(pathToImages, "01.jpg");
ByteArrayOutputStream bytes = new ByteArrayOutputStream(
(int) (Files.size(path) * 4 / 3 + 4));
try (OutputStream base64Stream = Base64.getEncoder().wrap(bytes)) {
Files.copy(path, base64Stream);
}
String base64 = bytes.toString("US-ASCII");
JsonObjectBuilder builder = Json.createObjectBuilder();
builder.add("data", base64);
JsonObject myObj = builder.build();
I am getting zipped blob from db and using that blob in below way,
Ex:-
byte[] inputBlob = blobfile.getBytes(1, (int) blobfile.length());
After getting the blob, the way i got the zippedStream and passed it into another Class method(unzipper).
Ex:-
ByteArrayOutputStream zippedStream = null;
InputStream byteInputStream = null;
IParser parser = null;
byte[] buffer = null;
try {
zippedStream = new ByteArrayOutputStream();
byteInputStream = new ByteArrayInputStream(blob);
blob = null;
int bytes_read;
buffer = new byte[byteInputStream.available()];
while ((bytes_read = byteInputStream.read(buffer)) > 0) {
zippedStream.write(buffer, 0, bytes_read);
}
buffer = null;
byteInputStream.close();
byteInputStream = null;
}catch(Exception e){
e.printStackTrace();
}
unzipper method:
Ex:-
byte[] buffer = new byte[1024];
try {
InputStream decodedInput = new ByteArrayInputStream(zippedStream.toByteArray());
zippedStream.close();
zippedStream = null;
GZIPInputStream unzippedStream = new GZIPInputStream(decodedInput);
decodedInput.close();
decodedInput = null;
int bytes_read;
unzippedOutputstream = new ByteArrayOutputStream();
while ((bytes_read = unzippedStream.read(buffer)) > 0) {
unzippedOutputstream.write(buffer, 0, bytes_read);
}
buffer = null;
unzippedStream.close();
unzippedStream = null;
} catch (Exception ex) {
logger.setException(ex);
logger.error("unzipper", generateMsg("Exception occurred"));
}
Using this way my application got stucked some time, and performance was so bad.
Is there any optimize way to get the zippedstream file and unzipping that easily?
Is all this buffering really needed. Can you IParser parse a Stream?
InputStream zippedStream = ...
IParser parser = ...
parser.parse(new GZIPInputStream(zippedStream));
This will read compressed data, uncompressing as it goes which is much more efficient.
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();
}
}