【问题标题】:How to read the pdf file using selenium如何使用 selenium 读取 pdf 文件
【发布时间】:2017-04-05 22:08:30
【问题描述】:

我正在处理有链接的网页,点击它会在新窗口中打开一个 pdf 文件。 我必须阅读该 pdf 文件以根据已完成的交易验证一些数据。一种方法是下载该文件然后使用它。 任何人都可以帮助我解决这个问题。我必须在 IE 11 上工作

提前致谢。

【问题讨论】:

  • 使用 selenium 从 pdf 读取内容将不起作用。下载 pdf 文件,然后使用 PDFbox 或任何其他库读取文件。

标签: java pdf selenium-webdriver download pdf-reader


【解决方案1】:

使用 PDFBox 和 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;
    }

由于旧版本 PDFBox 中的一些功能已被弃用,我们需要使用另一个 FontBox 和 PDFBox。我用过PDFBox (2.0.3)FontBox (2.0.3),它工作正常。但它不会读取图像。

【讨论】:

  • 不确定这是否适用于当前版本;最好做PDDocument doc = PDDocument.load(url.openStream()); 然后删除所有不需要的代码(COSDocument、PDFParser)
  • 试试下面的功能:
【解决方案2】:

首先下载pdfbox jar。

strURL 是一个包含 .pdf 文件的网络 URL: 喜欢(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;
    }

【讨论】:

  • 在我的情况下,URL 不以 .pdf 结尾,我该如何继续
  • 请分享你的pdf文件
猜你喜欢
  • 1970-01-01
  • 2017-10-16
  • 2016-07-17
  • 1970-01-01
  • 2011-06-14
  • 2011-07-24
  • 2015-09-27
  • 2011-04-30
  • 2012-08-17
相关资源
最近更新 更多