PagingPdfParser { public void run() throws ParseException, CheckedOutOfMemoryError { PDDocument doc = null; try { try { doc = PDDocument.load(file); } catch (InvalidPasswordException e) { throw new ParseException(Msg.doc_pw_protected.get()); } PagingStripper stripper = new PagingStripper(); stripper.setSortByPosition(true); stripper.writeText(doc, writer); } catch (Exception e) { if (e instanceof ParseException) { throw (ParseException) e; } else { throw new ParseException(e); } } catch (OutOfMemoryError e) { throw new CheckedOutOfMemoryError(e); } finally { Closeables.closeQuietly(doc); } } PagingPdfParser(File file, PageHandler handler); void run();  }
@Test public void testParse() throws ParseException, CheckedOutOfMemoryError { final List<String> pages = new ArrayList<String> (3); PageHandler handler = new PageHandler() { public boolean handlePage(String pageText) { pages.add(pageText); return false; } }; new PagingPdfParser(TestFiles.multi_page_pdf.get(), handler).run(); assertEquals(3, pages.size()); assertEquals("page 1" + Util.LS, pages.get(0)); assertEquals("page 2" + Util.LS, pages.get(1)); assertEquals("page 3" + Util.LS, pages.get(2)); }
@Test public void testParseAndStop() throws ParseException, CheckedOutOfMemoryError { final List<String> pages = new ArrayList<String> (2); PageHandler handler = new PageHandler() { public boolean handlePage(String pageText) { pages.add(pageText); return pages.size() >= 2; } }; new PagingPdfParser(TestFiles.multi_page_pdf.get(), handler).run(); assertEquals(2, pages.size()); assertEquals("page 1" + Util.LS, pages.get(0)); assertEquals("page 2" + Util.LS, pages.get(1)); }
@Test public void testEncryptedPdf() throws Exception { Logger logger = Logger.getLogger("org.apache.pdfbox.pdfparser.PDFParser"); logger.setLevel(java.util.logging.Level.OFF); try { PageHandler handler = new PageHandler() { public boolean handlePage(String pageText) { return false; } }; new PagingPdfParser(TestFiles.encrypted_pdf.get(), handler).run(); assertTrue(false); } catch (ParseException e) { assertTrue(e.getMessage().equals(Msg.doc_pw_protected.get())); } }