【问题标题】:Scala PDFBox error in code代码中的Scala PDFBox错误
【发布时间】:2016-05-18 10:12:24
【问题描述】:

编写了一个从 PDF 文档中读取文本的函数。 使用 scala 语言、Selenium、PDFBox 2.0.1。

下面是代码:

enter code here
import org.openqa.selenium.firefox.{FirefoxBinary, FirefoxDriver, FirefoxProfile}
import org.apache.pdfbox.pdfparser.PDFParser
import org.apache.pdfbox.text.PDFTextStripper
import java.io.BufferedInputStream
def pdfreaddata {
  driver.get("https://www.....pdf")
  driver.manage.timeouts.implicitlyWait(50, TimeUnit.SECONDS)
  val url: URL = new URL(driver.getCurrentUrl)
  println(url)
  val fileToParse: BufferedInputStream = new BufferedInputStream(url.openStream())
  val parser: PDFParser = new PDFParser(fileToParse)
  parser.parse()
  val output: String = new PDFTextStripper().getText(parser.getPDDocument)
  println("pdf Value" + output)
  parser.getPDDocument.close()

  driver.manage.timeouts.implicitlyWait(100, TimeUnit.SECONDS)
}

val parser: PDFParser = new PDFParser(fileToParse) 中显示 PDFParser 错误

错误信息:

无法解析构造函数

用Java也试过代码,得到同样的错误。

【问题讨论】:

  • 正确调用是 PDDocument doc = PDDocument.load(stream)。使用 new PDFParser() 是一种过时的方法。但是我不知道这是否是你麻烦的原因。

标签: java scala pdfbox


【解决方案1】:

您使用的是 PDFBox 2.x 版,但显然您正在关注 1.x 版的文档。在 2.0 中没有这样的构造函数。有些事情发生了变化,包括解析。关注migration guide 或回退到 1.8,因为它看起来确实有更多的文档记录和更多的在线资料。

【讨论】:

    【解决方案2】:

    使用 pdfbox 1.8.12 解决了构造函数问题。但即使是 pdf 也没有密码保护,它显示为加密。下面是使用 Scala 从 pdf 文档中提取加密文本的最终代码。将来可能对某人有用。

    def pdfreaddata {
    driver.get("https://www....combo.pdf")
    driver.manage.timeouts.implicitlyWait(50, TimeUnit.SECONDS)
    val url: URL = new URL(driver.getCurrentUrl)
    println(url)
    val fileToParse: BufferedInputStream = new BufferedInputStream(url.openStream())
    val parser: PDFParser = new PDFParser(fileToParse)
    parser.parse()
    val cosDocument:COSDocument  = parser.getDocument()
    val pdDocument:PDDocument = new PDDocument(cosDocument)
    if(pdDocument.isEncrypted()) {
      val sdm: StandardDecryptionMaterial  = new StandardDecryptionMaterial(PDF_OWNER_PASSWORD)//PDF_OWNER_PASSWORD =""
      pdDocument.openProtection(sdm) 
    }
    val output: String = new PDFTextStripper().getText(pdDocument)
    println("pdf Value" + output)
    parser.getPDDocument.close()
    
    driver.manage.timeouts.implicitlyWait(100, TimeUnit.SECONDS)
    }
    }
    

    【讨论】:

    • 文件可以用空的用户密码加密,这就是原因。这种情况经常发生,并且是为了限制权限(例如,禁止文本提取、打印等)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-05-28
    • 1970-01-01
    • 1970-01-01
    • 2020-09-17
    • 2017-11-18
    • 2016-03-15
    • 1970-01-01
    相关资源
    最近更新 更多