package it.stefanochizzolini.clown.samples;
import it.stefanochizzolini.clown.documents.Document;
import it.stefanochizzolini.clown.files.File;
import it.stefanochizzolini.clown.objects.PdfArray;
import it.stefanochizzolini.clown.objects.PdfDictionary;
import it.stefanochizzolini.clown.objects.PdfInteger;
import it.stefanochizzolini.clown.objects.PdfName;
import it.stefanochizzolini.clown.tokens.FileFormatException;
/**
This sample demonstrates how to perform advanced editing over a PDF document
structure accessing primitive objects. Particularly, it adds an 'open action' to
the document so that it starts with the content of page 2 magnified just enough to
fit the height of the page within the window.
*/
public class PrimitiveSample
implements ISample
{
public void run(
PDFClownSampleLoader loader
)
{
// (boilerplate user choice -- ignore it)
String filePath = loader.getPdfFileChoice("Please select a PDF file");
// 1. Open the PDF file!
File file;
try{file = new File(filePath);}
catch(FileFormatException e){throw new RuntimeException(filePath + " file has a bad file format.",e);}
catch(Exception e){throw new RuntimeException(filePath + " file access error.",e);}
// Get the PDF document!
Document document = file.getDocument();
// 2. Modifying the document...
{
// Create the action dictionary!
PdfDictionary action = new PdfDictionary();
// Define the action type (in this case: go-to)!
action.put(new PdfName("S"),new PdfName("GoTo"));
// Defining the action destination...
{
// Create the destination array!
PdfArray destination = new PdfArray();
// Define the 2nd page as the destination target!
destination.add(document.getPages().get(1).getBaseObject());
// Define the location of the document window on the page (fit vertically)!
destination.add(new PdfName("FitV"));
// Define the window's left-edge horizontal coordinate!
destination.add(new PdfInteger(-32768));
// Associate the destination to the action!
action.put(new PdfName("D"),destination);
}
// Associate the action to the document!
document.getBaseDataObject().put(
new PdfName("OpenAction"),
file.register(action) // Adds the action to the file, returning its reference.
); document.update(); // Update the existing document object (fundamental to override previous content).
}
// (boilerplate metadata insertion -- ignore it)
loader.buildAccessories(document,this.getClass(),"Primitive objects","manipulating a document at primitive object level");
// 3. Serialize the PDF file (again, boilerplate code -- see the PDFClownSampleLoader class source code)!
loader.serialize(file,this.getClass().getSimpleName());
}
}
|