简体   繁体   中英

How to access the PDF file having blob protocol, java.net.MalformedURLException: unknown protocol: blob how to resolve in selenium java?

How to access the PDF file having blob protocol, java.net.MalformedURLException: unknown protocol: blob how to resolve in selenium java?

I have found the solution to the question of How to access the PDF file having blob protocol, java.net.MalformedURLException: unknown protocol: blob how to resolve in selenium java?

  1. First convert the PDF on blob link into base64 using this code:
  private String getBytesBase64FromBlobURI(ChromeDriver driver, String uri) {
        String script = " "
                + "var uri = arguments[0];"
                + "var callback = arguments[1];"
                + "var toBase64 = function(buffer){for(var r,n=new Uint8Array(buffer),t=n.length,a=new Uint8Array(4*Math.ceil(t/3)),i=new Uint8Array(64),o=0,c=0;64>c;++c)i[c]='ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'.charCodeAt(c);for(c=0;t-t%3>c;c+=3,o+=4)r=n[c]<<16|n[c+1]<<8|n[c+2],a[o]=i[r>>18],a[o+1]=i[r>>12&63],a[o+2]=i[r>>6&63],a[o+3]=i[63&r];return t%3===1?(r=n[t-1],a[o]=i[r>>2],a[o+1]=i[r<<4&63],a[o+2]=61,a[o+3]=61):t%3===2&&(r=(n[t-2]<<8)+n[t-1],a[o]=i[r>>10],a[o+1]=i[r>>4&63],a[o+2]=i[r<<2&63],a[o+3]=61),new TextDecoder('ascii').decode(a)};"
                + "var xhr = new XMLHttpRequest();"
                + "xhr.responseType = 'arraybuffer';"
                + "xhr.onload = function(){ callback(toBase64(xhr.response)) };"
                + "xhr.onerror = function(){ callback(xhr.status) };"
                + "xhr.open('GET','"+ uri +"');"
                + "xhr.send();";
        String result = (String) driver.executeAsyncScript(script, uri);
        return result;
    }
  1. The Second step now converts the base64 into a pdf file
public void savePDF(String path, String x){
File file = new File(path);//"D:\\dealer-portal-v2-automation\\test.pdf");

        //Converting base64 to PDF
        try (FileOutputStream fos = new FileOutputStream(file); ) {
            // To be short I use a corrupted PDF string, so make sure to use a valid one if you want to preview the PDF file
            byte[] decoder = Base64.getDecoder().decode(x);
            fos.write(decoder);
            System.out.println("PDF File Saved");
        } catch (Exception e) {
            e.printStackTrace();
        }
}
  1. Now main class
public void main(Strings[] args) {
//here pass your driver and the url 
        String x = getBytesBase64FromBlobURI((ChromeDriver) driver,url);
//here convert your base64 to file and sendt base64 string and the path where you want to //store your PDF
        savePDF(path, x);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM