在 NetBeans 8.1 中使用 pdfbox 将 pdf 转换为文本
pdf to text coversion using pdfbox in netbeans 8.1
我正在尝试将 pdf 文档转换为文本,但出现空指针异常。不明白为什么会出现错误。错误显示在导入语句中。
我附上下面的代码:
public class PDFTextParser {
private static Object f;
public static void main(String args[]) {
PDFTextStripper pdfStripper = null;
PDDocument pdDoc = null;
COSDocument cosDoc = null;
File file = new File("D:\1.pdf");
try {
f = null;
PDFParser parser = new PDFParser((RandomAccessRead) f);
FileInputStream f= 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) {
e.printStackTrace();
}
}
}
This is the error im getting:
Exception in thread "main" java.lang.NullPointerException
at org.apache.pdfbox.pdfparser.PDFParser.<init>(PDFParser.java:138)
at org.apache.pdfbox.pdfparser.PDFParser.<init>(PDFParser.java:102)
at org.apache.pdfbox.pdfparser.PDFParser.<init>(PDFParser.java:61)
at PDFTextParser.main(PDFTextParser.java:33)
是的,您正在传递空对象:
f = null;
PDFParser parser = new PDFParser((RandomAccessRead) f);
顺便说一句,作为奖励,这里有一些更新的(和更短的)代码来使用 PDFBox 打开 PDF 文件,我省略了异常处理:
File file = new File("D:\1.pdf");
PDDocument pdDoc = PDDocument.load(file);
pdfStripper = new PDFTextStripper();
pdfStripper.setStartPage(1);
pdfStripper.setEndPage(5);
String parsedText = pdfStripper.getText(pdDoc);
System.out.println(parsedText);
我正在尝试将 pdf 文档转换为文本,但出现空指针异常。不明白为什么会出现错误。错误显示在导入语句中。 我附上下面的代码:
public class PDFTextParser {
private static Object f;
public static void main(String args[]) {
PDFTextStripper pdfStripper = null;
PDDocument pdDoc = null;
COSDocument cosDoc = null;
File file = new File("D:\1.pdf");
try {
f = null;
PDFParser parser = new PDFParser((RandomAccessRead) f);
FileInputStream f= 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) {
e.printStackTrace();
}
}
}
This is the error im getting:
Exception in thread "main" java.lang.NullPointerException
at org.apache.pdfbox.pdfparser.PDFParser.<init>(PDFParser.java:138)
at org.apache.pdfbox.pdfparser.PDFParser.<init>(PDFParser.java:102)
at org.apache.pdfbox.pdfparser.PDFParser.<init>(PDFParser.java:61)
at PDFTextParser.main(PDFTextParser.java:33)
是的,您正在传递空对象:
f = null;
PDFParser parser = new PDFParser((RandomAccessRead) f);
顺便说一句,作为奖励,这里有一些更新的(和更短的)代码来使用 PDFBox 打开 PDF 文件,我省略了异常处理:
File file = new File("D:\1.pdf");
PDDocument pdDoc = PDDocument.load(file);
pdfStripper = new PDFTextStripper();
pdfStripper.setStartPage(1);
pdfStripper.setEndPage(5);
String parsedText = pdfStripper.getText(pdDoc);
System.out.println(parsedText);