Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert BufferedReader to File

Tags:

java

I have a servlet which returns a PDF document to the requesting user. When it is called from a browser, the PDF document is automatically downloaded. Now I need to call this servlet from Java (standalone code, not server side). Once this Java code gets the PDF document, it needs to convert it to images using Apache PDF Box API.

This is how my Java code looks like. It writes bytes to the screen.

URL url = new URL("http://localhost:8080/Stream/Document&type=pdf");
BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream())); 
String line = in.readLine();
System.out.println( line ); 
in.close();

and this is how the code to convert it to Images looks like

String pdfFileName = "myfile.pdf";
PDDocument document = PDDocument.load(new File(pdfFileName)); 

Now I need to combine these two so that the PDF file that is downloaded (in memory, would prefer not to write it to Filesystem) is converted to JPG. So, instead of passing a hardcoded filename, I somehow need to convert the BufferedReader object to File object and pass it as an input to PDDocument.

I am not able to make out how this conversion would happen.

like image 941
swati Avatar asked Mar 24 '26 19:03

swati


1 Answers

From the docs, PDDocument can also load from a byte array or InputStream.

Thus, simply use the input stream from your url and pass that to PDDocument.load(InputStream).

like image 179
Martin Nyolt Avatar answered Mar 27 '26 10:03

Martin Nyolt



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!