We are getting Base 64 encoded graphic image as webservice response and we have to convert it to PDF file. We used bellow code snippet to transfrom base 64 encoded graphic image to pdf doc.
// First decode the Base 64 encoded graphic image
BASE64Decoder decoder = new BASE64Decoder();
byte[] decodedBytes = decoder.decodeBuffer(s);
// Create the pdf file
File file = new File("output.png");
FileOutputStream fop = new FileOutputStream(file);
fop.write(decodedBytes);
fop.flush();
fop.close();
But when we open the pdf file we are getting bellow error.
Adobe Reader could not open "output.pdf" because it is either not a supported file type or because the file has been damaged.
We tried the PDF box as bellow,
BASE64Decoder decoder = new BASE64Decoder();
byte[] decodedBytes = decoder.decodeBuffer(s);
ImageToPDF imageToPdf = new ImageToPDF();
imageToPdf.createPDFFromImage("output.pdf", decodedBytes.toString());
This also didnt help us. Please suggest me a way to creat the pdf file from Base 64 encoded graphic image.
I thing you are missing a step here. Please try following
First, create the image from the Base64 data as follows (Taken from here)
String base64String =
"BORw0KGgoAAAANSUhEUgAAAUAAAAHgCAYAAADUjLREAAAgAElEQVR4AexdB4BU1dX+ZmZ7ZWGX3pHeu6goitgQDCZGjdHYu4nGqL81mmaJvdd";
BASE64Decoder decoder = new BASE64Decoder();
byte[] decodedBytes = decoder.decodeBuffer(base64String);
log.debug("Decoded upload data : " + decodedBytes.length);
String uploadFile = "/tmp/test.png";
log.debug("File save path : " + uploadFile);
BufferedImage image = ImageIO.read(new ByteArrayInputStream(decodedBytes));
if (image == null) {
log.error("Buffered Image is null");
}
File f = new File(uploadFile);
// write the image
ImageIO.write(image, "png", f);
Please note that this example uses sun.misc.BASE64Decoder, but I would advice not to use this but use some other open source decoder (e.g apache commend-codec library is good and widely used.).
Once you have the image file, use ImageToPDF to convert the same to PDF file.
Related
I am trying to convert HTML to PDF as encoded string. I am using openhtmltopdf library. I don't want to create a new file in users environment, so I am using ByteArrayOutputStream.
Following is my code:
Document document = Jsoup.parse(html, "UTF-8");
document.outputSettings().syntax(Document.OutputSettings.Syntax.xml);
document.outputSettings().prettyPrint(false);
// File outputpdf = new File("output.pdf");
try (ByteArrayOutputStream os = new ByteArrayOutputStream()) {
PdfRendererBuilder pdfRendererBuilder = new PdfRendererBuilder();
pdfRendererBuilder.toStream(os);
pdfRendererBuilder.withW3cDocument(new W3CDom().fromJsoup(document), "/");
pdfRendererBuilder.run();
// os.writeTo(new FileOutputStream(outputpdf));
byte[] encoded = java.util.Base64.getEncoder().encode(os.toString().getBytes());
String encodedString = new String(encoded);
I used an online base64 string to PDF decoder and generated PDF while testing. My PDF is coming as empty. When I replaced the ByteArrayOutputStream with FileOutputStream(<fileName>). It is creating a proper PDF file and also when I decode the string it is coming correct.
What am I missing in ByteArrayOutputStream?
I am looking to convert an image to text which I intend to convert back to the image. I have looked into Base64 specified in the link here. But the problem that I encounter is that Eclipse freezes every time I try to convert. In this case, the conversion of the text back to the image is where Eclipse seems to freeze. The code in Eclipse is shown below. Is it somewhere wrong? Or is there any other way to convert images to text and back to images?
try
{
File file3=new File(sfile2.toString());
// Reading a Image file from file system
FileInputStream imageInFile = new FileInputStream(file3);
byte imageData[] = new byte[(int) file3.length()];
imageInFile.read(imageData);
// Converting Image byte array into Base64 String
String imageDataString = encodeImage(imageData);
System.out.println(imageDataString);
// Converting a Base64 String into Image byte array
byte[] imageByteArray = decodeImage(imageDataString);
// Write a image byte array into file system
FileOutputStream imageOutFile = new FileOutputStream(
"water-drop-after-convert.jpg");
imageOutFile.write(imageByteArray);
imageInFile.close();
imageOutFile.close();
System.out.println("Image Successfully Manipulated!");
}
catch (Exception e3)
{
}
}
});
I need to encode/decode pdf file into Base64 format.
So I read file from disk into String(because I will receive file in String Base64 format in future);
String pdfString = IOUtils.toString(new FileInputStream(new
File("D:\\vrpStamped.pdf")));
byte[] encoded = Base64.encodeBase64(pdfString.getBytes());
byte[] newPdfArray = Base64.decodeBase64(encoded);
FileOutputStream imageOutFile = new FileOutputStream(
"D:\\1.pdf");
imageOutFile.write(newPdfArray);
imageOutFile.close();
imageOutFile.flush();
So my D:\\1.pdf doesnt opens in AdobeReader, but if I read file straight to byte array, using IOUtils.toByteArray(..) instead ,all works fine and my D:\\1.pdf file sucessfuly opens in Adobe Reader:
byte[] encoded = Base64.encodeBase64(IOUtils.toByteArray(new FileInputStream(new File("D:\\vrpStamped.pdf"))););
It seems to me thath IOUtils.toString(..) change something inside file content. So how can I convert file to String with not content breaking?
How to encode a pdf...
byte[] bytes = IOUtils.toByteArray(new FileInputStream(new File("/home/fschaetz/test.pdf")));
byte[] encoded = Base64.encode(bytes);
String str = new String(encoded);
...now do something with this encoded String, for example, send it via a Rest service.
And now, if you receive an encoded String, you can decode and save it like this...
byte[] decoded = Base64.decode(str.getBytes());
FileOutputStream output = new FileOutputStream(new File("/home/fschaetz/result.pdf"));
output.write(decoded);
output.close();
Works perfectly fine with all files, not limited to images or pdfs.
What your example is doing is...
Read the pdf into a String (which pretty much destroys the data, since you are reading binary data into a String)
Encode this spring (which is in all likelyhood not a valid representation of the original pdf anymore)
Decode it and save it to disk
how to convert gif to base64?
here's what i try so far
public static String convertImageToBase64(String urlString, String type ){
String imageString = null;
ByteArrayOutputStream bos = new ByteArrayOutputStream();
try {
URL url = new URL(urlString);
BufferedImage img = ImageIO.read( url );
ImageIO.write(img, type, bos);
byte[] imageBytes = bos.toByteArray();
BASE64Encoder encoder = new BASE64Encoder();
imageString = encoder.encode(imageBytes);
bos.close();
} catch (IOException e) {
e.printStackTrace();
}
return imageString;
}
code above is working, but it lost the animation
Most likely the class BufferedImage does not support images with animation. So the code opens and parses the image only to the first frame.
Instead try directly getting the bytes with URL.openStream and then just convert the downloaded bytes to base64.
Notice that this way you can't be sure that the downloaded file is actually an image since you are not opening it at all. This may or may not be needed.
You have to use
public String encodeToString(byte[] src)
of class BASE64.Encoder (from java 8)
I'm assuming what you want is a Base64 representation of the GIF file itself, not the ImageIO representation. If you have an older version of Java without built-in Base64 support, Apache Commons Codec will do the job. Read the file into a byte array using URL.openStream(), not with ImageIO, then call Base64.encodeBase64String. If you want the result URL encoded, call Base64.encodeBase64URLSafe instead.
If you actually want the ImageIO representation, then you're stuck with losing the animation.
I am trying to get encoded byte of image into base64 format and sending to rest webservice. Inside the service i want to decode it and convert it back to image and want to save the image in my local path. Its fails during decoding. I dont know whether the logic is correct. Need some guidance
#POST
#Path("/imageupload")
#Produces("text/html")
#Consumes(MediaType.MULTIPART_FORM_DATA)
public String execute(#FormDataParam("image") String inputfile) throws Exception
{
System.out.println("entered into service");
BASE64Decoder decoder = new BASE64Decoder();
ByteBuffer img=decoder.decodeBufferToByteBuffer(inputfile);
System.out.println();
File outputfile = new File("D:\\TEST\\test.png");
ImageIO.write(img, "png", outputfile);
The logic is:
Step 1: get the byte array as string inside the service.
Step 2: decode it
Step 3: write the byte into file with png format
Provided you get correctly encoded image and you are sure it is png, I would do it this way.
BASE64Decoder decoder = new BASE64Decoder();
byte[] decodedImageBytes = decoder.decodeBuffer(inputfile);
final FileOutputStream out = new FileOutputStream(new File("D:\\TEST\\test.png"));
out.write(decodedImageBytes);
out.close();
P.S. Make sure you receive the image as encoded string.