From 6025b6016517c6d898d8957d1d7e03ba71431912 Mon Sep 17 00:00:00 2001 From: tknall Date: Fri, 1 Dec 2006 12:20:24 +0000 Subject: Initial import of release 2.2. git-svn-id: https://joinup.ec.europa.eu/svn/pdf-as/trunk@4 7b5415b0-85f9-ee4d-85bd-d5d0c3b42d1c --- .../java/org/pdfbox/examples/AbstractExample.java | 125 ++++++++ .../java/org/pdfbox/examples/fdf/PrintFields.java | 163 ++++++++++ .../java/org/pdfbox/examples/fdf/SetField.java | 128 ++++++++ src/main/java/org/pdfbox/examples/fdf/package.html | 9 + src/main/java/org/pdfbox/examples/package.html | 9 + .../org/pdfbox/examples/pdmodel/AddJavascript.java | 96 ++++++ .../examples/pdmodel/AddMessageToEachPage.java | 148 +++++++++ .../examples/pdmodel/AddMetadataFromDocInfo.java | 180 +++++++++++ .../pdfbox/examples/pdmodel/CreateBlankPDF.java | 123 +++++++ .../pdfbox/examples/pdmodel/CreateBookmarks.java | 119 +++++++ .../org/pdfbox/examples/pdmodel/EmbeddedFiles.java | 170 ++++++++++ .../org/pdfbox/examples/pdmodel/HelloWorld.java | 137 ++++++++ .../org/pdfbox/examples/pdmodel/HelloWorldTTF.java | 134 ++++++++ .../examples/pdmodel/HelloWorldType1AfmPfb.java | 134 ++++++++ .../org/pdfbox/examples/pdmodel/ImageToPDF.java | 146 +++++++++ .../pdfbox/examples/pdmodel/PrintBookmarks.java | 142 ++++++++ .../examples/pdmodel/PrintDocumentMetaData.java | 165 ++++++++++ .../pdfbox/examples/pdmodel/RemoveFirstPage.java | 98 ++++++ .../org/pdfbox/examples/pdmodel/ReplaceString.java | 186 +++++++++++ .../org/pdfbox/examples/pdmodel/RubberStamp.java | 113 +++++++ .../pdfbox/examples/pdmodel/ShowColorBoxes.java | 135 ++++++++ .../java/org/pdfbox/examples/pdmodel/package.html | 9 + .../examples/persistence/AppendAndFillDoc.java | 282 ++++++++++++++++ .../org/pdfbox/examples/persistence/AppendDoc.java | 357 +++++++++++++++++++++ .../org/pdfbox/examples/persistence/CopyDoc.java | 140 ++++++++ .../org/pdfbox/examples/persistence/FieldsDoc.java | 177 ++++++++++ .../examples/persistence/WriteDecodedDoc.java | 151 +++++++++ .../org/pdfbox/examples/persistence/package.html | 9 + .../pdfbox/examples/signature/ShowSignature.java | 168 ++++++++++ .../org/pdfbox/examples/signature/package.html | 9 + .../pdfbox/examples/util/ExtractTextByArea.java | 119 +++++++ .../pdfbox/examples/util/PrintTextLocations.java | 144 +++++++++ .../java/org/pdfbox/examples/util/package.html | 9 + 33 files changed, 4234 insertions(+) create mode 100644 src/main/java/org/pdfbox/examples/AbstractExample.java create mode 100644 src/main/java/org/pdfbox/examples/fdf/PrintFields.java create mode 100644 src/main/java/org/pdfbox/examples/fdf/SetField.java create mode 100644 src/main/java/org/pdfbox/examples/fdf/package.html create mode 100644 src/main/java/org/pdfbox/examples/package.html create mode 100644 src/main/java/org/pdfbox/examples/pdmodel/AddJavascript.java create mode 100644 src/main/java/org/pdfbox/examples/pdmodel/AddMessageToEachPage.java create mode 100644 src/main/java/org/pdfbox/examples/pdmodel/AddMetadataFromDocInfo.java create mode 100644 src/main/java/org/pdfbox/examples/pdmodel/CreateBlankPDF.java create mode 100644 src/main/java/org/pdfbox/examples/pdmodel/CreateBookmarks.java create mode 100644 src/main/java/org/pdfbox/examples/pdmodel/EmbeddedFiles.java create mode 100644 src/main/java/org/pdfbox/examples/pdmodel/HelloWorld.java create mode 100644 src/main/java/org/pdfbox/examples/pdmodel/HelloWorldTTF.java create mode 100644 src/main/java/org/pdfbox/examples/pdmodel/HelloWorldType1AfmPfb.java create mode 100644 src/main/java/org/pdfbox/examples/pdmodel/ImageToPDF.java create mode 100644 src/main/java/org/pdfbox/examples/pdmodel/PrintBookmarks.java create mode 100644 src/main/java/org/pdfbox/examples/pdmodel/PrintDocumentMetaData.java create mode 100644 src/main/java/org/pdfbox/examples/pdmodel/RemoveFirstPage.java create mode 100644 src/main/java/org/pdfbox/examples/pdmodel/ReplaceString.java create mode 100644 src/main/java/org/pdfbox/examples/pdmodel/RubberStamp.java create mode 100644 src/main/java/org/pdfbox/examples/pdmodel/ShowColorBoxes.java create mode 100644 src/main/java/org/pdfbox/examples/pdmodel/package.html create mode 100644 src/main/java/org/pdfbox/examples/persistence/AppendAndFillDoc.java create mode 100644 src/main/java/org/pdfbox/examples/persistence/AppendDoc.java create mode 100644 src/main/java/org/pdfbox/examples/persistence/CopyDoc.java create mode 100644 src/main/java/org/pdfbox/examples/persistence/FieldsDoc.java create mode 100644 src/main/java/org/pdfbox/examples/persistence/WriteDecodedDoc.java create mode 100644 src/main/java/org/pdfbox/examples/persistence/package.html create mode 100644 src/main/java/org/pdfbox/examples/signature/ShowSignature.java create mode 100644 src/main/java/org/pdfbox/examples/signature/package.html create mode 100644 src/main/java/org/pdfbox/examples/util/ExtractTextByArea.java create mode 100644 src/main/java/org/pdfbox/examples/util/PrintTextLocations.java create mode 100644 src/main/java/org/pdfbox/examples/util/package.html (limited to 'src/main/java/org/pdfbox/examples') diff --git a/src/main/java/org/pdfbox/examples/AbstractExample.java b/src/main/java/org/pdfbox/examples/AbstractExample.java new file mode 100644 index 0000000..1350b73 --- /dev/null +++ b/src/main/java/org/pdfbox/examples/AbstractExample.java @@ -0,0 +1,125 @@ +/** + * Copyright (c) 2003, www.pdfbox.org + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of pdfbox; nor the names of its + * contributors may be used to endorse or promote products derived from this + * software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON + * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + * http://www.pdfbox.org + * + */ +package org.pdfbox.examples; + +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; + +import org.pdfbox.cos.COSDocument; + +import org.pdfbox.pdmodel.PDDocument; + +import org.pdfbox.pdfwriter.COSWriter; + +/** + * A simple class which has some methods used by all examples. + * + * @author Ben Litchfield (ben@csh.rit.edu) + * @version $Revision: 1.3 $ + */ +public abstract class AbstractExample +{ + /** + * Close the stream. + * + * @param stream The stream to close. + * + * @throws IOException If there is an error closing the stream. + */ + public void close( InputStream stream ) throws IOException + { + if( stream != null ) + { + stream.close(); + } + } + + /** + * Close the stream. + * + * @param stream The stream to close. + * + * @throws IOException If there is an error closing the stream. + */ + public void close( OutputStream stream ) throws IOException + { + if( stream != null ) + { + stream.close(); + } + } + + /** + * Close the document. + * + * @param doc The doc to close. + * + * @throws IOException If there is an error closing the document. + */ + public void close( COSDocument doc ) throws IOException + { + if( doc != null ) + { + doc.close(); + } + } + + /** + * Close the document. + * + * @param doc The doc to close. + * + * @throws IOException If there is an error closing the document. + */ + public void close( PDDocument doc ) throws IOException + { + if( doc != null ) + { + doc.close(); + } + } + + /** + * Close the writer. + * + * @param writer The writer to close. + * + * @throws IOException If there is an error closing the writer. + */ + public static void close( COSWriter writer ) throws IOException + { + if( writer != null ) + { + writer.close(); + } + } +} \ No newline at end of file diff --git a/src/main/java/org/pdfbox/examples/fdf/PrintFields.java b/src/main/java/org/pdfbox/examples/fdf/PrintFields.java new file mode 100644 index 0000000..189ba72 --- /dev/null +++ b/src/main/java/org/pdfbox/examples/fdf/PrintFields.java @@ -0,0 +1,163 @@ +/** + * Copyright (c) 2003-2005, www.pdfbox.org + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of pdfbox; nor the names of its + * contributors may be used to endorse or promote products derived from this + * software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON + * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + * http://www.pdfbox.org + * + */ +package org.pdfbox.examples.fdf; + +import java.io.IOException; + +import java.util.Iterator; +import java.util.List; + +import org.pdfbox.pdmodel.interactive.form.PDAcroForm; +import org.pdfbox.pdmodel.interactive.form.PDField; + +import org.pdfbox.exceptions.CryptographyException; +import org.pdfbox.exceptions.InvalidPasswordException; + +import org.pdfbox.pdmodel.PDDocument; +import org.pdfbox.pdmodel.PDDocumentCatalog; + +/** + * This example will take a PDF document and print all the fields from the file. + * + * @author Ben Litchfield (ben@benlitchfield.com) + * @version $Revision: 1.15 $ + */ +public class PrintFields +{ + + /** + * This will print all the fields from the document. + * + * @param pdfDocument The PDF to get the fields from. + * + * @throws IOException If there is an error getting the fields. + */ + public void printFields( PDDocument pdfDocument ) throws IOException + { + PDDocumentCatalog docCatalog = pdfDocument.getDocumentCatalog(); + PDAcroForm acroForm = docCatalog.getAcroForm(); + List fields = acroForm.getFields(); + Iterator fieldsIter = fields.iterator(); + + System.out.println(new Integer(fields.size()).toString() + " top-level fields were found on the form"); + + while( fieldsIter.hasNext()) + { + PDField field = (PDField)fieldsIter.next(); + processField(field, "|--", field.getPartialName()); + } + } + + private void processField(PDField field, String sLevel, String sParent) throws IOException + { + List kids = field.getKids(); + if(kids != null) + { + Iterator kidsIter = kids.iterator(); + if(!sParent.equals(field.getPartialName())) + { + sParent = sParent + "." + field.getPartialName(); + } + System.out.println(sLevel + sParent); + //System.out.println(sParent + " is of type " + field.getClass().getName()); + while(kidsIter.hasNext()) + { + Object pdfObj = kidsIter.next(); + if(pdfObj instanceof PDField) + { + PDField kid = (PDField)pdfObj; + processField(kid, "| " + sLevel, sParent); + } + } + } + else + { + String outputString = sLevel + sParent + "." + field.getPartialName() + " = " + field.getValue() + + ", type=" + field.getClass().getName(); + + System.out.println(outputString); + } + } + + /** + * This will read a PDF file and print out the form elements. + *
+ * see usage() for commandline + * + * @param args command line arguments + * + * @throws IOException If there is an error importing the FDF document. + * @throws CryptographyException If there is an error decrypting the document. + */ + public static void main(String[] args) throws IOException, CryptographyException + { + PDDocument pdf = null; + try + { + if( args.length != 1 ) + { + usage(); + } + else + { + pdf = PDDocument.load( args[0] ); + PrintFields exporter = new PrintFields(); + if( pdf.isEncrypted() ) + { + try + { + pdf.decrypt( "" ); + } + catch( InvalidPasswordException e ) + { + System.err.println( "Error: The document is encrypted." ); + usage(); + } + } + exporter.printFields( pdf ); + } + } + finally + { + if( pdf != null ) + { + pdf.close(); + } + } + } + /** + * This will print out a message telling how to use this example. + */ + private static void usage() + { + System.err.println( "usage: org.pdfbox.examples.fdf.PrintFields " ); + } +} \ No newline at end of file diff --git a/src/main/java/org/pdfbox/examples/fdf/SetField.java b/src/main/java/org/pdfbox/examples/fdf/SetField.java new file mode 100644 index 0000000..904feeb --- /dev/null +++ b/src/main/java/org/pdfbox/examples/fdf/SetField.java @@ -0,0 +1,128 @@ +/** + * Copyright (c) 2003-2004, www.pdfbox.org + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of pdfbox; nor the names of its + * contributors may be used to endorse or promote products derived from this + * software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON + * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + * http://www.pdfbox.org + * + */ +package org.pdfbox.examples.fdf; + +import java.io.IOException; + +import org.pdfbox.pdmodel.interactive.form.PDAcroForm; +import org.pdfbox.pdmodel.interactive.form.PDField; + +import org.pdfbox.pdmodel.PDDocument; +import org.pdfbox.pdmodel.PDDocumentCatalog; + +import org.pdfbox.exceptions.COSVisitorException; + +import org.pdfbox.examples.AbstractExample; + +/** + * This example will take a PDF document and set a FDF field in it. + * + * @author Ben Litchfield (ben@csh.rit.edu) + * @version $Revision: 1.6 $ + */ +public class SetField extends AbstractExample +{ + + /** + * This will set a single field in the document. + * + * @param pdfDocument The PDF to set the field in. + * @param name The name of the field to set. + * @param value The new value of the field. + * + * @throws IOException If there is an error setting the field. + */ + public void setField( PDDocument pdfDocument, String name, String value ) throws IOException + { + PDDocumentCatalog docCatalog = pdfDocument.getDocumentCatalog(); + PDAcroForm acroForm = docCatalog.getAcroForm(); + PDField field = acroForm.getField( name ); + if( field != null ) + { + field.setValue( value ); + } + else + { + System.err.println( "No field found with name:" + name ); + } + + } + + /** + * This will read a PDF file and set a field and then write it the pdf out again. + *
+ * see usage() for commandline + * + * @param args command line arguments + * + * @throws IOException If there is an error importing the FDF document. + * @throws COSVisitorException If there is an error writing the PDF. + */ + public static void main(String[] args) throws IOException, COSVisitorException + { + SetField setter = new SetField(); + setter.setField( args ); + } + + private void setField( String[] args ) throws IOException, COSVisitorException + { + PDDocument pdf = null; + try + { + if( args.length != 3 ) + { + usage(); + } + else + { + SetField example = new SetField(); + + pdf = PDDocument.load( args[0] ); + example.setField( pdf, args[1], args[2] ); + pdf.save( args[0] ); + } + } + finally + { + if( pdf != null ) + { + pdf.close(); + } + } + } + /** + * This will print out a message telling how to use this example. + */ + private static void usage() + { + System.err.println( "usage: org.pdfbox.examples.fdf.SetField " ); + } +} \ No newline at end of file diff --git a/src/main/java/org/pdfbox/examples/fdf/package.html b/src/main/java/org/pdfbox/examples/fdf/package.html new file mode 100644 index 0000000..5c80aca --- /dev/null +++ b/src/main/java/org/pdfbox/examples/fdf/package.html @@ -0,0 +1,9 @@ + + + + + + +These are examples that use the FDF features of a PDF document. + + diff --git a/src/main/java/org/pdfbox/examples/package.html b/src/main/java/org/pdfbox/examples/package.html new file mode 100644 index 0000000..fe059eb --- /dev/null +++ b/src/main/java/org/pdfbox/examples/package.html @@ -0,0 +1,9 @@ + + + + + + +The packages in this package will show how to use the PDFBox API. + + diff --git a/src/main/java/org/pdfbox/examples/pdmodel/AddJavascript.java b/src/main/java/org/pdfbox/examples/pdmodel/AddJavascript.java new file mode 100644 index 0000000..d04700e --- /dev/null +++ b/src/main/java/org/pdfbox/examples/pdmodel/AddJavascript.java @@ -0,0 +1,96 @@ +/** + * Copyright (c) 2005, www.pdfbox.org + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of pdfbox; nor the names of its + * contributors may be used to endorse or promote products derived from this + * software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON + * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + * http://www.pdfbox.org + * + */ +package org.pdfbox.examples.pdmodel; + +import org.pdfbox.pdmodel.PDDocument; +import org.pdfbox.pdmodel.interactive.action.type.PDActionJavaScript; + +import java.io.IOException; + +/** + * This is an example of how to set some javascript in the document. + * + * @author Ben Litchfield (ben@benlitchfield.com) + * @version $Revision: 1.2 $ + */ +public class AddJavascript +{ + private AddJavascript() + { + //static class, should not be instantiated. + } + + /** + * This will print the documents data. + * + * @param args The command line arguments. + * + * @throws Exception If there is an error parsing the document. + */ + public static void main( String[] args ) throws Exception + { + if( args.length != 2 ) + { + usage(); + } + else + { + PDDocument document = null; + try + { + document = PDDocument.load( args[0] ); + PDActionJavaScript javascript = new PDActionJavaScript( + "app.alert( {cMsg: 'PDFBox rocks!', nIcon: 3, nType: 0, cTitle: 'PDFBox Javascript example' } );"); + document.getDocumentCatalog().setOpenAction( javascript ); + if( document.isEncrypted() ) + { + throw new IOException( "Encrypted documents are not supported for this example" ); + } + document.save( args[1] ); + } + finally + { + if( document != null ) + { + document.close(); + } + } + } + } + + /** + * This will print the usage for this document. + */ + private static void usage() + { + System.err.println( "Usage: java org.pdfbox.examples.pdmodel.AddJavascript " ); + } +} \ No newline at end of file diff --git a/src/main/java/org/pdfbox/examples/pdmodel/AddMessageToEachPage.java b/src/main/java/org/pdfbox/examples/pdmodel/AddMessageToEachPage.java new file mode 100644 index 0000000..efb6ec1 --- /dev/null +++ b/src/main/java/org/pdfbox/examples/pdmodel/AddMessageToEachPage.java @@ -0,0 +1,148 @@ +/** + * Copyright (c) 2005, www.pdfbox.org + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of pdfbox; nor the names of its + * contributors may be used to endorse or promote products derived from this + * software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON + * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + * http://www.pdfbox.org + * + */ +package org.pdfbox.examples.pdmodel; + +import java.io.IOException; +import java.util.List; + +import org.pdfbox.exceptions.COSVisitorException; + +import org.pdfbox.pdmodel.PDDocument; +import org.pdfbox.pdmodel.PDPage; + +import org.pdfbox.pdmodel.common.PDRectangle; +import org.pdfbox.pdmodel.edit.PDPageContentStream; + +import org.pdfbox.pdmodel.font.PDFont; +import org.pdfbox.pdmodel.font.PDType1Font; + + +/** + * This is an example of how to add a message to every page + * in a pdf document. + * + * @author Ben Litchfield (ben@benlitchfield.com) + * @version $Revision: 1.2 $ + */ +public class AddMessageToEachPage +{ + /** + * Constructor. + */ + public AddMessageToEachPage() + { + super(); + } + + /** + * create the second sample document from the PDF file format specification. + * + * @param file The file to write the PDF to. + * @param message The message to write in the file. + * @param outfile The resulting PDF. + * + * @throws IOException If there is an error writing the data. + * @throws COSVisitorException If there is an error writing the PDF. + */ + public void doIt( String file, String message, String outfile ) throws IOException, COSVisitorException + { + // the document + PDDocument doc = null; + try + { + doc = PDDocument.load( file ); + + List allPages = doc.getDocumentCatalog().getAllPages(); + PDFont font = PDType1Font.HELVETICA_BOLD; + float fontSize = 12.0f; + + for( int i=0; i + * see usage() for commandline + * + * @param args Command line arguments. + */ + public static void main(String[] args) + { + AddMessageToEachPage app = new AddMessageToEachPage(); + try + { + if( args.length != 3 ) + { + app.usage(); + } + else + { + app.doIt( args[0], args[1], args[2] ); + } + } + catch (Exception e) + { + e.printStackTrace(); + } + } + + /** + * This will print out a message telling how to use this example. + */ + private void usage() + { + System.err.println( "usage: " + this.getClass().getName() + " " ); + } +} \ No newline at end of file diff --git a/src/main/java/org/pdfbox/examples/pdmodel/AddMetadataFromDocInfo.java b/src/main/java/org/pdfbox/examples/pdmodel/AddMetadataFromDocInfo.java new file mode 100644 index 0000000..35080cd --- /dev/null +++ b/src/main/java/org/pdfbox/examples/pdmodel/AddMetadataFromDocInfo.java @@ -0,0 +1,180 @@ +/** + * Copyright (c) 2005, www.pdfbox.org + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of pdfbox; nor the names of its + * contributors may be used to endorse or promote products derived from this + * software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON + * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + * http://www.pdfbox.org + * + */ +package org.pdfbox.examples.pdmodel; + +import org.pdfbox.pdmodel.PDDocument; +import org.pdfbox.pdmodel.PDDocumentCatalog; +import org.pdfbox.pdmodel.PDDocumentInformation; +import org.pdfbox.pdmodel.common.PDMetadata; +import org.pdfbox.util.DateConverter; + +import java.io.ByteArrayInputStream; +import java.util.Calendar; +import java.util.GregorianCalendar; + +/** + * This is an example on how to add metadata to a document. + * + * Usage: java org.pdfbox.examples.pdmodel.AddMetadataToDocument <input-pdf> <output-pdf> + * + * @author Ben Litchfield (ben@benlitchfield.com) + * @version $Revision: 1.2 $ + */ +public class AddMetadataFromDocInfo +{ + private static final String PADDING = + " " + + " " + + " " + + " " + + " " + + " " + + " " + + " " + + " " + + " " + + " " + + " "; + + + + private AddMetadataFromDocInfo() + { + //utility class + } + + /** + * This will print the documents data. + * + * @param args The command line arguments. + * + * @throws Exception If there is an error parsing the document. + */ + public static void main( String[] args ) throws Exception + { + if( args.length != 2 ) + { + usage(); + } + else + { + PDDocument document = null; + + try + { + document = PDDocument.load( args[0] ); + if( document.isEncrypted() ) + { + System.err.println( "Error: Cannot add metadata to encrypted document." ); + System.exit( 1 ); + } + PDDocumentCatalog catalog = document.getDocumentCatalog(); + PDDocumentInformation info = document.getDocumentInformation(); + + //Right now, PDFBox does not have any XMP library, so we will + //just consruct the XML by hand. + StringBuffer xmp= new StringBuffer(); + xmp.append( + "\n" + + "\n" + + "\n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " " + fixNull( info.getTitle() ) +"\n" + + " \n" + + " \n" + + " \n" + + " \n" + + " PDFBox.org\n" + + " \n" + + " \n" + + " \n" + + " \n" + + " " + fixNull( info.getSubject() ) +"\n" + + " \n" + + " \n" + + " \n" + + " \n" + + "\n" ); + + //xmp spec says we should put padding, so that the metadata can be appended to + //in place + xmp.append( PADDING ); + xmp.append( PADDING ); + xmp.append( PADDING ); + xmp.append( "\n" ); + ByteArrayInputStream mdInput = new ByteArrayInputStream( xmp.toString().getBytes() ); + PDMetadata metadataStream = new PDMetadata(document, mdInput, false ); + catalog.setMetadata( metadataStream ); + + + document.save( args[1] ); + } + finally + { + if( document != null ) + { + document.close(); + } + } + } + } + + private static String fixNull( String string ) + { + return string == null ? "" : string; + } + + private static String fixNull( Calendar cal ) + { + return cal == null ? "" : DateConverter.toISO8601( cal ); + } + + /** + * This will print the usage for this document. + */ + private static void usage() + { + System.err.println( "Usage: java org.pdfbox.examples.pdmodel.AddMetadata " ); + } +} \ No newline at end of file diff --git a/src/main/java/org/pdfbox/examples/pdmodel/CreateBlankPDF.java b/src/main/java/org/pdfbox/examples/pdmodel/CreateBlankPDF.java new file mode 100644 index 0000000..6d942ac --- /dev/null +++ b/src/main/java/org/pdfbox/examples/pdmodel/CreateBlankPDF.java @@ -0,0 +1,123 @@ +/** + * Copyright (c) 2003, www.pdfbox.org + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of pdfbox; nor the names of its + * contributors may be used to endorse or promote products derived from this + * software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON + * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + * http://www.pdfbox.org + * + */ +package org.pdfbox.examples.pdmodel; + +import java.io.FileOutputStream; +import java.io.IOException; + +import org.pdfbox.exceptions.COSVisitorException; + +import org.pdfbox.pdfwriter.COSWriter; + +import org.pdfbox.pdmodel.PDDocument; +import org.pdfbox.pdmodel.PDPage; + +/** + * This will create a blank PDF and write the contents to a file. + * + * usage: java org.pdfbox.examples.pdmodel.CreateBlankPDF <outputfile.pdf> + * + * @author Ben Litchfield (ben@csh.rit.edu) + * @version $Revision: 1.7 $ + */ +public class CreateBlankPDF +{ + + /** + * This will create a blank PDF and write the contents to a file. + * + * @param file The name of the file to write to. + * + * @throws IOException If there is an error writing the data. + * @throws COSVisitorException If there is an error while generating the document. + */ + public void create( String file ) throws IOException, COSVisitorException + { + PDDocument document = null; + FileOutputStream output = null; + COSWriter writer = null; + try + { + document = new PDDocument(); + //Every document requires at least one page, so we will add one + //blank page. + PDPage blankPage = new PDPage(); + document.addPage( blankPage ); + output = new FileOutputStream( file ); + writer = new COSWriter( output ); + writer.write( document.getDocument() ); + } + finally + { + if( writer != null ) + { + writer.close(); + } + if( output != null ) + { + output.close(); + } + if( document != null ) + { + document.close(); + } + } + } + + /** + * This will create a blank document. + * + * @param args The command line arguments. + * + * @throws IOException If there is an error writing the document data. + * @throws COSVisitorException If there is an error generating the data. + */ + public static void main( String[] args ) throws IOException, COSVisitorException + { + if( args.length != 1 ) + { + usage(); + } + else + { + CreateBlankPDF creator = new CreateBlankPDF(); + creator.create( args[0] ); + } + } + + /** + * This will print the usage of this class. + */ + private static void usage() + { + System.err.println( "usage: java org.pdfbox.examples.pdmodel.CreateBlankPDF " ); + } +} \ No newline at end of file diff --git a/src/main/java/org/pdfbox/examples/pdmodel/CreateBookmarks.java b/src/main/java/org/pdfbox/examples/pdmodel/CreateBookmarks.java new file mode 100644 index 0000000..88c09fb --- /dev/null +++ b/src/main/java/org/pdfbox/examples/pdmodel/CreateBookmarks.java @@ -0,0 +1,119 @@ +/** + * Copyright (c) 2005, www.pdfbox.org + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of pdfbox; nor the names of its + * contributors may be used to endorse or promote products derived from this + * software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON + * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + * http://www.pdfbox.org + * + */ +package org.pdfbox.examples.pdmodel; + +import org.pdfbox.pdmodel.PDDocument; +import org.pdfbox.pdmodel.PDPage; +import org.pdfbox.pdmodel.interactive.documentnavigation.destination.PDPageFitWidthDestination; +import org.pdfbox.pdmodel.interactive.documentnavigation.outline.PDDocumentOutline; +import org.pdfbox.pdmodel.interactive.documentnavigation.outline.PDOutlineItem; + +import java.util.List; + +/** + * This is an example on how to add bookmarks to a PDF document. It simply + * adds 1 bookmark for every page. + * + * Usage: java org.pdfbox.examples.pdmodel.CreateBookmarks <input-pdf> <output-pdf> + * + * @author Ben Litchfield (ben@csh.rit.edu) + * @version $Revision: 1.1 $ + */ +public class CreateBookmarks +{ + private CreateBookmarks() + { + //utility class + } + + /** + * This will print the documents data. + * + * @param args The command line arguments. + * + * @throws Exception If there is an error parsing the document. + */ + public static void main( String[] args ) throws Exception + { + if( args.length != 2 ) + { + usage(); + } + else + { + PDDocument document = null; + try + { + document = PDDocument.load( args[0] ); + if( document.isEncrypted() ) + { + System.err.println( "Error: Cannot add bookmarks to encrypted document." ); + System.exit( 1 ); + } + PDDocumentOutline outline = new PDDocumentOutline(); + document.getDocumentCatalog().setDocumentOutline( outline ); + PDOutlineItem pagesOutline = new PDOutlineItem(); + pagesOutline.setTitle( "All Pages" ); + outline.appendChild( pagesOutline ); + List pages = document.getDocumentCatalog().getAllPages(); + for( int i=0; i " ); + } +} \ No newline at end of file diff --git a/src/main/java/org/pdfbox/examples/pdmodel/EmbeddedFiles.java b/src/main/java/org/pdfbox/examples/pdmodel/EmbeddedFiles.java new file mode 100644 index 0000000..86bc447 --- /dev/null +++ b/src/main/java/org/pdfbox/examples/pdmodel/EmbeddedFiles.java @@ -0,0 +1,170 @@ +/** + * Copyright (c) 2004, www.pdfbox.org + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of pdfbox; nor the names of its + * contributors may be used to endorse or promote products derived from this + * software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON + * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + * http://www.pdfbox.org + * + */ +package org.pdfbox.examples.pdmodel; + +import java.io.ByteArrayInputStream; +import java.io.IOException; +import java.util.GregorianCalendar; +import java.util.HashMap; +import java.util.Map; + +import org.pdfbox.exceptions.COSVisitorException; + +import org.pdfbox.pdmodel.PDDocument; +import org.pdfbox.pdmodel.PDDocumentNameDictionary; +import org.pdfbox.pdmodel.PDEmbeddedFilesNameTreeNode; +import org.pdfbox.pdmodel.PDPage; + +import org.pdfbox.pdmodel.common.filespecification.PDComplexFileSpecification; +import org.pdfbox.pdmodel.common.filespecification.PDEmbeddedFile; +import org.pdfbox.pdmodel.edit.PDPageContentStream; + +import org.pdfbox.pdmodel.font.PDFont; +import org.pdfbox.pdmodel.font.PDType1Font; + + +/** + * This is an example that creates a simple document and embeds a file into it.. + * + * @author Ben Litchfield (ben@benlitchfield.com) + * @version $Revision: 1.1 $ + */ +public class EmbeddedFiles +{ + /** + * Constructor. + */ + public EmbeddedFiles() + { + super(); + } + + /** + * create the second sample document from the PDF file format specification. + * + * @param file The file to write the PDF to. + * + * @throws IOException If there is an error writing the data. + * @throws COSVisitorException If there is an error writing the PDF. + */ + public void doIt( String file) throws IOException, COSVisitorException + { + // the document + PDDocument doc = null; + try + { + doc = new PDDocument(); + + PDPage page = new PDPage(); + doc.addPage( page ); + PDFont font = PDType1Font.HELVETICA_BOLD; + + PDPageContentStream contentStream = new PDPageContentStream(doc, page); + contentStream.beginText(); + contentStream.setFont( font, 12 ); + contentStream.moveTextPositionByAmount( 100, 700 ); + contentStream.drawString( "Go to Document->File Attachments to View Embedded Files" ); + contentStream.endText(); + contentStream.close(); + + //embedded files are stored in a named tree + PDEmbeddedFilesNameTreeNode efTree = new PDEmbeddedFilesNameTreeNode(); + + + //first create the file specification, which holds the embedded file + PDComplexFileSpecification fs = new PDComplexFileSpecification(); + fs.setFile( "Test.txt" ); + //create a dummy file stream, this would probably normally be a FileInputStream + byte[] data = "This is the contents of the embedded file".getBytes(); + ByteArrayInputStream fakeFile = + new ByteArrayInputStream( data ); + PDEmbeddedFile ef = new PDEmbeddedFile(doc, fakeFile ); + //now lets some of the optional parameters + ef.setSubtype( "test/plain" ); + ef.setSize( data.length ); + ef.setCreationDate( new GregorianCalendar() ); + fs.setEmbeddedFile( ef ); + + //now add the entry to the embedded file tree and set in the document. + Map efMap = new HashMap(); + efMap.put( "My first attachment", fs ); + efTree.setNames( efMap ); + PDDocumentNameDictionary names = new PDDocumentNameDictionary( doc.getDocumentCatalog() ); + names.setEmbeddedFiles( efTree ); + doc.getDocumentCatalog().setNames( names ); + + + doc.save( file ); + } + finally + { + if( doc != null ) + { + doc.close(); + } + } + } + + /** + * This will create a hello world PDF document with an embedded file. + *
+ * see usage() for commandline + * + * @param args Command line arguments. + */ + public static void main(String[] args) + { + EmbeddedFiles app = new EmbeddedFiles(); + try + { + if( args.length != 1 ) + { + app.usage(); + } + else + { + app.doIt( args[0] ); + } + } + catch (Exception e) + { + e.printStackTrace(); + } + } + + /** + * This will print out a message telling how to use this example. + */ + private void usage() + { + System.err.println( "usage: " + this.getClass().getName() + " " ); + } +} \ No newline at end of file diff --git a/src/main/java/org/pdfbox/examples/pdmodel/HelloWorld.java b/src/main/java/org/pdfbox/examples/pdmodel/HelloWorld.java new file mode 100644 index 0000000..9bceca7 --- /dev/null +++ b/src/main/java/org/pdfbox/examples/pdmodel/HelloWorld.java @@ -0,0 +1,137 @@ +/** + * Copyright (c) 2004, www.pdfbox.org + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of pdfbox; nor the names of its + * contributors may be used to endorse or promote products derived from this + * software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON + * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + * http://www.pdfbox.org + * + */ +package org.pdfbox.examples.pdmodel; + +import java.io.IOException; + +import org.pdfbox.exceptions.COSVisitorException; + +import org.pdfbox.pdmodel.PDDocument; +import org.pdfbox.pdmodel.PDPage; + +import org.pdfbox.pdmodel.edit.PDPageContentStream; + +import org.pdfbox.pdmodel.font.PDFont; +import org.pdfbox.pdmodel.font.PDType1Font; + + +/** + * This is an example that creates a simple document. + * + * The example is taken from the pdf file format specification. + * + * @author Ben Litchfield (ben@csh.rit.edu) + * @version $Revision: 1.5 $ + */ +public class HelloWorld +{ + /** + * Constructor. + */ + public HelloWorld() + { + super(); + } + + /** + * create the second sample document from the PDF file format specification. + * + * @param file The file to write the PDF to. + * @param message The message to write in the file. + * + * @throws IOException If there is an error writing the data. + * @throws COSVisitorException If there is an error writing the PDF. + */ + public void doIt( String file, String message) throws IOException, COSVisitorException + { + // the document + PDDocument doc = null; + try + { + doc = new PDDocument(); + + PDPage page = new PDPage(); + doc.addPage( page ); + PDFont font = PDType1Font.HELVETICA_BOLD; + + PDPageContentStream contentStream = new PDPageContentStream(doc, page); + contentStream.beginText(); + contentStream.setFont( font, 12 ); + contentStream.moveTextPositionByAmount( 100, 700 ); + contentStream.drawString( message ); + contentStream.endText(); + contentStream.close(); + doc.save( file ); + } + finally + { + if( doc != null ) + { + doc.close(); + } + } + } + + /** + * This will create a hello world PDF document. + *
+ * see usage() for commandline + * + * @param args Command line arguments. + */ + public static void main(String[] args) + { + HelloWorld app = new HelloWorld(); + try + { + if( args.length != 2 ) + { + app.usage(); + } + else + { + app.doIt( args[0], args[1] ); + } + } + catch (Exception e) + { + e.printStackTrace(); + } + } + + /** + * This will print out a message telling how to use this example. + */ + private void usage() + { + System.err.println( "usage: " + this.getClass().getName() + " " ); + } +} \ No newline at end of file diff --git a/src/main/java/org/pdfbox/examples/pdmodel/HelloWorldTTF.java b/src/main/java/org/pdfbox/examples/pdmodel/HelloWorldTTF.java new file mode 100644 index 0000000..16b1423 --- /dev/null +++ b/src/main/java/org/pdfbox/examples/pdmodel/HelloWorldTTF.java @@ -0,0 +1,134 @@ +/** + * Copyright (c) 2005, www.pdfbox.org + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of pdfbox; nor the names of its + * contributors may be used to endorse or promote products derived from this + * software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON + * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + * http://www.pdfbox.org + * + */ + +package org.pdfbox.examples.pdmodel; + +import java.io.IOException; + +import org.pdfbox.exceptions.COSVisitorException; +import org.pdfbox.pdmodel.PDDocument; +import org.pdfbox.pdmodel.PDPage; +import org.pdfbox.pdmodel.edit.PDPageContentStream; +import org.pdfbox.pdmodel.font.PDFont; +import org.pdfbox.pdmodel.font.PDTrueTypeFont; + +/** + * This is an example that creates a simple document + * with a ttf-font. + * + * @author Michael Niedermair + * @version $Revision: 1.2 $ + */ +public class HelloWorldTTF +{ + + /** + * create the second sample document from the PDF file format specification. + * + * @param file The file to write the PDF to. + * @param message The message to write in the file. + * @param fontfile The ttf-font file. + * + * @throws IOException If there is an error writing the data. + * @throws COSVisitorException If there is an error writing the PDF. + */ + public void doIt(final String file, final String message, + final String fontfile) throws IOException, COSVisitorException + { + + // the document + PDDocument doc = null; + try + { + doc = new PDDocument(); + + PDPage page = new PDPage(); + doc.addPage(page); + PDFont font = PDTrueTypeFont.loadTTF(doc, fontfile); + + PDPageContentStream contentStream = new PDPageContentStream(doc, + page); + contentStream.beginText(); + contentStream.setFont(font, 12); + contentStream.moveTextPositionByAmount(100, 700); + contentStream.drawString(message); + contentStream.endText(); + contentStream.close(); + doc.save(file); + System.out.println(file + " created!"); + } + finally + { + if (doc != null) + { + doc.close(); + } + } + } + + /** + * This will create a hello world PDF document + * with a ttf-font. + *
+ * see usage() for commandline + * + * @param args Command line arguments. + */ + public static void main(String[] args) + { + + HelloWorldTTF app = new HelloWorldTTF(); + try + { + if (args.length != 3) + { + app.usage(); + } + else + { + app.doIt(args[0], args[1], args[2]); + } + } + catch (Exception e) + { + e.printStackTrace(); + } + } + + /** + * This will print out a message telling how to use this example. + */ + private void usage() + { + System.err.println("usage: " + this.getClass().getName() + + " "); + } +} \ No newline at end of file diff --git a/src/main/java/org/pdfbox/examples/pdmodel/HelloWorldType1AfmPfb.java b/src/main/java/org/pdfbox/examples/pdmodel/HelloWorldType1AfmPfb.java new file mode 100644 index 0000000..2457a2e --- /dev/null +++ b/src/main/java/org/pdfbox/examples/pdmodel/HelloWorldType1AfmPfb.java @@ -0,0 +1,134 @@ +/** + * Copyright (c) 2005, www.pdfbox.org + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of pdfbox; nor the names of its + * contributors may be used to endorse or promote products derived from this + * software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON + * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + * http://www.pdfbox.org + * + */ + +package org.pdfbox.examples.pdmodel; + +import java.io.IOException; + +import org.pdfbox.exceptions.COSVisitorException; +import org.pdfbox.pdmodel.PDDocument; +import org.pdfbox.pdmodel.PDPage; +import org.pdfbox.pdmodel.edit.PDPageContentStream; +import org.pdfbox.pdmodel.font.PDFont; +import org.pdfbox.pdmodel.font.PDType1AfmPfbFont; + +/** + * This is an example that creates a simple document + * with a Type 1 font (afm + pfb). + * + * @author Michael Niedermair + * @version $Revision: 1.2 $ + */ +public class HelloWorldType1AfmPfb +{ + + /** + * create the second sample document from the PDF file format specification. + * + * @param file The file to write the PDF to. + * @param message The message to write in the file. + * @param fontfile The ttf-font file. + * + * @throws IOException If there is an error writing the data. + * @throws COSVisitorException If there is an error writing the PDF. + */ + public void doIt(final String file, final String message, + final String fontfile) throws IOException, COSVisitorException + { + + // the document + PDDocument doc = null; + try + { + doc = new PDDocument(); + + PDPage page = new PDPage(); + doc.addPage(page); + PDFont font = new PDType1AfmPfbFont(doc,fontfile); + + PDPageContentStream contentStream = new PDPageContentStream(doc, + page); + contentStream.beginText(); + contentStream.setFont(font, 12); + contentStream.moveTextPositionByAmount(100, 700); + contentStream.drawString(message); + contentStream.endText(); + contentStream.close(); + doc.save(file); + System.out.println(file + " created!"); + } + finally + { + if (doc != null) + { + doc.close(); + } + } + } + + /** + * This will create a hello world PDF document + * with a ttf-font. + *
+ * see usage() for commandline + * + * @param args Command line arguments. + */ + public static void main(String[] args) + { + + HelloWorldType1AfmPfb app = new HelloWorldType1AfmPfb(); + try + { + if (args.length != 3) + { + app.usage(); + } + else + { + app.doIt(args[0], args[1], args[2]); + } + } + catch (Exception e) + { + e.printStackTrace(); + } + } + + /** + * This will print out a message telling how to use this example. + */ + private void usage() + { + System.err.println("usage: " + this.getClass().getName() + + " "); + } +} \ No newline at end of file diff --git a/src/main/java/org/pdfbox/examples/pdmodel/ImageToPDF.java b/src/main/java/org/pdfbox/examples/pdmodel/ImageToPDF.java new file mode 100644 index 0000000..9faf79d --- /dev/null +++ b/src/main/java/org/pdfbox/examples/pdmodel/ImageToPDF.java @@ -0,0 +1,146 @@ +/** + * Copyright (c) 2005, www.pdfbox.org + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of pdfbox; nor the names of its + * contributors may be used to endorse or promote products derived from this + * software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON + * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + * http://www.pdfbox.org + * + */ +package org.pdfbox.examples.pdmodel; + +import java.io.File; +import java.io.FileInputStream; +import java.io.IOException; +import java.io.RandomAccessFile; + +import org.pdfbox.exceptions.COSVisitorException; + +import org.pdfbox.pdmodel.PDDocument; +import org.pdfbox.pdmodel.PDPage; + +import org.pdfbox.pdmodel.edit.PDPageContentStream; + +import org.pdfbox.pdmodel.graphics.xobject.PDCcitt; +import org.pdfbox.pdmodel.graphics.xobject.PDJpeg; +import org.pdfbox.pdmodel.graphics.xobject.PDXObjectImage; + + +/** + * This is an example that creates a simple document. + * + * The example is taken from the pdf file format specification. + * + * @author Ben Litchfield (ben@csh.rit.edu) + * @version $Revision: 1.5 $ + */ +public class ImageToPDF +{ + + /** + * create the second sample document from the PDF file format specification. + * + * @param file The file to write the PDF to. + * @param image The filename of the image to put in the PDF. + * + * @throws IOException If there is an error writing the data. + * @throws COSVisitorException If there is an error writing the PDF. + */ + public void createPDFFromImage( String file, String image) throws IOException, COSVisitorException + { + // the document + PDDocument doc = null; + try + { + doc = new PDDocument(); + + PDPage page = new PDPage(); + doc.addPage( page ); + + PDXObjectImage ximage = null; + if( image.toLowerCase().endsWith( ".jpg" ) ) + { + ximage = new PDJpeg(doc, new FileInputStream( image ) ); + } + else if (image.toLowerCase().endsWith(".tif") || image.toLowerCase().endsWith(".tiff")) + { + ximage = new PDCcitt(doc, new RandomAccessFile(new File(image),"r")); + } + else + { + //BufferedImage awtImage = ImageIO.read( new File( image ) ); + //ximage = new PDPixelMap(doc, awtImage); + throw new IOException( "Image type not supported:" + image ); + } + PDPageContentStream contentStream = new PDPageContentStream(doc, page); + + contentStream.drawImage( ximage, 20, 20 ); + + contentStream.close(); + doc.save( file ); + } + finally + { + if( doc != null ) + { + doc.close(); + } + } + } + + /** + * This will create a PDF document with a single image on it. + *
+ * see usage() for commandline + * + * @param args Command line arguments. + */ + public static void main(String[] args) + { + ImageToPDF app = new ImageToPDF(); + try + { + if( args.length != 2 ) + { + app.usage(); + } + else + { + app.createPDFFromImage( args[0], args[1] ); + } + } + catch (Exception e) + { + e.printStackTrace(); + } + } + + /** + * This will print out a message telling how to use this example. + */ + private void usage() + { + System.err.println( "usage: " + this.getClass().getName() + " " ); + } +} \ No newline at end of file diff --git a/src/main/java/org/pdfbox/examples/pdmodel/PrintBookmarks.java b/src/main/java/org/pdfbox/examples/pdmodel/PrintBookmarks.java new file mode 100644 index 0000000..0a1a647 --- /dev/null +++ b/src/main/java/org/pdfbox/examples/pdmodel/PrintBookmarks.java @@ -0,0 +1,142 @@ +/** + * Copyright (c) 2005, www.pdfbox.org + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of pdfbox; nor the names of its + * contributors may be used to endorse or promote products derived from this + * software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON + * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + * http://www.pdfbox.org + * + */ +package org.pdfbox.examples.pdmodel; + +import org.pdfbox.exceptions.InvalidPasswordException; + +import org.pdfbox.pdfparser.PDFParser; + +import org.pdfbox.pdmodel.PDDocument; +import org.pdfbox.pdmodel.interactive.documentnavigation.outline.PDDocumentOutline; +import org.pdfbox.pdmodel.interactive.documentnavigation.outline.PDOutlineItem; +import org.pdfbox.pdmodel.interactive.documentnavigation.outline.PDOutlineNode; + +import java.io.FileInputStream; +import java.io.IOException; + +/** + * This is an example on how to access the bookmarks that are part of a pdf document. + * + * Usage: java org.pdfbox.examples.pdmodel.PrintBookmarks <input-pdf> + * + * @author Ben Litchfield (ben@csh.rit.edu) + * @version $Revision: 1.1 $ + */ +public class PrintBookmarks +{ + /** + * This will print the documents data. + * + * @param args The command line arguments. + * + * @throws Exception If there is an error parsing the document. + */ + public static void main( String[] args ) throws Exception + { + if( args.length != 1 ) + { + usage(); + } + else + { + PDDocument document = null; + FileInputStream file = null; + try + { + file = new FileInputStream( args[0] ); + PDFParser parser = new PDFParser( file ); + parser.parse(); + document = parser.getPDDocument(); + if( document.isEncrypted() ) + { + try + { + document.decrypt( "" ); + } + catch( InvalidPasswordException e ) + { + System.err.println( "Error: Document is encrypted with a password." ); + System.exit( 1 ); + } + } + PrintBookmarks meta = new PrintBookmarks(); + PDDocumentOutline outline = document.getDocumentCatalog().getDocumentOutline(); + if( outline != null ) + { + meta.printBookmark( outline, "" ); + } + else + { + System.out.println( "This document does not contain any bookmarks" ); + } + } + finally + { + if( file != null ) + { + file.close(); + } + if( document != null ) + { + document.close(); + } + } + } + } + + /** + * This will print the usage for this document. + */ + private static void usage() + { + System.err.println( "Usage: java org.pdfbox.examples.pdmodel.PrintBookmarks " ); + } + + /** + * This will print the documents bookmarks to System.out. + * + * @param bookmark The bookmark to print out. + * @param indentation A pretty printing parameter + * + * @throws IOException If there is an error getting the page count. + */ + public void printBookmark( PDOutlineNode bookmark, String indentation ) throws IOException + { + PDOutlineItem current = bookmark.getFirstChild(); + while( current != null ) + { + System.out.println( indentation + current.getTitle() ); + printBookmark( current, indentation + " " ); + current = current.getNextSibling(); + } + + } +} \ No newline at end of file diff --git a/src/main/java/org/pdfbox/examples/pdmodel/PrintDocumentMetaData.java b/src/main/java/org/pdfbox/examples/pdmodel/PrintDocumentMetaData.java new file mode 100644 index 0000000..c096113 --- /dev/null +++ b/src/main/java/org/pdfbox/examples/pdmodel/PrintDocumentMetaData.java @@ -0,0 +1,165 @@ +/** + * Copyright (c) 2003-2005, www.pdfbox.org + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of pdfbox; nor the names of its + * contributors may be used to endorse or promote products derived from this + * software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON + * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + * http://www.pdfbox.org + * + */ +package org.pdfbox.examples.pdmodel; + +import org.pdfbox.exceptions.InvalidPasswordException; + +import org.pdfbox.pdfparser.PDFParser; + +import org.pdfbox.pdmodel.PDDocument; +import org.pdfbox.pdmodel.PDDocumentCatalog; +import org.pdfbox.pdmodel.PDDocumentInformation; +import org.pdfbox.pdmodel.common.PDMetadata; + +import java.io.FileInputStream; +import java.io.IOException; + +import java.text.SimpleDateFormat; + +import java.util.Calendar; + +/** + * This is an example on how to get a documents metadata information. + * + * Usage: java org.pdfbox.examples.pdmodel.PrintDocumentMetaData <input-pdf> + * + * @author Ben Litchfield (ben@benlitchfield.com) + * @version $Revision: 1.10 $ + */ +public class PrintDocumentMetaData +{ + /** + * This will print the documents data. + * + * @param args The command line arguments. + * + * @throws Exception If there is an error parsing the document. + */ + public static void main( String[] args ) throws Exception + { + if( args.length != 1 ) + { + usage(); + } + else + { + PDDocument document = null; + FileInputStream file = null; + try + { + file = new FileInputStream( args[0] ); + PDFParser parser = new PDFParser( file ); + parser.parse(); + document = parser.getPDDocument(); + if( document.isEncrypted() ) + { + try + { + document.decrypt( "" ); + } + catch( InvalidPasswordException e ) + { + System.err.println( "Error: Document is encrypted with a password." ); + System.exit( 1 ); + } + } + PrintDocumentMetaData meta = new PrintDocumentMetaData(); + meta.printMetadata( document ); + } + finally + { + if( file != null ) + { + file.close(); + } + if( document != null ) + { + document.close(); + } + } + } + } + + /** + * This will print the usage for this document. + */ + private static void usage() + { + System.err.println( "Usage: java org.pdfbox.examples.pdmodel.PrintDocumentMetaData " ); + } + + /** + * This will print the documents data to System.out. + * + * @param document The document to get the metadata from. + * + * @throws IOException If there is an error getting the page count. + */ + public void printMetadata( PDDocument document ) throws IOException + { + PDDocumentInformation info = document.getDocumentInformation(); + PDDocumentCatalog cat = document.getDocumentCatalog(); + PDMetadata metadata = cat.getMetadata(); + System.out.println( "Page Count=" + document.getNumberOfPages() ); + System.out.println( "Title=" + info.getTitle() ); + System.out.println( "Author=" + info.getAuthor() ); + System.out.println( "Subject=" + info.getSubject() ); + System.out.println( "Keywords=" + info.getKeywords() ); + System.out.println( "Creator=" + info.getCreator() ); + System.out.println( "Producer=" + info.getProducer() ); + System.out.println( "Creation Date=" + formatDate( info.getCreationDate() ) ); + System.out.println( "Modification Date=" + formatDate( info.getModificationDate() ) ); + System.out.println( "Trapped=" + info.getTrapped() ); + if( metadata != null ) + { + System.out.println( "Metadata=" + metadata.getInputStreamAsString() ); + } + } + + /** + * This will format a date object. + * + * @param date The date to format. + * + * @return A string representation of the date. + */ + private String formatDate( Calendar date ) + { + String retval = null; + if( date != null ) + { + SimpleDateFormat formatter = new SimpleDateFormat(); + retval = formatter.format( date.getTime() ); + } + + return retval; + } +} \ No newline at end of file diff --git a/src/main/java/org/pdfbox/examples/pdmodel/RemoveFirstPage.java b/src/main/java/org/pdfbox/examples/pdmodel/RemoveFirstPage.java new file mode 100644 index 0000000..2b7242b --- /dev/null +++ b/src/main/java/org/pdfbox/examples/pdmodel/RemoveFirstPage.java @@ -0,0 +1,98 @@ +/** + * Copyright (c) 2005, www.pdfbox.org + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of pdfbox; nor the names of its + * contributors may be used to endorse or promote products derived from this + * software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON + * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + * http://www.pdfbox.org + * + */ +package org.pdfbox.examples.pdmodel; + +import org.pdfbox.pdmodel.PDDocument; + +import java.io.IOException; + +/** + * This is an example on how to remove pages from a PDF document. + * + * @author Ben Litchfield (ben@benlitchfield.com) + * @version $Revision: 1.4 $ + */ +public class RemoveFirstPage +{ + private RemoveFirstPage() + { + //utility class, should not be instantiated. + } + + /** + * This will print the documents data. + * + * @param args The command line arguments. + * + * @throws Exception If there is an error parsing the document. + */ + public static void main( String[] args ) throws Exception + { + if( args.length != 2 ) + { + usage(); + } + else + { + PDDocument document = null; + try + { + document = PDDocument.load( args[0] ); + if( document.isEncrypted() ) + { + throw new IOException( "Encrypted documents are not supported for this example" ); + } + if( document.getNumberOfPages() <= 1 ) + { + throw new IOException( "Error: A PDF document must have at least one page, " + + "cannot remove the last page!"); + } + document.removePage( 0 ); + document.save( args[1] ); + } + finally + { + if( document != null ) + { + document.close(); + } + } + } + } + + /** + * This will print the usage for this document. + */ + private static void usage() + { + System.err.println( "Usage: java org.pdfbox.examples.pdmodel.RemoveFirstPage " ); + } +} \ No newline at end of file diff --git a/src/main/java/org/pdfbox/examples/pdmodel/ReplaceString.java b/src/main/java/org/pdfbox/examples/pdmodel/ReplaceString.java new file mode 100644 index 0000000..bbf8688 --- /dev/null +++ b/src/main/java/org/pdfbox/examples/pdmodel/ReplaceString.java @@ -0,0 +1,186 @@ +/** + * Copyright (c) 2005, www.pdfbox.org + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of pdfbox; nor the names of its + * contributors may be used to endorse or promote products derived from this + * software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON + * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + * http://www.pdfbox.org + * + */ +package org.pdfbox.examples.pdmodel; + +import java.io.IOException; +import java.io.OutputStream; +import java.util.List; + +import org.pdfbox.cos.COSArray; +import org.pdfbox.cos.COSString; +import org.pdfbox.exceptions.COSVisitorException; + +import org.pdfbox.pdfparser.PDFStreamParser; +import org.pdfbox.pdfwriter.ContentStreamWriter; +import org.pdfbox.pdmodel.PDDocument; +import org.pdfbox.pdmodel.PDPage; + +import org.pdfbox.pdmodel.common.PDStream; + +import org.pdfbox.util.PDFOperator; + + +/** + * This is an example that will replace a string in a PDF with a new one. + * + * The example is taken from the pdf file format specification. + * + * @author Ben Litchfield (ben@benlitchfield.com) + * @version $Revision: 1.2 $ + */ +public class ReplaceString +{ + /** + * Constructor. + */ + public ReplaceString() + { + super(); + } + + /** + * Locate a string in a PDF and replace it with a new string. + * + * @param inputFile The PDF to open. + * @param outputFile The PDF to write to. + * @param strToFind The string to find in the PDF document. + * @param message The message to write in the file. + * + * @throws IOException If there is an error writing the data. + * @throws COSVisitorException If there is an error writing the PDF. + */ + public void doIt( String inputFile, String outputFile, String strToFind, String message) + throws IOException, COSVisitorException + { + // the document + PDDocument doc = null; + try + { + doc = PDDocument.load( inputFile ); + List pages = doc.getDocumentCatalog().getAllPages(); + for( int i=0; i + * see usage() for commandline + * + * @param args Command line arguments. + */ + public static void main(String[] args) + { + ReplaceString app = new ReplaceString(); + try + { + if( args.length != 4 ) + { + app.usage(); + } + else + { + app.doIt( args[0], args[1], args[2], args[3] ); + } + } + catch (Exception e) + { + e.printStackTrace(); + } + } + + /** + * This will print out a message telling how to use this example. + */ + private void usage() + { + System.err.println( "usage: " + this.getClass().getName() + + " " ); + } +} \ No newline at end of file diff --git a/src/main/java/org/pdfbox/examples/pdmodel/RubberStamp.java b/src/main/java/org/pdfbox/examples/pdmodel/RubberStamp.java new file mode 100644 index 0000000..158e0f8 --- /dev/null +++ b/src/main/java/org/pdfbox/examples/pdmodel/RubberStamp.java @@ -0,0 +1,113 @@ +/** + * Copyright (c) 2005, www.pdfbox.org + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of pdfbox; nor the names of its + * contributors may be used to endorse or promote products derived from this + * software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON + * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + * http://www.pdfbox.org + * + */ +package org.pdfbox.examples.pdmodel; + +import org.pdfbox.pdmodel.PDDocument; +import org.pdfbox.pdmodel.PDPage; +import org.pdfbox.pdmodel.common.PDRectangle; +import org.pdfbox.pdmodel.interactive.annotation.PDAnnotationRubberStamp; + +import java.io.IOException; +import java.util.ArrayList; +import java.util.List; + +/** + * This is an example on how to add annotations to pages of a PDF document. + * + * @author Paul King + * @version $Revision: 1.1 $ + */ +public class RubberStamp +{ + private RubberStamp() + { + //utility class, should not be instantiated. + } + + /** + * This will print the documents data. + * + * @param args The command line arguments. + * + * @throws Exception If there is an error parsing the document. + */ + public static void main( String[] args ) throws Exception + { + if( args.length != 2 ) + { + usage(); + } + else + { + PDDocument document = null; + try + { + document = PDDocument.load( args[0] ); + if( document.isEncrypted() ) + { + throw new IOException( "Encrypted documents are not supported for this example" ); + } + List allpages = new ArrayList(); + document.getDocumentCatalog().getPages().getAllKids(allpages); + + for (int i=0; i < allpages.size(); i++) + { + PDPage apage = (PDPage) allpages.get(i); + List annotations = apage.getAnnotations(); + + PDAnnotationRubberStamp rs = new PDAnnotationRubberStamp(); + rs.setName(PDAnnotationRubberStamp.NAME_TOP_SECRET); + rs.setRectangle(new PDRectangle(100,100)); + rs.setContents("A top secret note"); + + annotations.add(rs); + } + + document.save( args[1] ); + } + finally + { + if( document != null ) + { + document.close(); + } + } + } + } + + /** + * This will print the usage for this document. + */ + private static void usage() + { + System.err.println( "Usage: java org.pdfbox.examples.pdmodel.RubberStamp " ); + } +} \ No newline at end of file diff --git a/src/main/java/org/pdfbox/examples/pdmodel/ShowColorBoxes.java b/src/main/java/org/pdfbox/examples/pdmodel/ShowColorBoxes.java new file mode 100644 index 0000000..f936642 --- /dev/null +++ b/src/main/java/org/pdfbox/examples/pdmodel/ShowColorBoxes.java @@ -0,0 +1,135 @@ +/** + * Copyright (c) 2004, www.pdfbox.org + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of pdfbox; nor the names of its + * contributors may be used to endorse or promote products derived from this + * software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON + * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + * http://www.pdfbox.org + * + */ +package org.pdfbox.examples.pdmodel; + +import java.awt.Color; +import java.io.IOException; + +import org.pdfbox.exceptions.COSVisitorException; + +import org.pdfbox.pdmodel.PDDocument; +import org.pdfbox.pdmodel.PDPage; + +import org.pdfbox.pdmodel.edit.PDPageContentStream; + +/** + * This is an example that creates a simple document. + * + * The example is taken from the pdf file format specification. + * + * @author Ben Litchfield (ben@csh.rit.edu) + * @version $Revision: 1.1 $ + */ +public class ShowColorBoxes +{ + /** + * Constructor. + */ + public ShowColorBoxes() + { + super(); + } + + /** + * create the second sample document from the PDF file format specification. + * + * @param file The file to write the PDF to. + * + * @throws IOException If there is an error writing the data. + * @throws COSVisitorException If there is an error writing the PDF. + */ + public void doIt( String file) throws IOException, COSVisitorException + { + // the document + PDDocument doc = null; + try + { + doc = new PDDocument(); + + PDPage page = new PDPage(); + doc.addPage( page ); + + PDPageContentStream contentStream = new PDPageContentStream(doc, page); + //first fill the entire background with cyan + contentStream.setNonStrokingColor( Color.CYAN ); + contentStream.fillRect( 0,0, page.findMediaBox().getWidth(), page.findMediaBox().getHeight() ); + + //then draw a red box in the lower left hand corner + contentStream.setNonStrokingColor( Color.RED ); + contentStream.fillRect( 10, 10, 100, 100 ); + + contentStream.close(); + doc.save( file ); + } + finally + { + if( doc != null ) + { + doc.close(); + } + } + } + + /** + * This will create a hello world PDF document. + *
+ * see usage() for commandline + * + * @param args Command line arguments. + */ + public static void main(String[] args) + { + ShowColorBoxes app = new ShowColorBoxes(); + try + { + if( args.length != 1 ) + { + app.usage(); + } + else + { + app.doIt( args[0] ); + } + } + catch (Exception e) + { + e.printStackTrace(); + } + } + + /** + * This will print out a message telling how to use this example. + */ + private void usage() + { + System.err.println( "usage: " + this.getClass().getName() + " " ); + } +} \ No newline at end of file diff --git a/src/main/java/org/pdfbox/examples/pdmodel/package.html b/src/main/java/org/pdfbox/examples/pdmodel/package.html new file mode 100644 index 0000000..b9beefa --- /dev/null +++ b/src/main/java/org/pdfbox/examples/pdmodel/package.html @@ -0,0 +1,9 @@ + + + + + + +These examples show how to use the classes in the PDModel package. + + diff --git a/src/main/java/org/pdfbox/examples/persistence/AppendAndFillDoc.java b/src/main/java/org/pdfbox/examples/persistence/AppendAndFillDoc.java new file mode 100644 index 0000000..01b8cf6 --- /dev/null +++ b/src/main/java/org/pdfbox/examples/persistence/AppendAndFillDoc.java @@ -0,0 +1,282 @@ +/** + * Copyright (c) 2003, www.pdfbox.org + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of pdfbox; nor the names of its + * contributors may be used to endorse or promote products derived from this + * software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON + * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + * http://www.pdfbox.org + * + */ +package org.pdfbox.examples.persistence; + +import java.io.IOException; +import java.io.OutputStream; +import java.io.FileOutputStream; +import java.io.InputStream; +import java.io.FileInputStream; + +import java.util.Iterator; + +import org.pdfbox.pdfparser.PDFParser; + +import org.pdfbox.pdfwriter.COSWriter; + +import org.pdfbox.cos.COSDocument; +import org.pdfbox.cos.COSString; +import org.pdfbox.cos.COSBase; +import org.pdfbox.cos.COSDictionary; +import org.pdfbox.cos.COSObject; +import org.pdfbox.cos.COSName; +import org.pdfbox.cos.COSArray; +import org.pdfbox.cos.COSNumber; +import org.pdfbox.cos.COSInteger; + +import org.pdfbox.exceptions.COSVisitorException; + +/** + * This concatenates two documents with fields and fills the fields in the two templates using different + * values. + * + * @author Michael Traut + * @version $Revision: 1.6 $ + */ +public class AppendAndFillDoc +{ + /** + * Constructor. + */ + public AppendAndFillDoc() + { + super(); + } + + /** + * Append all pages from source to destination. + * + * todo: this method will go to the pdfmodel package one day + * + * @param destination the document to receive the pages + * @param source the document originating the new pages + * + */ + public void appendDocument(COSDocument destination, COSDocument source) + { + COSDictionary pages2 = getPages(source); + COSArray kids = (COSArray)pages2.getItem(COSName.getPDFName("Kids")); + for (Iterator i = kids.iterator(); i.hasNext();) + { + COSDictionary page = (COSDictionary)((COSObject)i.next()).getObject(); + appendPage(destination, page); + } + } + /** + * append a page dict to destination. + * + * todo: this method will go to the pdfmodel package one day + * + * @param destination the document to receive the page + * @param page the page to append to the document + * + */ + public void appendPage(COSDocument destination, COSDictionary page) + { + // get the parent object (pages dictionary) + COSDictionary pages = getPages(destination); + // and set in the page object + page.setItem(COSName.PARENT, pages); + // add new page to kids entry in the pages dictionary + COSArray kids = (COSArray) pages.getItem(COSName.getPDFName("Kids")); + kids.add(page); + // and increase count + COSNumber count = (COSNumber) pages.getItem(COSName.COUNT); + pages.setItem(COSName.COUNT, new COSInteger(count.intValue() + 1)); + } + /** + * concat two pdf documents and fill fields in both templates + * this is a bit tricky as one has to rename the fields if we use the same template two times. + * here we don't user a clever algorithm to create dynamic fieldnames - this is left to the user.. + * + * @param in1 The first template file + * @param in2 The second template file + * @param out The created fiel with all pages from document one and document two + * @param name1 The name of the PDF field (FDF field) in the first template + * @param value1 The value to be used for the field in the first template + * @param name2 The name of the PDF field (FDF field) in the second template + * @param value2 The value to be used for the field in the second template + * + * @throws IOException If there is an error writing the data. + * @throws COSVisitorException If there is an error generating the PDF document. + */ + public void doIt( String in1, + String in2, + String out, + String name1, + String value1, + String name2, + String value2) throws IOException, COSVisitorException + { + COSDocument doc1 = null; + COSDocument doc2 = null; + InputStream is1 = null; + InputStream is2 = null; + PDFParser parser1 = null; + PDFParser parser2 = null; + + OutputStream os = null; + COSWriter writer = null; + try + { + is1 = new FileInputStream(in1); + parser1 = new PDFParser(is1); + parser1.parse(); + doc1 = parser1.getDocument(); + + is2 = new FileInputStream(in2); + parser2 = new PDFParser(is2); + parser2.parse(); + doc2 = parser2.getDocument(); + + setField(doc1, "doc1", new COSString(name1), new COSString(value1)); + setField(doc2, "doc2", new COSString(name2), new COSString(value2)); + + appendDocument(doc1, doc2); + + os = new FileOutputStream(out); + writer = new COSWriter(os); + writer.write(doc1); + } + finally + { + is1.close(); + doc1.close(); + + is2.close(); + doc2.close(); + + os.close(); + writer.close(); + } + } + + /** + * Lookup the pages dictionary in a document. + * + * todo: this method will go to the pdfmodel package one day + * + * @param doc the document where the pages dict is searched + * + * @return The Pages dictionary. + */ + public COSDictionary getPages(COSDocument doc) + { + // todo should access via catalog instead! + for (Iterator i = doc.getObjects().iterator(); i.hasNext();) + { + COSObject obj = (COSObject) i.next(); + COSBase base = obj.getObject(); + if (base instanceof COSDictionary) + { + COSDictionary dict = (COSDictionary) base; + COSBase type = dict.getItem(COSName.TYPE); + if (type != null && type.equals(COSName.getPDFName("Pages"))) + { + return dict; + } + } + } + return null; + } + /** + * This will concat two pdf documents and fill fields in both. + *
+ * see usage() for commandline + * + * @param args command line arguments + */ + public static void main(String[] args) + { + AppendAndFillDoc app = new AppendAndFillDoc(); + try + { + if( args.length != 7 ) + { + app.usage(); + } + else + { + app.doIt( args[0], args[1], args[2], args[3], args[4], args[5], args[6]); + } + } + catch (Exception e) + { + e.printStackTrace(); + } + } + /** + * lookup and fill the field. + * + * todo: this method will go to the pdfmodel package one day + * + * @param doc the document where the field resides + * @param prefix a prefix to use to make the field name unique in the new document + * @param name the name of the PDF Annotation field + * @param value The desired value to be used for the field + * + */ + public void setField(COSDocument doc, String prefix, COSString name, COSString value) + { + for (Iterator i = doc.getObjects().iterator(); i.hasNext();) + { + COSObject obj = (COSObject) i.next(); + COSBase base = obj.getObject(); + if (base instanceof COSDictionary) + { + COSDictionary dict = (COSDictionary) base; + COSBase type = dict.getItem(COSName.TYPE); + if (type != null && type.equals(COSName.getPDFName("Annot"))) + { + COSBase subtype = dict.getItem(COSName.getPDFName("Subtype")); + if (subtype != null && subtype.equals(COSName.getPDFName("Widget"))) + { + // we found the field + COSBase fname = dict.getItem(COSName.getPDFName("T")); + if (fname != null && fname.equals(name)) + { + dict.setItem(COSName.getPDFName("V"), value); + dict.setItem(COSName.getPDFName("T"), new COSString(prefix + name.getString())); + } + } + } + } + } + } + /** + * This will print out a message telling how to use this example. + */ + private void usage() + { + System.err.println( "usage: " + this.getClass().getName() + + " " ); + } +} \ No newline at end of file diff --git a/src/main/java/org/pdfbox/examples/persistence/AppendDoc.java b/src/main/java/org/pdfbox/examples/persistence/AppendDoc.java new file mode 100644 index 0000000..68e254c --- /dev/null +++ b/src/main/java/org/pdfbox/examples/persistence/AppendDoc.java @@ -0,0 +1,357 @@ +/** + * Copyright (c) 2003-2004, www.pdfbox.org + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of pdfbox; nor the names of its + * contributors may be used to endorse or promote products derived from this + * software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON + * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + * http://www.pdfbox.org + * + */ +package org.pdfbox.examples.persistence; + +import java.io.IOException; + +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.Map; + +import org.pdfbox.cos.COSBase; +import org.pdfbox.cos.COSDictionary; +import org.pdfbox.cos.COSName; +import org.pdfbox.cos.COSArray; +import org.pdfbox.cos.COSNumber; +import org.pdfbox.cos.COSInteger; +import org.pdfbox.cos.COSObject; +import org.pdfbox.cos.COSStream; + +import org.pdfbox.pdmodel.PDDocument; +import org.pdfbox.pdmodel.PDDocumentInformation; +import org.pdfbox.pdmodel.PDPage; + +import org.pdfbox.pdmodel.common.PDStream; + +import org.pdfbox.exceptions.COSVisitorException; + +/** + * This example concatenates two documents and writes the result. + * + * @author Michael Traut + * @version $Revision: 1.17 $ + */ +public class AppendDoc +{ + /** + * Constructor. + */ + public AppendDoc() + { + super(); + } + /** + * append all pages from source to destination. + * + * todo: this method will go to the pdfmodel package one day + * + * @param destination the document to receive the pages + * @param source the document originating the new pages + * + * @throws IOException If there is an error accessing data from either document. + */ + public void appendDocument(PDDocument destination, PDDocument source) throws IOException + { + if( destination.isEncrypted() ) + { + throw new IOException( "Error: destination PDF is encrypted, can't append encrypted PDF documents." ); + } + if( source.isEncrypted() ) + { + throw new IOException( "Error: destination PDF is encrypted, can't append encrypted PDF documents." ); + } + PDDocumentInformation destInfo = destination.getDocumentInformation(); + PDDocumentInformation srcInfo = source.getDocumentInformation(); + destInfo.getDictionary().mergeInto( srcInfo.getDictionary() ); + + COSDictionary destTrailer = destination.getDocument().getTrailer(); + COSDictionary destRoot = (COSDictionary)destTrailer.getDictionaryObject( COSName.ROOT ); + + COSDictionary srcTrailer = source.getDocument().getTrailer(); + COSDictionary srcRoot = (COSDictionary)srcTrailer.getDictionaryObject( COSName.ROOT ); + + COSName openAction = COSName.getPDFName( "OpenAction" ); + if( destRoot.getDictionaryObject( openAction ) == null ) + { + COSBase open = srcRoot.getDictionaryObject( openAction ); + if( open != null ) + { + destRoot.setItem( openAction, copyStreamsIntoDocument( destination, open ) ); + } + } + + COSName acroForm = COSName.getPDFName( "AcroForm" ); + COSDictionary destAcroForm = (COSDictionary)destRoot.getDictionaryObject( acroForm ); + COSDictionary srcAcroForm = (COSDictionary)srcRoot.getDictionaryObject( acroForm ); + if( srcAcroForm != null ) + { + if( destAcroForm == null ) + { + destRoot.setItem( acroForm, copyStreamsIntoDocument( destination, srcAcroForm ) ); + } + else + { + //****************need to do proper merge*************** + //destAcroForm.addAll( (COSArray)copyStreamsIntoDocument( destination, srcAcroForm ) ); + } + } + + COSName threads = COSName.getPDFName( "Threads" ); + COSArray destThreads = (COSArray)destRoot.getDictionaryObject( threads ); + COSArray srcThreads = (COSArray)srcRoot.getDictionaryObject( threads ); + if( srcThreads != null ) + { + if( destThreads == null ) + { + destRoot.setItem( threads, copyStreamsIntoDocument( destination, srcThreads ) ); + } + else + { + destThreads.addAll( (COSArray)copyStreamsIntoDocument( destination, srcThreads ) ); + } + } + + COSName names = COSName.getPDFName( "Names" ); + COSDictionary destNames = (COSDictionary)destRoot.getDictionaryObject( names ); + COSDictionary srcNames = (COSDictionary)srcRoot.getDictionaryObject( names ); + if( srcNames != null ) + { + if( destNames == null ) + { + destRoot.setItem( names, copyStreamsIntoDocument( destination, srcNames ) ); + } + else + { + //warning, potential for collision here!! + destNames.mergeInto( (COSDictionary)copyStreamsIntoDocument( destination, srcNames ) ); + } + } + + COSName outlines = COSName.getPDFName( "Outlines" ); + COSDictionary destOutlines = (COSDictionary)destRoot.getDictionaryObject( outlines ); + COSDictionary srcOutlines = (COSDictionary)srcRoot.getDictionaryObject( outlines ); + if( srcOutlines != null && destOutlines == null ) + { + destRoot.setItem( outlines, copyStreamsIntoDocument( destination, srcOutlines ) ); + } + + COSName pagemode = COSName.getPDFName( "PageMode" ); + COSBase srcPageMode = srcRoot.getDictionaryObject( pagemode ); + if( srcOutlines != null && destOutlines == null ) + { + destRoot.setItem( pagemode, copyStreamsIntoDocument( destination, srcPageMode ) ); + } + + COSName pageLabels = COSName.getPDFName( "PageLabels" ); + COSDictionary destLabels = (COSDictionary)destRoot.getDictionaryObject( pageLabels ); + COSDictionary srcLabels = (COSDictionary)srcRoot.getDictionaryObject( pageLabels ); + if( srcLabels != null ) + { + int destPageCount = destination.getNumberOfPages(); + COSArray destNums = null; + if( destLabels == null ) + { + destLabels = new COSDictionary(); + destNums = new COSArray(); + destLabels.setItem( COSName.getPDFName( "Nums" ), destNums ); + destRoot.setItem( pageLabels, destLabels ); + } + else + { + destNums = (COSArray)destLabels.getDictionaryObject( COSName.getPDFName( "Nums" ) ); + } + COSArray srcNums = (COSArray)srcLabels.getDictionaryObject( COSName.getPDFName( "Nums" ) ); + for( int i=0; i + * see usage() for commandline + * + * @param args command line arguments + */ + public static void main(String[] args) + { + AppendDoc app = new AppendDoc(); + try + { + if( args.length != 3 ) + { + app.usage(); + } + else + { + app.doIt( args[0], args[1], args[2]); + } + } + catch( Exception e ) + { + e.printStackTrace(); + } + } + /** + * This will print out a message telling how to use this example. + */ + private void usage() + { + System.err.println( "usage: " + this.getClass().getName() + " " ); + } +} \ No newline at end of file diff --git a/src/main/java/org/pdfbox/examples/persistence/CopyDoc.java b/src/main/java/org/pdfbox/examples/persistence/CopyDoc.java new file mode 100644 index 0000000..a3b7e3f --- /dev/null +++ b/src/main/java/org/pdfbox/examples/persistence/CopyDoc.java @@ -0,0 +1,140 @@ +/** + * Copyright (c) 2003, www.pdfbox.org + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of pdfbox; nor the names of its + * contributors may be used to endorse or promote products derived from this + * software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON + * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + * http://www.pdfbox.org + * + */ +package org.pdfbox.examples.persistence; + +import java.io.IOException; + +import org.pdfbox.cos.COSDocument; + + + +import org.pdfbox.pdfparser.PDFParser; + +import org.pdfbox.pdfwriter.COSWriter; +import org.pdfbox.exceptions.COSVisitorException; + +/** + * This is an example used to copy a documents contents from a source doc to destination doc + * via an in-memory document representation. + * + * @author Michael Traut + * @version $Revision: 1.7 $ + */ +public class CopyDoc +{ + /** + * Constructor. + */ + public CopyDoc() + { + super(); + } + + /** + * This will perform the document copy. + * + * @param in The filename used for input. + * @param out The filename used for output. + * + * @throws IOException If there is an error parsing the document. + * @throws COSVisitorException If there is an error while copying the document. + */ + public void doIt(String in, String out) throws IOException, COSVisitorException + { + java.io.InputStream is = null; + java.io.OutputStream os = null; + COSWriter writer = null; + try + { + is = new java.io.FileInputStream(in); + PDFParser parser = new PDFParser(is); + parser.parse(); + + COSDocument doc = parser.getDocument(); + + os = new java.io.FileOutputStream(out); + writer = new COSWriter(os); + + writer.write(doc); + + } + finally + { + if( is != null ) + { + is.close(); + } + if( os != null ) + { + os.close(); + } + if( writer != null ) + { + writer.close(); + } + } + } + + /** + * This will copy a PDF document. + *
+ * see usage() for commandline + * + * @param args command line arguments + */ + public static void main(String[] args) + { + CopyDoc app = new CopyDoc(); + try + { + if( args.length != 2 ) + { + app.usage(); + } + else + { + app.doIt( args[0], args[1]); + } + } + catch (Exception e) + { + e.printStackTrace(); + } + } + + /** + * This will print out a message telling how to use this example. + */ + private void usage() + { + System.err.println( "usage: " + this.getClass().getName() + " " ); + } +} \ No newline at end of file diff --git a/src/main/java/org/pdfbox/examples/persistence/FieldsDoc.java b/src/main/java/org/pdfbox/examples/persistence/FieldsDoc.java new file mode 100644 index 0000000..e506fe1 --- /dev/null +++ b/src/main/java/org/pdfbox/examples/persistence/FieldsDoc.java @@ -0,0 +1,177 @@ +/** + * Copyright (c) 2003, www.pdfbox.org + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of pdfbox; nor the names of its + * contributors may be used to endorse or promote products derived from this + * software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON + * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + * http://www.pdfbox.org + * + */ +package org.pdfbox.examples.persistence; + +import java.io.IOException; +import java.io.OutputStream; +import java.io.FileOutputStream; + +import java.util.Iterator; + +import org.pdfbox.pdfparser.PDFParser; + +import org.pdfbox.pdfwriter.COSWriter; + +import org.pdfbox.cos.COSDocument; +import org.pdfbox.cos.COSString; +import org.pdfbox.cos.COSBase; +import org.pdfbox.cos.COSDictionary; +import org.pdfbox.cos.COSObject; +import org.pdfbox.cos.COSName; + +import org.pdfbox.exceptions.COSVisitorException; + +/** + * This example fills a field in a pdf document and writes it to new destination. + * + * @author Michael Traut + * @version $Revision: 1.5 $ + */ +public class FieldsDoc +{ + /** + * Constructor. + */ + public FieldsDoc() + { + super(); + } + /** + * fill a field in the pdf. + * + * @param in The template file + * @param out The file to write the PDF to. + * @param name The name of the PDF field (FDF field) + * @param value The value to be used for the field + * + * @throws IOException If there is an error writing the data. + * @throws COSVisitorException If there is an error generating the PDF document. + */ + public void doIt(String in, String out, String name, String value) throws IOException, COSVisitorException + { + java.io.InputStream is = null; + COSDocument doc = null; + OutputStream os = null; + COSWriter writer = null; + try + { + is = new java.io.FileInputStream(in); + PDFParser parser = new PDFParser(is); + parser.parse(); + + doc = parser.getDocument(); + + setField(doc, new COSString(name), new COSString(value)); + + os = new FileOutputStream(out); + writer = new COSWriter(os); + + writer.write(doc); + + } + finally + { + is.close(); + doc.close(); + os.close(); + writer.close(); + } + } + /** + * This will fill a field in a PDF document. + *
+ * see usage() for commandline + * + * @param args command line arguments + */ + public static void main(String[] args) + { + FieldsDoc app = new FieldsDoc(); + try + { + if( args.length != 4 ) + { + app.usage(); + } + else + { + app.doIt( args[0], args[1], args[2], args[3]); + } + } + catch (Exception e) + { + e.printStackTrace(); + } + } + /** + * lookup and fill the field. + * + * todo: this method will go to the pdfmodel package one day + * + * @param doc the document where the field resides + * @param name the name of the PDF Annotation field + * @param value The desired value to be used for the field + * + */ + public void setField(COSDocument doc, COSString name, COSString value) + { + for (Iterator i = doc.getObjects().iterator(); i.hasNext();) + { + COSObject obj = (COSObject) i.next(); + COSBase base = obj.getObject(); + if (base instanceof COSDictionary) + { + COSDictionary dict = (COSDictionary) base; + COSBase type = dict.getItem(COSName.TYPE); + if (type != null && type.equals(COSName.getPDFName("Annot"))) + { + COSBase subtype = dict.getItem(COSName.getPDFName("Subtype")); + if (subtype != null && subtype.equals(COSName.getPDFName("Widget"))) + { + // we found the field + COSBase fname = dict.getItem(COSName.getPDFName("T")); + if (fname != null && fname.equals(name)) + { + dict.setItem(COSName.getPDFName("V"), value); + } + } + } + } + } + } + /** + * This will print out a message telling how to use this example. + */ + private void usage() + { + System.err.println( "usage: " + this.getClass().getName() + " " ); + } +} \ No newline at end of file diff --git a/src/main/java/org/pdfbox/examples/persistence/WriteDecodedDoc.java b/src/main/java/org/pdfbox/examples/persistence/WriteDecodedDoc.java new file mode 100644 index 0000000..8fcab7f --- /dev/null +++ b/src/main/java/org/pdfbox/examples/persistence/WriteDecodedDoc.java @@ -0,0 +1,151 @@ +/** + * Copyright (c) 2003-2004, www.pdfbox.org + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of pdfbox; nor the names of its + * contributors may be used to endorse or promote products derived from this + * software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON + * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + * http://www.pdfbox.org + * + */ +package org.pdfbox.examples.persistence; + +import java.io.IOException; + +import java.util.Iterator; + +import org.pdfbox.cos.COSBase; +import org.pdfbox.cos.COSObject; +import org.pdfbox.cos.COSStream; + +import org.pdfbox.pdmodel.PDDocument; + +import org.pdfbox.exceptions.COSVisitorException; + +import org.pdfbox.exceptions.InvalidPasswordException; + +/** + * load document and write with all streams decoded. + * + * @author Michael Traut + * @version $Revision: 1.8 $ + */ +public class WriteDecodedDoc +{ + + /** + * Constructor. + */ + public WriteDecodedDoc() + { + super(); + } + + /** + * This will perform the document reading, decoding and writing. + * + * @param in The filename used for input. + * @param out The filename used for output. + * + * @throws IOException If there is an error parsing the document. + * @throws COSVisitorException If there is an error while copying the document. + */ + public void doIt(String in, String out) throws IOException, COSVisitorException + { + PDDocument doc = null; + try + { + doc = PDDocument.load( in ); + if( doc.isEncrypted() ) + { + try + { + doc.decrypt( "" ); + } + catch( InvalidPasswordException e ) + { + System.err.println( "Error: The document is encrypted." ); + } + catch( org.pdfbox.exceptions.CryptographyException e ) + { + e.printStackTrace(); + } + } + + for (Iterator i = doc.getDocument().getObjects().iterator(); i.hasNext();) + { + COSBase base = ((COSObject) i.next()).getObject(); + if (base instanceof COSStream) + { + // just kill the filters + COSStream cosStream = (COSStream)base; + cosStream.getUnfilteredStream(); + cosStream.setFilters(null); + } + } + doc.save( out ); + } + finally + { + if( doc != null ) + { + doc.close(); + } + } + } + + /** + * This will write a PDF document with completely decoded streams. + *
+ * see usage() for commandline + * + * @param args command line arguments + */ + public static void main(String[] args) + { + WriteDecodedDoc app = new WriteDecodedDoc(); + try + { + if( args.length != 2 ) + { + app.usage(); + } + else + { + app.doIt( args[0], args[1]); + } + } + catch (Exception e) + { + e.printStackTrace(); + } + } + + /** + * This will print out a message telling how to use this example. + */ + private void usage() + { + System.err.println( "usage: " + this.getClass().getName() + " " ); + } +} \ No newline at end of file diff --git a/src/main/java/org/pdfbox/examples/persistence/package.html b/src/main/java/org/pdfbox/examples/persistence/package.html new file mode 100644 index 0000000..9c0d57f --- /dev/null +++ b/src/main/java/org/pdfbox/examples/persistence/package.html @@ -0,0 +1,9 @@ + + + + + + +These examples will show how to use the persistence features of the PDFBox. + + diff --git a/src/main/java/org/pdfbox/examples/signature/ShowSignature.java b/src/main/java/org/pdfbox/examples/signature/ShowSignature.java new file mode 100644 index 0000000..7398534 --- /dev/null +++ b/src/main/java/org/pdfbox/examples/signature/ShowSignature.java @@ -0,0 +1,168 @@ +/** + * Copyright (c) 2003, www.pdfbox.org + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of pdfbox; nor the names of its + * contributors may be used to endorse or promote products derived from this + * software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON + * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + * http://www.pdfbox.org + * + */ +package org.pdfbox.examples.signature; + +import java.io.ByteArrayInputStream; +import java.io.IOException; + +import java.security.cert.CertificateFactory; + +import java.util.Collection; + +import org.pdfbox.cos.COSArray; +import org.pdfbox.cos.COSDictionary; +import org.pdfbox.cos.COSName; +import org.pdfbox.cos.COSString; + +import org.pdfbox.pdmodel.PDDocument; + +/** + * This will read a document from the filesystem, decrypt it and do something with the signature. + * + * usage: java org.pdfbox.examples.signature.ShowSignature <password> <inputfile> + * + * + * @author Ben Litchfield (ben@csh.rit.edu) + * @version $Revision: 1.8 $ + */ +public class ShowSignature +{ + + /** + * This is the entry point for the application. + * + * @param args The command-line arguments. + * + * @throws Exception If there is an error reading the file. + */ + public static void main( String[] args ) throws Exception + { + ShowSignature show = new ShowSignature(); + show.showSignature( args ); + } + + private void showSignature( String[] args ) throws Exception + { + if( args.length != 2 ) + { + usage(); + } + else + { + String password = args[0]; + String infile = args[1]; + PDDocument document = null; + try + { + document = PDDocument.load( infile ); + + if( document.isEncrypted() ) + { + document.decrypt( password ); + } + else + { + System.err.println( "Warning: Document is not encrypted." ); + } + + COSDictionary trailer = document.getDocument().getTrailer(); + COSDictionary root = (COSDictionary)trailer.getDictionaryObject( COSName.ROOT ); + COSDictionary acroForm = (COSDictionary)root.getDictionaryObject( COSName.getPDFName( "AcroForm" ) ); + COSArray fields = (COSArray)acroForm.getDictionaryObject( COSName.getPDFName( "Fields" ) ); + for( int i=0; i " ); + } + +} \ No newline at end of file diff --git a/src/main/java/org/pdfbox/examples/signature/package.html b/src/main/java/org/pdfbox/examples/signature/package.html new file mode 100644 index 0000000..731c0ff --- /dev/null +++ b/src/main/java/org/pdfbox/examples/signature/package.html @@ -0,0 +1,9 @@ + + + + + + +These examples will show how to gain access to the PDF signature. + + diff --git a/src/main/java/org/pdfbox/examples/util/ExtractTextByArea.java b/src/main/java/org/pdfbox/examples/util/ExtractTextByArea.java new file mode 100644 index 0000000..042e3e6 --- /dev/null +++ b/src/main/java/org/pdfbox/examples/util/ExtractTextByArea.java @@ -0,0 +1,119 @@ +/** + * Copyright (c) 2005, www.pdfbox.org + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of pdfbox; nor the names of its + * contributors may be used to endorse or promote products derived from this + * software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON + * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + * http://www.pdfbox.org + * + */ +package org.pdfbox.examples.util; + +import org.pdfbox.exceptions.InvalidPasswordException; + +import org.pdfbox.pdmodel.PDDocument; +import org.pdfbox.pdmodel.PDPage; +import org.pdfbox.util.PDFTextStripperByArea; + +import java.awt.Rectangle; + +import java.util.List; + +/** + * This is an example on how to extract text from a specific area on the PDF document. + * + * Usage: java org.pdfbox.examples.util.ExtractTextByArea <input-pdf> + * + * @author Ben Litchfield (ben@benlitchfield.com) + * @version $Revision: 1.1 $ + */ +public class ExtractTextByArea +{ + private ExtractTextByArea() + { + //utility class and should not be constructed. + } + + + /** + * This will print the documents text in a certain area. + * + * @param args The command line arguments. + * + * @throws Exception If there is an error parsing the document. + */ + public static void main( String[] args ) throws Exception + { + if( args.length != 1 ) + { + usage(); + } + else + { + PDDocument document = null; + try + { + document = PDDocument.load( args[0] ); + if( document.isEncrypted() ) + { + try + { + document.decrypt( "" ); + } + catch( InvalidPasswordException e ) + { + System.err.println( "Error: Document is encrypted with a password." ); + System.exit( 1 ); + } + } + PDFTextStripperByArea stripper = new PDFTextStripperByArea(); + stripper.setSortByPosition( true ); + Rectangle rect = new Rectangle( 10, 280, 275, 60 ); + stripper.addRegion( "class1", rect ); + List allPages = document.getDocumentCatalog().getAllPages(); + PDPage firstPage = (PDPage)allPages.get( 0 ); + stripper.extractRegions( firstPage ); + System.out.println( "Text in the area:" + rect ); + System.out.println( stripper.getTextForRegion( "class1" ) ); + + } + finally + { + if( document != null ) + { + document.close(); + } + } + } + } + + /** + * This will print the usage for this document. + */ + private static void usage() + { + System.err.println( "Usage: java org.pdfbox.examples.util.ExtractTextByArea " ); + } + +} \ No newline at end of file diff --git a/src/main/java/org/pdfbox/examples/util/PrintTextLocations.java b/src/main/java/org/pdfbox/examples/util/PrintTextLocations.java new file mode 100644 index 0000000..6c83b57 --- /dev/null +++ b/src/main/java/org/pdfbox/examples/util/PrintTextLocations.java @@ -0,0 +1,144 @@ +/** + * Copyright (c) 2005, www.pdfbox.org + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of pdfbox; nor the names of its + * contributors may be used to endorse or promote products derived from this + * software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON + * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + * http://www.pdfbox.org + * + */ +package org.pdfbox.examples.util; + +import org.pdfbox.exceptions.InvalidPasswordException; + +import org.pdfbox.pdfparser.PDFParser; + +import org.pdfbox.pdmodel.PDDocument; +import org.pdfbox.pdmodel.PDPage; +import org.pdfbox.util.PDFTextStripper; +import org.pdfbox.util.TextPosition; + +import java.io.FileInputStream; +import java.io.IOException; + +import java.util.List; + +/** + * This is an example on how to get some x/y coordinates of text. + * + * Usage: java org.pdfbox.examples.util.PrintTextLocations <input-pdf> + * + * @author Ben Litchfield (ben@benlitchfield.com) + * @version $Revision: 1.2 $ + */ +public class PrintTextLocations extends PDFTextStripper +{ + /** + * Default constructor. + * + * @throws IOException If there is an error loading text stripper properties. + */ + public PrintTextLocations() throws IOException + { + //default constructor. + } + + /** + * This will print the documents data. + * + * @param args The command line arguments. + * + * @throws Exception If there is an error parsing the document. + */ + public static void main( String[] args ) throws Exception + { + if( args.length != 1 ) + { + usage(); + } + else + { + PDDocument document = null; + FileInputStream file = null; + try + { + file = new FileInputStream( args[0] ); + PDFParser parser = new PDFParser( file ); + parser.parse(); + document = parser.getPDDocument(); + if( document.isEncrypted() ) + { + try + { + document.decrypt( "" ); + } + catch( InvalidPasswordException e ) + { + System.err.println( "Error: Document is encrypted with a password." ); + System.exit( 1 ); + } + } + PrintTextLocations printer = new PrintTextLocations(); + List allPages = document.getDocumentCatalog().getAllPages(); + for( int i=0; i" ); + } + +} \ No newline at end of file diff --git a/src/main/java/org/pdfbox/examples/util/package.html b/src/main/java/org/pdfbox/examples/util/package.html new file mode 100644 index 0000000..bc50f59 --- /dev/null +++ b/src/main/java/org/pdfbox/examples/util/package.html @@ -0,0 +1,9 @@ + + + + + + +The packages in this package will show how to use the PDFBox util API. + + -- cgit v1.2.3