01: package it.stefanochizzolini.clown.samples;
02:
03: import it.stefanochizzolini.clown.documents.Document;
04: import it.stefanochizzolini.clown.files.File;
05: import it.stefanochizzolini.clown.objects.PdfArray;
06: import it.stefanochizzolini.clown.objects.PdfDictionary;
07: import it.stefanochizzolini.clown.objects.PdfInteger;
08: import it.stefanochizzolini.clown.objects.PdfName;
09: import it.stefanochizzolini.clown.tokens.FileFormatException;
10:
11: /**
12: This sample demonstrates how to perform advanced editing over a PDF document
13: structure accessing primitive objects. Particularly, it adds an 'open action' to
14: the document so that it starts with the content of page 2 magnified just enough to
15: fit the height of the page within the window.
16: */
17: public class PrimitiveSample implements ISample {
18: public void run(PDFClownSampleLoader loader) {
19: // (boilerplate user choice -- ignore it)
20: String filePath = loader
21: .getPdfFileChoice("Please select a PDF file");
22:
23: // 1. Open the PDF file!
24: File file;
25: try {
26: file = new File(filePath);
27: } catch (FileFormatException e) {
28: throw new RuntimeException(filePath
29: + " file has a bad file format.", e);
30: } catch (Exception e) {
31: throw new RuntimeException(
32: filePath + " file access error.", e);
33: }
34:
35: // Get the PDF document!
36: Document document = file.getDocument();
37:
38: // 2. Modifying the document...
39: {
40: // Create the action dictionary!
41: PdfDictionary action = new PdfDictionary();
42: // Define the action type (in this case: go-to)!
43: action.put(new PdfName("S"), new PdfName("GoTo"));
44: // Defining the action destination...
45: {
46: // Create the destination array!
47: PdfArray destination = new PdfArray();
48: // Define the 2nd page as the destination target!
49: destination.add(document.getPages().get(1)
50: .getBaseObject());
51: // Define the location of the document window on the page (fit vertically)!
52: destination.add(new PdfName("FitV"));
53: // Define the window's left-edge horizontal coordinate!
54: destination.add(new PdfInteger(-32768));
55: // Associate the destination to the action!
56: action.put(new PdfName("D"), destination);
57: }
58: // Associate the action to the document!
59: document.getBaseDataObject().put(new PdfName("OpenAction"),
60: file.register(action) // Adds the action to the file, returning its reference.
61: );
62: document.update(); // Update the existing document object (fundamental to override previous content).
63: }
64:
65: // (boilerplate metadata insertion -- ignore it)
66: loader.buildAccessories(document, this .getClass(),
67: "Primitive objects",
68: "manipulating a document at primitive object level");
69:
70: // 3. Serialize the PDF file (again, boilerplate code -- see the PDFClownSampleLoader class source code)!
71: loader.serialize(file, this.getClass().getSimpleName());
72: }
73: }
|