In my application a pdf report only opens in print preview which allows user to directly print the pdf document. Now i want to automate this to verify the pdf content.
I have got the pdf content through an api which is in base64 [did split to get only data], i tried converting to byte array after decoding but it only prints junk characters.[byte array to string]
Now i have converted this data into ByteBuffer and want this to write in pdf.
ByteBuffer decodedBytes = new BASE64Decoder().decodeBufferToByteBuffer(
new String(base64split2[1].substring(0, base64split2[1].length() - 1))
);
Can someone tell me how do i convert this decodedBytes of ByteBuffer to pdf.
Thanks
byte[] decodedBytes = new BASE64Decoder().decodeBuffer(str);
InputStream targetStream = new ByteArrayInputStream(decodedBytes);
PDDocument document = PDDocument.load(targetStream);
document.save("C:/test.pdf");
FileUtils.writeByteArrayToFile(new File("C:/test.pdf"), decodedBytes);
Using above code to convert to pdf.
Getting blob data of pdf from API :
Future<dynamic> getBlobdata(int pdfId) async {
try {
var response = await Dio().get(
"https://www.google.com/pdf/$pdfId",
options: Options(
responseType: ResponseType.bytes,
contentType: 'application/octet-stream',
),
);
var data = {"data": response.data.buffer};
return data;
} on DioError catch (error) {
var data = error.response.data;
return data;
}
}
Define file name and directory to save file :
String fileName = "pdf$pdfId";
final dir = await getExternalStorageDirectory();
var pdfBlob = await getBlobdata(1); // have to be in a asyn func to use await
Save Pdf :
final file = File("${dir.path}/$fileName.pdf");
await file.writeAsBytes(pdfBlob.asUint8List());
View Pdf in app :
await OpenFile.open("${dir.path}/$fileName.pdf");
Related
I am using base64 string image to send through the ajax call,and recieving it in spring controller as below,
function saveImages(e){
alert("inside save images "+e);
var x = $('#image'+e).prop('src');
$.ajax({
type : "POST",
contentType : 'text/plain',
url : "saveUserImage",
data : 'imagecode=' + x ,
dataType : 'json',
success : function(data) {
alert("success");
},
error: function (resp) {
window.location.reload();
}
});
}
In above ajax call x is the base64 image data,
#RequestMapping(value="/saveUserImage", method = RequestMethod.POST)
public void saveImage(ModelMap model, Principal principal,HttpSession session,#RequestBody String imageString) throws UnsupportedEncodingException {
String imagedata=imageString.replace("imagecode=", "");
//here I am decoding imageString to bytes
byte[] decodedBytes = Base64.decodeBase64(imagedata);
UserImages image=new UserImages();
//here I am saving to my UserImages pojo
image.setFiledata(decodedBytes);
image.setUSER_ID(Integer.parseInt(userid));
//database call to save image
service.saveImage(image);
}
In the above controller code I have decoded string to bytes and I am saving it to database.
while I am retrieving that image to show the image,I am encoding back to base64 string
List<UserImages> list=service.viewImages(profile);
Iterator it=list.listIterator();
while(it.hasNext()) {
UserImages images=(UserImages) it.next();
ImagesTest image=new ImagesTest();//another pojo to set base64 string & to show in frontend
image.setUploadid(images.getUploadid());
//here encoding the decoded bytes to base64 string ,which I have stored in database
byte[] encodeBase64 = Base64.encodeBase64(images.getFiledata());
String base64Encoded = new String(encodeBase64, "UTF-8");
image.setBase64String(base64Encoded);
newList.add(image);
}
model.addAttribute("imagespojo", newList);
I am getting different base64 string ,and I am unable to see the image.Because of that I am making changes to base64Encoded as,
base64Encoded.replace("dataimage", "data:image").replace("base64", ";base64,")
Now it is working for jpeg images,when I try to save png image,again the image is not visible.
How could download a file using Angular2 and Java?
There is a GET HTTP call which returns the file data:
If receive a byte[] array, the file (in this case ODT, but could be
other format) opens as a document with the literal byte content
written in it: "UEsDBBQAAAgAAPBZjklexjIMJwAAACcAAAA"
If receive a blob object , it shows
"{"binaryStream":{},"wrappedBlob":{"binaryStream":{}}}" in the
document
Angular2 code:
goFile() {
//This service calls #angular/http for a GET request and returs the response
//ends up doing:
// this.http.get(url, {responseType: ResponseContentType.Blob})
// .map(res => res.blob())
this.myService.subscribe(result=> { this.saveFile(result); });
return false;
}
downloadFile(file: any) {
var blob = new Blob([file], {type: 'application/vnd.oasis.opendocument.text'});
var url= window.URL.createObjectURL(blob);
window.open(url);
}
Java code just reads the file and returns a blob or byte array (in each case tried):
byte[] file = FileUtils.getFile("E:/file.odt");
return file;
byte[] file = FileUtils.getFile("E:/file.odt");
Blob blob = Hibernate.createBlob(fichero);
return blob;
UPDATE
I believe the problem comes that data is being received as a json object, something setup in the system i am working.
Have tried intead to return byte[] from java and try to convert to a blob in Angular2 (for a txt file):
//file is returned by a call to http.get which has a map:
// .map(res => res.text())
var blob = new Blob([file], {type: 'text/plain'});
var objectUrl = URL.createObjectURL(blob);
window.open(objectUrl);
but returns a page with the byte content ("YWJj"), obviously the content received is not converted to a proper blob object.
Also tried with same result:
var byteArray = new Uint8Array(file);
var blob = new Blob([byteArray], {type: 'text/plain'});
there is not solution for different mime types without using additional plugins?
Hi I want to display server side image dynamically in browser using ajax.
but images is not coming.
i have checked the server code in debugging mode its working fine but not sure about client code.
readyState coming as 4 but image is not getting displayed.
Server code :
File f = new File("D:\\mapping events\\Camping\\"+(String) request.getParameter("imageName")+"\\"+"01.jpg");
DataInputStream dis = new DataInputStream(new FileInputStream(f));
byte[] barray = new byte[(int) f.length()];
try
{
dis.readFully(barray); // now the array contains the image
}
catch (Exception e)
{
barray = null;
}
finally
{
dis.close( );
}
sos.write(barray); // send the byte array to client
System.out.println(barray);
sos.close();
Ajax code :
$.ajax({
url: 'GetCampingImages',
type: 'POST',
data:{
imageName:allData[0]
},
cache: true,
dataType: 'json',
success: function(jqXHR)
{
if(jqXHR)
{
if (jqXHR.readyState == 4) {
$('#dynamicCamping01').html('<img src="data:image/jpeg;'+jqXHR.reresponseText+'"/> ');
$('#dynamicCampingDesc01').html("<h3>"+allData[0]+"</h3>");
}
}
else
{
alert("Something went wrong while retriving events");
}
},
error: function(jqXHR)
{
console.log('ERRORS in server: ' );
}
You should encode the binary data using base64, and use the scheme: "data:image/jpeg;base64,...". Directly sending data bytes is not a good idea for jpeg files.
I'm retrieving a PDF file from a web server java, returning a byte array.
Need save the PDF on the local machine using C #, but the file is saved completely in blank, I think it is because of the byte array format is different.
Here is my code:
StreamReader responseReader = new StreamReader(webStream);
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(URL);
request.Method = "GET";
request.ContentType = "application/pdf";
WebResponse webResponse = request.GetResponse();
Stream webStream = webResponse.GetResponseStream();
StreamReader responseReader = new StreamReader(webStream);
string response = responseReader.ReadToEnd();
responseReader.Close();
byte[] docByte = Encoding.ASCII.GetBytes(response);
File.WriteAllBytes(#"C:\file.pdf", docByte);
Any suggestions on how to save the PDF file normally?
Thank you for listening
// ...
Stream webStream = webResponse.GetResponseStream();
using (var stream = File.Create(#"C:\file.pdf"))
{
webStream.CopyTo(stream);
}
Why don't you do it simply with WebClient like this?
using System.Net;
using (WebClient webClient = new WebClient())
{
webClient.DownloadFile(URL, #"C:\file.pdf");
}
I am sending an image after base64 encoding from my JSP to a servlet using AJAX. At the servlet side, I am trying to decode and save it to either a file or render to a browser.
I am getting an empty image. Here is my servlet side code
String imageStr = request.getParameter("image");
byte[] decoded = Base64.decodeBase64(imageStr);
String path = "D:\\myImage.png";
try {
OutputStream out1 = new BufferedOutputStream(new FileOutputStream(path));
out1.write(decoded);
} finally {
}
I get a the image, but its empty.
Try closing the stream, it should flush all buffered data:
String imageStr = request.getParameter("image");
byte[] decoded = Base64.decodeBase64(imageStr);
String path = "D:\\myImage.png";
OutputStream out1 = null;
try {
out1 = new BufferedOutputStream(new FileOutputStream(path));
out1.write(decoded);
} finally {
if (out1 != null) {
*out1.close();*
}
}
And make sure the decoded array really contains some data.