How to read the pdf file using selenium

你。 提交于 2021-01-28 19:22:19

问题


I am working on web page over which there is a link, clicking on which it opens a pdf file on new window. I have to read that pdf file to validate some data against the transactions done. One way is to download that file and then use it. Can any one help me out on this. I have to work on IE 11

Thanks in Advance.


回答1:


Use PDFBox and FontBox.

    public String readPDFInURL() throws EmptyFileException, IOException {
        WebDriver driver = new FirefoxDriver();
        // page with example pdf document
        driver.get("file:///C:/Users/admin/Downloads/dotnet_TheRaceforEmpires.pdf");
        URL url = new URL(driver.getCurrentUrl());
        InputStream is = url.openStream();
        BufferedInputStream fileToParse = new BufferedInputStream(is);
        PDDocument document = null;
        try {
            document = PDDocument.load(fileToParse);
            String output = new PDFTextStripper().getText(document);
        } finally {
            if (document != null) {
                document.close();
            }
            fileToParse.close();
            is.close();
        }
        return output;
    }

Since some of the functions from the older versions of PDFBox have been deprecated, we need to use another FontBox along with PDFBox. I have used PDFBox (2.0.3) and FontBox (2.0.3) and it is working fine. It won't read images though.




回答2:


First Downlaod pdfbox jar.

strURL is a web URl which contains .pdf file: like(https://example.com/downloads/presence/Online-Presence-CA-05-02-2017-04-13.pdf)

public boolean verifyPDFContent(String strURL, String text) {

        String output ="";
        boolean flag = false;
        try{
            URL url = new URL(strURL);
            BufferedInputStream file = new BufferedInputStream(url.openStream());
            PDDocument document = null;
            try {
                document = PDDocument.load(file);
                output = new PDFTextStripper().getText(document);
                System.out.println(output);
            } finally {
                if (document != null) {
                    document.close();
                }
            }
        }catch(Exception e){
            e.printStackTrace();
        }
        if(output.contains(text)){
            flag =  true;
        }
        return flag;
    }


来源:https://stackoverflow.com/questions/40738373/how-to-read-the-pdf-file-using-selenium

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!