Skip to content

Commit

Permalink
Merge pull request #248 from sixdouglas/Fix/#211_NullPointerOnAutoClo…
Browse files Browse the repository at this point in the history
…singDocument

Fix #211 null pointer on auto closing document
  • Loading branch information
andreasrosdal authored Aug 28, 2019
2 parents d34d918 + e69e835 commit 0d7b744
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 6 deletions.
6 changes: 3 additions & 3 deletions openpdf/src/main/java/com/lowagie/text/pdf/PdfWriter.java
Original file line number Diff line number Diff line change
Expand Up @@ -104,6 +104,7 @@
*/

public class PdfWriter extends DocWriter implements
AutoCloseable,
Closeable,
PdfViewerPreferences,
PdfEncryptionSettings,
Expand Down Expand Up @@ -1165,7 +1166,7 @@ public void close() {
// See: https://github.com/LibrePDF/OpenPDF/issues/164
throw new RuntimeException("The page " + pageReferences.size() +
" was requested but the document has only " + (currentPageNumber - 1) + " pages.");
pdf.close();

try {
addSharedObjectsToBody();
// add the root to the body
Expand Down Expand Up @@ -1224,8 +1225,7 @@ public void close() {
os.write(getISOBytes("\n%%EOF\n"));
super.close();
}
catch(IOException ioe) {
throw new ExceptionConverter(ioe);
catch(IOException ignored) {
}
}
}
Expand Down
21 changes: 18 additions & 3 deletions openpdf/src/test/java/com/lowagie/text/pdf/SimplePdfTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -31,11 +31,26 @@ void testSimplePdf() throws Exception {
}

@Test
void testTryWithResources() throws Exception {
void testTryWithResources_with_os_before_doc() throws Exception {
try (PdfReader reader = new PdfReader("./src/test/resources/HelloWorldMeta.pdf");
Document document = new Document();
FileOutputStream os = new FileOutputStream(File.createTempFile("temp-file-name", ".pdf"));
PdfWriter writer = PdfWriter.getInstance(document, os)
Document document = new Document();
PdfWriter writer = PdfWriter.getInstance(document, os)
) {
document.open();
final PdfContentByte cb = writer.getDirectContent();

document.newPage();
PdfImportedPage page = writer.getImportedPage(reader, 1);
cb.addTemplate(page, 1, 0, 0, 1, 0, 0);
}
}

@Test
void testTryWithResources_with_unknown_os() throws Exception {
try (PdfReader reader = new PdfReader("./src/test/resources/HelloWorldMeta.pdf");
Document document = new Document();
PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(File.createTempFile("temp-file-name", ".pdf")))
) {
document.open();
final PdfContentByte cb = writer.getDirectContent();
Expand Down

0 comments on commit 0d7b744

Please sign in to comment.