In a long-term CefSharp / Chromium project we had been working upon, a client requested if we can always open PDF files for previewing after they have been downloaded. They specifically mentioned Chrome does the same.
So I did some testing and observed that:
- You obviously need a
DownloadHandler
on yourChromiumWebBrowser
instance for downloads to work. Here’s a default DownloadHandler which should work for most use-cases. - When an attachment / file is sent by a server, it can send a
Content-Disposition
header.- If this header is omitted, or its value is set to
inline
, a browser is allowed to open the file directly in preview mode if the Browser supports the file’s format (images / pdf etc). - However if the value of this header is set to
attachment
, the browser is always supposed to download the file and not open it for previewing automatically.
- If this header is omitted, or its value is set to
In my testing, Chrome on my machine was depicting the same behaviour. As was our Chromium-based application. Chromium has in-built support for pdf previews and for Content-Disposition: inline
, it would automatically open the file for previewing.
However for Content-Disposition: attachment
, both Chrome and our application were downloading the file to user’s Downloads folder which is the expected behaviour.
However the client claimed on their machine, Chrome was opening the file for previewing even when Content-Disposition
was set to attachment
. We did not check whether they had some Chrome setting or extension for this behaviour. But we set out to implement this ourselves. And it was not too difficult.
All we had to do was the launch the file if it was a pdf once the download completed. The following code in OnDownloadUpdated
of our DownloadHandler
did the trick:
public void OnDownloadUpdated (IWebBrowser chromiumWebBrowser, IBrowser browser, DownloadItem downloadItem, IDownloadItemCallback callback)
{
OnDownloadUpdatedFired?.Invoke(this, downloadItem);
if (downloadItem.IsComplete && downloadItem.FullPath.ToLower().EndsWith(".pdf"))
{
System.Diagnostics.Process.Start(downloadItem.FullPath);
}
}
Basically we check for download to have completed and then if the file extension is pdf, just launch the downloaded file which would open it in System’s default PDF application for previewing.
You can easily tweak it to open the pdf file in your own application or for any other behaviour if you so desire!
Recent Comments