KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > it > stefanochizzolini > clown > samples > PagesManipulationSample


1 package it.stefanochizzolini.clown.samples;
2
3 import it.stefanochizzolini.clown.bytes.*;
4 import it.stefanochizzolini.clown.documents.contents.*;
5 import it.stefanochizzolini.clown.documents.contents.entities.*;
6 import it.stefanochizzolini.clown.documents.contents.colorSpaces.*;
7 import it.stefanochizzolini.clown.documents.contents.fonts.*;
8 import it.stefanochizzolini.clown.documents.contents.xObjects.*;
9 import it.stefanochizzolini.clown.objects.*;
10 import it.stefanochizzolini.clown.documents.*;
11 import it.stefanochizzolini.clown.files.*;
12 import it.stefanochizzolini.clown.tokens.*;
13 import java.awt.geom.Point2D JavaDoc;
14 import java.util.*;
15
16 /**
17   This sample demonstrates how to manipulate the pages collection within a document, to perform
18   movements, additions, removals and extractions of groups of pages.
19   <h3>Remarks</h3>
20   <p>This implementation is based on the <b>contextual cloning</b> functionality
21   of PDF Clown which allows to transparently and intuitively import contents from
22   one document into another.</p>
23 */

24 public class PagesManipulationSample
25   implements ISample
26 {
27   public void run(
28     PDFClownSampleLoader loader
29     )
30   {
31     /*
32       NOTE: This procedure is made up of this sequence of actions:
33       1. User choice.
34       2. Document editing.
35       3. Page file serialization.
36     */

37     Scanner in = new Scanner(System.in);
38
39     File file;
40     java.io.RandomAccessFile JavaDoc baseInputStream;
41     while(true)
42     {
43       // 1. User choice.
44
String JavaDoc filePath = loader.getPdfFileChoice("Please select a PDF file");
45
46       // 2. Document editing.
47
FileInputStream inputStream;
48       try
49       {
50         // Open the file stream!
51
baseInputStream = new java.io.RandomAccessFile JavaDoc(filePath,"r");
52         inputStream = new FileInputStream(baseInputStream);
53       }
54       catch(Exception JavaDoc e)
55       {throw new RuntimeException JavaDoc(filePath + " file access error.",e);}
56       try
57       {
58         // Open the PDF file!
59
file = new File(inputStream);
60       }
61       catch(FileFormatException e)
62       {throw new RuntimeException JavaDoc(filePath + " file has a bad file format.",e);}
63
64       // Get the PDF document!
65
Document doc = file.getDocument();
66       // Get the page collection!
67
Pages pages = doc.getPages();
68       // Get the page count!
69
int pageCount = pages.size();
70       // Are there more than one page?
71
if(pageCount > 1) // Multiple pages.
72
{
73         int action = 0;
74         // Getting the user's choice about which operation to perform...
75
System.out.println("\nAvailable operations:");
76         System.out.println("[0] Page removal");
77         System.out.println("[1] Page addition");
78         System.out.println("[2] Page movement");
79         System.out.println("[3] Page extraction");
80         System.out.print("Select the operation to perform: ");
81         try{action = Integer.parseInt(in.nextLine()); /* Custom choice. */}
82         catch(Exception JavaDoc e){/* Default choice. */}
83
84         switch(action)
85         {
86           case 0: // Page removal.
87
{
88             // Get the user's choice about the first page to remove!
89
int fromPageIndex = getPageChoice("Select the start page to remove",pageCount);
90             // Get the user's choice about the last page to remove!
91
int toPageIndex = getPageChoice("Select the end page to remove",pageCount) + 1;
92
93             List<Page> removingPages = pages.subList(fromPageIndex,toPageIndex);
94
95             // Remove the pages from the pages collection!
96
/* NOTE: Shallow removal. */
97             pages.removeAll(removingPages); pages.update();
98
99             // Remove the pages from the document (decontextualize)!
100
/* NOTE: Deep removal. */
101             doc.decontextualize(removingPages);
102
103             break;
104           }
105           case 1: // Page addition.
106
{
107             String JavaDoc sourceFilePath = loader.getPdfFileChoice("Select the source PDF file");
108             java.io.RandomAccessFile JavaDoc baseSourceInputStream;
109             FileInputStream sourceInputStream;
110             // Opening the file stream...
111
try
112             {
113               baseSourceInputStream = new java.io.RandomAccessFile JavaDoc(sourceFilePath,"r");
114               sourceInputStream = new FileInputStream(baseSourceInputStream);
115             }
116             catch(Exception JavaDoc e)
117             {throw new RuntimeException JavaDoc(sourceFilePath + " file access error.",e);}
118             File sourceFile;
119             // Opening the PDF file...
120
try
121             {sourceFile = new File(sourceInputStream);}
122             catch(FileFormatException e)
123             {throw new RuntimeException JavaDoc(sourceFilePath + " file has a bad file format.",e);}
124             // Get the page collection!
125
Pages sourcePages = sourceFile.getDocument().getPages();
126             // Get the page count!
127
int sourcePageCount = sourcePages.size();
128
129             // Get the user's choice about the first page to add!
130
int fromSourcePageIndex = getPageChoice("Select the start source page to add",sourcePageCount);
131             // Get the user's choice about the last page to add!
132
int toSourcePageIndex = getPageChoice("Select the end source page to add",sourcePageCount) + 1;
133             // Get the user's choice about where to insert the source pages!
134
int targetPageIndex = getPageChoice("Select the position where to insert the source pages",pageCount+1);
135
136             /*
137             NOTE: To be added to an alien document, pages MUST be contextualized within it first,
138             then added to the target pages collection.
139             */

140             // Add the source pages to the document (contextualize)!
141
/* NOTE: Deep addition. */
142             Collection<Page> addingPages = (Collection<Page>)doc.contextualize(
143               sourcePages.subList(
144                 fromSourcePageIndex,
145                 toSourcePageIndex
146                 )
147               );
148             // Add the source pages to the pages collection!
149
/* NOTE: Shallow addition. */
150             if(targetPageIndex == pageCount)
151             {pages.addAll(addingPages);}
152             else
153             {pages.addAll(targetPageIndex,addingPages);}
154             pages.update();
155
156             try{baseSourceInputStream.close();}
157             catch(Exception JavaDoc e){/* Ignore. */}
158
159             break;
160           }
161           case 2: // Page movement.
162
{
163             // Get the user's choice about the first page to move!
164
int fromSourcePageIndex = getPageChoice("Select the start page to move",pageCount);
165             // Get the user's choice about the last page to add!
166
int toSourcePageIndex = getPageChoice("Select the end page to move",pageCount) + 1;
167             // Get the user's choice about where to move the pages!
168
int targetPageIndex = getPageChoice("Select the position where to insert the pages",pageCount+1);
169
170             List<Page> movingPages = pages.subList(fromSourcePageIndex,toSourcePageIndex);
171
172             // Temporarily remove the pages from the pages collection!
173
/* NOTE: Shallow removal. */
174             pages.removeAll(movingPages);
175
176             // Adjust indexes!
177
pageCount -= movingPages.size();
178             if(targetPageIndex > fromSourcePageIndex)
179             {targetPageIndex -= movingPages.size(); /* Adjust target position due to shifting for temporary page removal. */}
180
181             // Reinsert the pages at the target position!
182
/* NOTE: Shallow addition. */
183             if(targetPageIndex == pageCount)
184             {pages.addAll(movingPages);}
185             else
186             {pages.addAll(targetPageIndex,movingPages);}
187             pages.update();
188
189             break;
190           }
191           case 3: // Page extraction.
192
{
193             // Get the user's choice about the first page to extract!
194
int fromPageIndex = getPageChoice("Select the start page",pageCount);
195             // Get the user's choice about the last page to extract!
196
int toPageIndex = getPageChoice("Select the end page",pageCount) + 1;
197
198             // Instantiate target file!
199
file = new File();
200             doc = file.getDocument();
201             // Add the pages to the target file!
202
/*
203             NOTE: To be added to an alien document, pages MUST be contextualized within it first,
204             then added to the target pages collection.
205             */

206             doc.getPages().addAll(
207               (Collection<Page>)doc.contextualize(
208                 pages.subList(fromPageIndex,toPageIndex)
209                 )
210               );
211
212             break;
213           }
214         }
215
216         // 3. Serialization.
217
loader.serialize(file,"PagesManipulationSample");
218
219         try{baseInputStream.close();}
220         catch(Exception JavaDoc e){/* Ignore. */}
221
222         break;
223       }
224       else // Single page.
225
{
226         try{baseInputStream.close();}
227         catch(Exception JavaDoc e){/* Ignore. */}
228
229         System.out.println("\nSorry, the document you selected (" + filePath + ") has just a single page: try another document, please!");
230       }
231     }
232   }
233
234   private int getPageChoice(
235     String JavaDoc inputDescription,
236     int pageCount
237     )
238   {
239     Scanner in = new Scanner(System.in);
240     int pageIndex = 0;
241     // Getting the user's choice about which page to remove...
242
System.out.print("\n" + inputDescription + " [1-" + pageCount + "]: ");
243     try
244     {pageIndex = Integer.parseInt(in.nextLine()) - 1; /* Custom choice. */}
245     catch(Exception JavaDoc e)
246     {/* Default choice. */}
247     if(pageIndex < 0)
248       pageIndex = 0;
249     else if(pageIndex >= pageCount)
250       pageIndex = pageCount - 1;
251
252     return pageIndex;
253   }
254 }
Popular Tags