01: package it.stefanochizzolini.clown.samples;
02:
03: import it.stefanochizzolini.clown.documents.Document;
04: import it.stefanochizzolini.clown.documents.Page;
05: import it.stefanochizzolini.clown.documents.Pages;
06: import it.stefanochizzolini.clown.files.File;
07: import it.stefanochizzolini.clown.tokens.FileFormatException;
08:
09: /**
10: This sample demonstrates how to split a document into its constituting pages.
11: <h3>Remarks</h3>
12: <p>This implementation is based on the <b>contextual cloning</b> functionality
13: of PDF Clown which allows to transparently and intuitively import contents from
14: one document to another.</p>
15: */
16: public class SplitSample implements ISample {
17: public void run(PDFClownSampleLoader loader) {
18: // (boilerplate user choice -- ignore it)
19: String filePath = loader
20: .getPdfFileChoice("Please select a PDF file");
21:
22: // 1. Open the PDF file!
23: File file;
24: try {
25: file = new File(filePath);
26: } catch (FileFormatException e) {
27: throw new RuntimeException(filePath
28: + " file has a bad file format.", e);
29: } catch (Exception e) {
30: throw new RuntimeException(
31: filePath + " file access error.", e);
32: }
33:
34: // Get the PDF documents!
35: Document document = file.getDocument();
36:
37: // 2. Splitting the document into single-page documents...
38: int index = 0;
39: Pages pages = document.getPages();
40: int pagesCount = pages.size();
41: for (Page page : pages) {
42: // 2.1. Page file creation.
43: File pageFile = new File();
44: Document pageDocument = pageFile.getDocument();
45: // Append current page to its own document!
46: /* NOTE: Contextual cloning in action. */
47: pageDocument.getPages().add((Page) page.clone(pageDocument) // Contextual cloning of the source page into its target document.
48: );
49:
50: // (boilerplate metadata insertion -- ignore it)
51: loader.buildAccessories(pageDocument, this .getClass(),
52: "Split (" + (index + 1) + "/" + pagesCount + ")",
53: "splitting a PDF file into its constituting pages");
54:
55: // 2.2. Page file serialization (again, boilerplate code -- see the PDFClownSampleLoader class source code).
56: loader.serialize(pageFile, this .getClass().getSimpleName()
57: + "." + (++index), false);
58: }
59: }
60: }
|