Q:

HtmlUnit: saving pdf link

How do I download a pdfLink from a website using HtmlUnit?
The default return from HtmlClient.getPage() is an HtmlPage. This does not handle pdf Files.

A:

The answer is that HtmlClient.getPage will return an UnexpectedPage if the response was not  an html file. THen you can get the pdf as an inputstream and save.
private void grabPdf(String urlNow)
{
    OutputStream outStream =null;
    InputStream is = null;
    try
    {
        if(urlNow.endsWith(".pdf"))
        {
            final WebClient webClient = new WebClient(BrowserVersion.FIREFOX_45);
            try
            {
                setWebClientOptions(webClient);
                final UnexpectedPage pdfPage = webClient.getPage(urlNow);
                is = pdfPage.getWebResponse().getContentAsStream();

                String fileName = "myfilename";
                fileName = fileName.replaceAll("[^A-Za-z0-9]", "");

                File targetFile = new File(outputPath + File.separator + fileName  + ".pdf");
                outStream = new FileOutputStream(targetFile);
                byte[] buffer = new byte[8 * 1024];
                int bytesRead;
                while ((bytesRead = is.read(buffer)) != -1)
                {
                    outStream.write(buffer, 0, bytesRead);
                }

            }
            catch (Exception e)
            {
                NioLog.getLogger().error(e.getMessage(), e);
            }
            finally
            {
                webClient.close();
                if(null!=is)
                {
                    is.close();
                }
                if(null!=outStream)
                {
                    outStream.close();
                }
            }
        }
    }
    catch (Exception e)
    {
        NioLog.getLogger().error(e.getMessage(), e);
    }

}

Sidenote. I didn't use try with resources because the outputstream can only be initialized within the try block. I could break into two methods but that would be cognitively slower for the programmer to read.

