diff --git a/pdf-2/src/main/java/com/baeldung/pdfinfo/PdfInfoPdfBox.java b/pdf-2/src/main/java/com/baeldung/pdfinfo/PdfInfoPdfBox.java new file mode 100644 index 0000000000..33e38aadb8 --- /dev/null +++ b/pdf-2/src/main/java/com/baeldung/pdfinfo/PdfInfoPdfBox.java @@ -0,0 +1,36 @@ +package com.baeldung.pdfinfo; + + +import org.apache.pdfbox.Loader; +import org.apache.pdfbox.pdmodel.PDDocument; +import org.apache.pdfbox.pdmodel.PDDocumentInformation; + +import java.io.File; +import java.io.IOException; + +public class PdfInfoPdfBox { + + public static int getNumberOfPage(final String pdfFile) throws IOException { + File file = new File(pdfFile); + PDDocument document = Loader.loadPDF(file); + int pages = document.getNumberOfPages(); + document.close(); + return pages; + } + + public static boolean isPasswordRequired(final String pdfFile) throws IOException { + File file = new File(pdfFile); + PDDocument document = Loader.loadPDF(file); + boolean isEncrypted = document.isEncrypted(); + document.close(); + return isEncrypted; + } + + public static PDDocumentInformation getInfo(final String pdfFile) throws IOException { + File file = new File(pdfFile); + PDDocument document = Loader.loadPDF(file); + PDDocumentInformation info = document.getDocumentInformation(); + document.close(); + return info; + } +} diff --git a/pdf-2/src/test/java/com/baeldung/pdfinfo/PdfInfoPdfBoxUnitTest.java b/pdf-2/src/test/java/com/baeldung/pdfinfo/PdfInfoPdfBoxUnitTest.java new file mode 100644 index 0000000000..6d397bf9c8 --- /dev/null +++ b/pdf-2/src/test/java/com/baeldung/pdfinfo/PdfInfoPdfBoxUnitTest.java @@ -0,0 +1,51 @@ +package com.baeldung.pdfinfo; + +import org.apache.pdfbox.pdmodel.PDDocumentInformation; +import org.junit.Assert; +import org.junit.Test; + +import java.io.IOException; +import java.util.HashMap; + +public class PdfInfoPdfBoxUnitTest { + + private static final String PDF_FILE = "src/test/resources/input.pdf"; + + @Test + public void givenPdf_whenGetNumberOfPage_thenOK() throws IOException { + // given + int expectedNumberOfPage = 4; + + // when + int actualNumberOfPage = PdfInfoPdfBox.getNumberOfPage(PDF_FILE); + + // then + Assert.assertEquals(expectedNumberOfPage, actualNumberOfPage); + } + + @Test + public void givenPdf_whenIsPasswordRequired_thenOK() throws IOException { + // given + boolean expectedPasswordRequired = false; + + // when + boolean actualPasswordRequired = PdfInfoPdfBox.isPasswordRequired(PDF_FILE); + + // then + Assert.assertEquals(expectedPasswordRequired, actualPasswordRequired); + } + + @Test + public void givenPdf_whenGetInfo_thenOK() throws IOException { + // given + String expectedProducer = "LibreOffice 4.2"; + String expectedCreator = "Writer"; + + // when + PDDocumentInformation info = PdfInfoPdfBox.getInfo(PDF_FILE); + + // then + Assert.assertEquals(expectedProducer, info.getProducer()); + Assert.assertEquals(expectedCreator, info.getCreator()); + } +}