Display PDF file from disk

Hello,

I have a PDF file on my disk and I want to display it. But the following code doesn’t work :


     File f = new File("C:/Test/test.pdf");
     System.out.println(f.exists()); // Displays "true"
     URL url = f.toURI().toURL();
     ExternalResource r = new ExternalResource(url);
     Embedded e = new Embedded(null, r);
     e.setType(Embedded.TYPE_BROWSER);
     
     mainLayout.addComponent(e);
     setContent(mainLayout);

Hi Kevin !

You’re putting a physical path to the file while this should be an url. Do not forget this is a client-server application :wink:
Put your PDF files into your webapp area somewhere and construct a full or relative url to it. If your goal is to stream arbitrary located pdf file to the client, then consider using a StreamResource, so you can open a stream to any fila at the server and stream it’s contents to the client.

Hi Dimitri,

Actually, I have a directory which contains generated PDF files and which has no link with my webapp. This directory is located on my server.
My aim is to display to my webapp client one of the PDF file. So how can I get a file located on my server ?

So in this case you can try using
StreamResource
instead of ExternalResource

Would you have an example of this please ?

This code doesn’t work :


						StreamSource s = new StreamResource.StreamSource()
						{
							@Override
							public InputStream getStream()
							{
								try
								{
									File f = new File("C:/Test/test.pdf");
									FileInputStream fis = new FileInputStream(f);
									return fis;
								}
								catch (Exception e) { e.printStackTrace(); return null; }
							}
						};
						
						StreamResource r = new StreamResource(s, "", getMain());
						Embedded e = new Embedded();
						e.setType(Embedded.TYPE_BROWSER);
						e.setMimeType("application/pdf");
						e.setSource(r);
						e.setWidth("200px");
						e.setHeight("200px");
	
				       		mainLayout.removeAllComponents();
						mainLayout.addComponent(e);
						setContent(mainLayout);

Sorry, actually it works well.
Thanks a lot Dimitri for your time :wink: