java AFMParser,如何使用Apache PDFBox从PDF文件中提取文本

博主在尝试使用Apache PDFBox从PDF文件中提取文本时遇到了NullPointerException错误。问题可能与FilePath有关,解决方案是确保PDF文件路径正确,并使用RandomAccessFile进行解析。经过调整后的代码成功提取了文本。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

I would like to extract text from a given PDF file with Apache PDFBox.

I wrote this code:

PDFTextStripper pdfStripper = null;

PDDocument pdDoc = null;

COSDocument cosDoc = null;

File file = new File(filepath);

PDFParser parser = new PDFParser(new FileInputStream(file));

parser.parse();

cosDoc = parser.getDocument();

pdfStripper = new PDFTextStripper();

pdDoc = new PDDocument(cosDoc);

pdfStripper.setStartPage(1);

pdfStripper.setEndPage(5);

String parsedText = pdfStripper.getText(pdDoc);

System.out.println(parsedText);

However, I got the following error:

Exception in thread "main" java.lang.NullPointerException

at org.apache.fontbox.afm.AFMParser.main(AFMParser.java:304)

I added pdfbox-1.8.5.jar and fontbox-1.8.5.jar to the class path.

Edit

I added System.out.println("program starts"); to the beginning of the program.

I ran it, then I got the same error as mentioned above and program starts did not appear in the console.

Thus, I think I have a problem with the class path or something.

Thank you.

解决方案

I executed your code and it worked properly. Maybe your problem is related to FilePath that you have given to file. I put my pdf in C drive and hard coded the file path.here is my code:

// PDFBox 2.0.8 require org.apache.pdfbox.io.RandomAccessRead

// import org.apache.pdfbox.io.RandomAccessFile;

public class PDFReader{

public static void main(String args[]) {

PDFTextStripper pdfStripper = null;

PDDocument pdDoc = null;

COSDocument cosDoc = null;

File file = new File("C:/my.pdf");

try {

// PDFBox 2.0.8 require org.apache.pdfbox.io.RandomAccessRead

// RandomAccessFile randomAccessFile = new RandomAccessFile(file, "r");

// PDFParser parser = new PDFParser(randomAccessFile);

PDFParser parser = new PDFParser(new FileInputStream(file));

parser.parse();

cosDoc = parser.getDocument();

pdfStripper = new PDFTextStripper();

pdDoc = new PDDocument(cosDoc);

pdfStripper.setStartPage(1);

pdfStripper.setEndPage(5);

String parsedText = pdfStripper.getText(pdDoc);

System.out.println(parsedText);

} catch (IOException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值