PDF Libraries

From Chorke Wiki
Revision as of 23:51, 5 December 2023 by Shahed (talk | contribs) (→‎Apache PDFBox)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to navigation Jump to search

Apache PDFBox

<dependency>
    <groupId>org.apache.pdfbox</groupId>
    <artifactId>pdfbox</artifactId>
    <version>2.0.24</version>
</dependency>
@BeforeEach
public void setUp() {
    String[] names = new String[]{"pdf_source_1.pdf", "pdf_source_2.pdf", "pdf_source_3.pdf"};
    mergeTargetPath = String.format(DESTINATION_FORMAT, System.getProperty(USER_HOME), "Merge");
    splitTargetPath = String.format(DESTINATION_FORMAT, System.getProperty(USER_HOME), "Split Merge");
    resourcePaths = Arrays.stream(names).map(name -> String.format(CLASSPATH_FORMAT, name)).collect(Collectors.toList());
}

@Test
public void mergeTest() throws IOException {
    LocalDateTime startTime = LocalDateTime.now();
    PDFMergerUtility merger = new PDFMergerUtility();
    resourcePaths.forEach(path -> {
        try {
            merger.addSource(new ClassPathResource(path).getInputStream());
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    });

    merger.setDestinationFileName(mergeTargetPath);
    merger.mergeDocuments(MemoryUsageSetting.setupMainMemoryOnly());
    Duration duration = Duration.between(startTime, LocalDateTime.now());
    LOG.info("Duration: {} Millis", duration.toMillis());
    Assertions.assertTrue(true);
}

@Test
public void splitMergeTest() throws IOException {
    LocalDateTime startTime = LocalDateTime.now();
    try (PDDocument target = new PDDocument()) {
        resourcePaths.forEach(path -> {
            try {
                PDDocument source = PDDocument.load(new ClassPathResource(path).getInputStream());
                target.addPage(source.getPage(0));
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        });
        target.save(splitTargetPath);
    }
    Duration duration = Duration.between(startTime, LocalDateTime.now());
    LOG.info("Duration: {} Millis", duration.toMillis());
    Assertions.assertTrue(true);
}

References