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: import java.util.Collection;
10:
11: /**
12: This sample demonstrates how to concatenate a document to another.
13: <h3>Remarks</h3>
14: <p>This implementation is based on the <b>contextual cloning</b> functionality
15: of PDF Clown which allows to transparently and intuitively import contents from
16: one document to another.</p>
17: */
18: public class MergeSample implements ISample {
19: public void run(PDFClownSampleLoader loader) {
20: // (boilerplate user choice -- ignore it)
21: String sourceFilePath = loader
22: .getPdfFileChoice("Please select source PDF file");
23: String targetFilePath = loader
24: .getPdfFileChoice("Please select target PDF file");
25:
26: // 1. Opening the PDF files...
27: // Source file.
28: File sourceFile;
29: try {
30: sourceFile = new File(sourceFilePath);
31: } catch (FileFormatException e) {
32: throw new RuntimeException(sourceFilePath
33: + " file has a bad file format.", e);
34: } catch (Exception e) {
35: throw new RuntimeException(sourceFilePath
36: + " file access error.", e);
37: }
38: // Target file.
39: File targetFile;
40: try {
41: targetFile = new File(targetFilePath);
42: } catch (FileFormatException e) {
43: throw new RuntimeException(targetFilePath
44: + " file has a bad file format.", e);
45: } catch (Exception e) {
46: throw new RuntimeException(targetFilePath
47: + " file access error.", e);
48: }
49:
50: // Get the PDF documents!
51: Document sourceDocument = sourceFile.getDocument();
52: Document targetDocument = targetFile.getDocument();
53: Pages targetPages = targetDocument.getPages();
54:
55: // 2. Append the source document's pages to the target document!
56: /*
57: NOTE: To be added to an alien document,
58: pages MUST be firstly contextualized into it,
59: then added to the target pages collection.
60: */
61: targetPages.addAll((Collection<Page>) targetDocument
62: .contextualize((Collection<Page>) sourceDocument
63: .getPages()));
64: targetPages.update(); // NOTE: Update is fundamental to override original page collection.
65:
66: // (boilerplate metadata insertion -- ignore it)
67: loader.buildAccessories(targetDocument, this .getClass(),
68: "Merge",
69: "concatenating two (or possibly more) documents");
70:
71: // 3. Serialize the PDF file (again, boilerplate code -- see the PDFClownSampleLoader class source code)!
72: loader.serialize(targetFile, this.getClass().getSimpleName());
73: }
74: }
|