Reputation: 131
I have a controller that creates many images from pdf(pdfBox).I save all picture to List . And I need to send one picture per view when I press the button. or enter value
public class Pdf{
public byte[] PDFCREATE(){
byte[] pdf = ...;
//Code for creating pdf using Itext
return pdf;
}
}
public List<byte[]> getImage(byte[] pdf) throws Exception{
ByteArrayOutputStream baos = new ByteArrayOutputStream();
List<byte> listImg = new List()<>;
try (final PDDocument document = PDDocument.load(file)){
PDFRenderer pdfRenderer = new PDFRenderer(document);
for (int page = 0; page < document.getNumberOfPages(); ++page)
{
BufferedImage bim = pdfRenderer.renderImage(page)
ImageIO.write(bim, "png",baos);
listImg.add(baos)
}
document.close();
} catch (IOException e){
System.err.println("Exception while trying to create pdf document - " + e);
}
return baos.toByteArray();
With view i post:
public ResponseEntity<?> CreateFont(int pictureNumber ) {
PDF pdf= new PDF();
PdfToImg pdfToImg = new PdfToImg();
List<byte []> fileBytes = pdfToImg.getImage(pdf.PDFCREATE());
byte[] encoded= Base64.encodeBase64(fileBytes.get(pictureNumber ));
String encodedString = new String(encoded);
return new ResponseEntity<String>(
"<img src='data:image/jpeg;base64," + encodedString + "' alt='' width='420' height='580'>",
HttpStatus.OK);
But here I have to create pdf each time. Is it possible to just save the values from getImage to the List?.And when the user enters value (pictureNumber) or press button each time not to create new pdf.And Instead of this take values from the List.And create new List after refresh the pageI need to store somewhere List fileBytes,but where?
Sorry for my English
Upvotes: 2
Views: 121
Reputation: 4643
This might helps you:
private static Map<Integer, String> pictureMap = new HashMap<>();
private static PDF pdf;
public ResponseEntity<?> CreateFont(int pictureNumber) {
if(pictureMap.containsKey(pictureNumber))
return response(pictureMap.get(pictureNumber));
if(pdf == null)
pdf = new PDF();
PdfToImg pdfToImg = new PdfToImg();
List<byte[]> fileBytes = pdfToImg.getImage(pdf.PDFCREATE());
byte[] encoded = Base64.encodeBase64(fileBytes.get(pictureNumber));
String encodedString = new String(encoded);
pictureMap.put(pictureNumber, encodedString);
return response(encodedString);
}
private ResponseEntity response(String encodedString){
return new ResponseEntity<String>(
"<img src='data:image/jpeg;base64," + encodedString + "' alt='' width='420' height='580'>",
HttpStatus.OK);
}
Upvotes: 3