Package org.apache.pdfbox.pdmodel

Examples of org.apache.pdfbox.pdmodel.PDDocument


     *
     * @throws Exception If there is an error during the process.
     */
    public static void main(String[] args) throws Exception
    {
        PDDocument doc = null;
        try
        {
            if( args.length != 2 )
            {
                usage();
            }
            else
            {
                doc = PDDocument.load( args[0] );
                int pageNum = 0;
                for( PDPage page : doc.getPages() )
                {
                    pageNum++;
                    List annotations = page.getAnnotations();

                    for( int j=0; j<annotations.size(); j++ )
                    {
                        PDAnnotation annot = (PDAnnotation)annotations.get( j );
                        if( annot instanceof PDAnnotationLink )
                        {
                            PDAnnotationLink link = (PDAnnotationLink)annot;
                            PDAction action = link.getAction();
                            if( action instanceof PDActionURI )
                            {
                                PDActionURI uri = (PDActionURI)action;
                                String oldURI = uri.getURI();
                                String newURI = "http://www.pdfbox.org";
                                System.out.println( "Page " + pageNum +": Replacing " + oldURI + " with " + newURI );
                                uri.setURI( newURI );
                            }
                        }
                    }
                }
                doc.save( args[1] );
            }
        }
        finally
        {
            if( doc != null )
            {
                doc.close();
            }
        }
    }
View Full Code Here


     * @throws IOException If there is an error writing the data.
     */
    public void doIt( String file) throws IOException
    {
        // 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("ISO-8859-1");
            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 );

            // create a new tree node and add the embedded file
            PDEmbeddedFilesNameTreeNode treeNode = new PDEmbeddedFilesNameTreeNode();
            treeNode.setNames( Collections.singletonMap( "My first attachment",  fs ) );
            // add the new node as kid to the root node
            List<PDEmbeddedFilesNameTreeNode> kids = new ArrayList<PDEmbeddedFilesNameTreeNode>();
            kids.add(treeNode);
            efTree.setKids(kids);
            // add the tree to the document catalog
            PDDocumentNameDictionary names = new PDDocumentNameDictionary( doc.getDocumentCatalog() );
            names.setEmbeddedFiles( efTree );
            doc.getDocumentCatalog().setNames( names );


            doc.save( file );
        }
        finally
        {
            if( doc != null )
            {
                doc.close();
            }
        }
    }
View Full Code Here

        {
            usage();
        }
        else
        {
            PDDocument document = new PDDocument();

            try
            {
                PDPage page = new PDPage();
                document.addPage(page);
                List annotations = page.getAnnotations();

                // Setup some basic reusable objects/constants
                // Annotations themselves can only be used once!

                float inch = 72;
                PDGamma colourRed = new PDGamma();
                colourRed.setR(1);
                PDGamma colourBlue = new PDGamma();
                colourBlue.setB(1);
                PDGamma colourBlack = new PDGamma();

                PDBorderStyleDictionary borderThick = new PDBorderStyleDictionary();
                borderThick.setWidth(inch/12)// 12th inch
                PDBorderStyleDictionary borderThin = new PDBorderStyleDictionary();
                borderThin.setWidth(inch/72); // 1 point
                PDBorderStyleDictionary borderULine = new PDBorderStyleDictionary();
                borderULine.setStyle(PDBorderStyleDictionary.STYLE_UNDERLINE);
                borderULine.setWidth(inch/72); // 1 point


                float pw = page.getMediaBox().getUpperRightX();
                float ph = page.getMediaBox().getUpperRightY();


                // First add some text, two lines we'll add some annotations to this later


                PDFont font = PDType1Font.HELVETICA_BOLD;

                PDPageContentStream contentStream = new PDPageContentStream(document, page);
                contentStream.beginText();
                contentStream.setFont( font, 18 );
                contentStream.moveTextPositionByAmount( inch, ph-inch-18);
                contentStream.drawString( "PDFBox" );
                contentStream.moveTextPositionByAmount( 0,-(inch/2));
                contentStream.drawString( "Click Here" );
                contentStream.endText();

                contentStream.close();

                // Now add the markup annotation, a highlight to PDFBox text
                PDAnnotationTextMarkup txtMark = new PDAnnotationTextMarkup(PDAnnotationTextMarkup.SUB_TYPE_HIGHLIGHT);
                txtMark.setColour(colourBlue);
                txtMark.setConstantOpacity((float)0.2);   // Make the highlight 20% transparent

                // Set the rectangle containing the markup

                float textWidth = (font.getStringWidth( "PDFBox" )/1000) * 18;
                PDRectangle position = new PDRectangle();
                position.setLowerLeftX(inch);
                position.setLowerLeftY( ph-inch-18 );
                position.setUpperRightX(72 + textWidth);
                position.setUpperRightY(ph-inch);
                txtMark.setRectangle(position);

                // work out the points forming the four corners of the annotations
                // set out in anti clockwise form (Completely wraps the text)
                // OK, the below doesn't match that description.
                // It's what acrobat 7 does and displays properly!
                float[] quads = new float[8];

                quads[0] = position.getLowerLeftX()// x1
                quads[1] = position.getUpperRightY()-2; // y1
                quads[2] = position.getUpperRightX(); // x2
                quads[3] = quads[1]; // y2
                quads[4] = quads[0]// x3
                quads[5] = position.getLowerLeftY()-2; // y3
                quads[6] = quads[2]; // x4
                quads[7] = quads[5]; // y5

                txtMark.setQuadPoints(quads);
                txtMark.setContents("Highlighted since it's important");

                annotations.add(txtMark);

                // Now add the link annotation, so the clickme works
                PDAnnotationLink txtLink = new PDAnnotationLink();
                txtLink.setBorderStyle(borderULine);

                // Set the rectangle containing the link

                textWidth = (font.getStringWidth( "Click Here" )/1000) * 18;
                position = new PDRectangle();
                position.setLowerLeftX(inch);
                position.setLowerLeftY( ph-(float)(1.5*inch)-20)// down a couple of points
                position.setUpperRightX(72 + textWidth);
                position.setUpperRightY(ph-(float)(1.5*inch));
                txtLink.setRectangle(position);

                // add an action
                PDActionURI action = new PDActionURI();
                action.setURI("http://www.pdfbox.org");
                txtLink.setAction(action);

                annotations.add(txtLink);


                // Now draw a few more annotations

                PDAnnotationSquareCircle aCircle =
                    new PDAnnotationSquareCircle( PDAnnotationSquareCircle.SUB_TYPE_CIRCLE);
                aCircle.setContents("Circle Annotation");
                aCircle.setInteriorColour(colourRed)// Fill in circle in red
                aCircle.setColour(colourBlue); // The border itself will be blue
                aCircle.setBorderStyle(borderThin);

                // Place the annotation on the page, we'll make this 1" round
                // 3" down, 1" in on the page

                position = new PDRectangle();
                position.setLowerLeftX(inch);
                position.setLowerLeftY(ph-(3*inch)-inch); // 1" height, 3" down
                position.setUpperRightX(2*inch); // 1" in, 1" width
                position.setUpperRightY(ph-(3*inch)); // 3" down
                aCircle.setRectangle(position);

                //  add to the annotations on the page
                annotations.add(aCircle);

                // Now a square annotation

                PDAnnotationSquareCircle aSquare =
                    new PDAnnotationSquareCircle( PDAnnotationSquareCircle.SUB_TYPE_SQUARE);
                aSquare.setContents("Square Annotation");
                aSquare.setColour(colourRed)// Outline in red, not setting a fill
                aSquare.setBorderStyle(borderThick);

                // Place the annotation on the page, we'll make this 1" (72points) square
                // 3.5" down, 1" in from the right on the page

                position = new PDRectangle(); // Reuse the variable, but note it's a new object!
                position.setLowerLeftX(pw-(2*inch))// 1" in from right, 1" wide
                position.setLowerLeftY(ph-(float)(3.5*inch) - inch); // 1" height, 3.5" down
                position.setUpperRightX(pw-inch); // 1" in from right
                position.setUpperRightY(ph-(float)(3.5*inch)); // 3.5" down
                aSquare.setRectangle(position);

                //  add to the annotations on the page
                annotations.add(aSquare);

                // Now we want to draw a line between the two, one end with an open arrow

                PDAnnotationLine aLine = new PDAnnotationLine();

                aLine.setEndPointEndingStyle( PDAnnotationLine.LE_OPEN_ARROW );
                aLine.setContents("Circle->Square");
                aLine.setCaption(true)// Make the contents a caption on the line

                // Set the rectangle containing the line

                position = new PDRectangle(); // Reuse the variable, but note it's a new object!
                position.setLowerLeftX(2*inch)// 1" in + width of circle
                position.setLowerLeftY(ph-(float)(3.5*inch)-inch); // 1" height, 3.5" down
                position.setUpperRightX(pw-inch-inch); // 1" in from right, and width of square
                position.setUpperRightY(ph-(3*inch)); // 3" down (top of circle)
                aLine.setRectangle(position);

                // Now set the line position itself
                float[] linepos = new float[4];
                linepos[0] = 2*inch;  // x1 = rhs of circle
                linepos[1] = ph-(float)(3.5*inch); // y1 halfway down circle
                linepos[2] = pw-(2*inch)// x2 = lhs of square
                linepos[3] = ph-(4*inch); // y2 halfway down square
                aLine.setLine(linepos);

                aLine.setBorderStyle(borderThick);
                aLine.setColour(colourBlack);

                // add to the annotations on the page
                annotations.add(aLine);


                // Finally all done


                document.save( args[0] );
            }
            finally
            {
                document.close();
            }
        }
    }
View Full Code Here

        }
        else
        {
            String password = args[0];
            String infile = args[1];
            PDDocument document = null;
            try
            {
                document = PDDocument.load( infile );

                if( document.isEncrypted() )
                {
                    StandardDecryptionMaterial sdm = new StandardDecryptionMaterial(password);
                    document.openProtection(sdm);
                }
                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.ACRO_FORM );
                COSArray fields = (COSArray)acroForm.getDictionaryObject( COSName.FIELDS );
                for( int i=0; i<fields.size(); i++ )
                {
                    COSDictionary field = (COSDictionary)fields.getObject( i );
                    String type = field.getNameAsString( "FT" );
                    if( "Sig".equals( type ) )
                    {
                        COSDictionary cert = (COSDictionary)field.getDictionaryObject( COSName.V );
                        if( cert != null )
                        {
                            System.out.println( "Certificate found" );
                            System.out.println( "Name=" + cert.getDictionaryObject( COSName.NAME ) );
                            System.out.println( "Modified=" + cert.getDictionaryObject( COSName.getPDFName( "M" ) ) );
                            COSName subFilter = (COSName)cert.getDictionaryObject( COSName.getPDFName( "SubFilter" ) );
                            if( subFilter != null )
                            {
                                if( subFilter.getName().equals( "adbe.x509.rsa_sha1" ) )
                                {
                                    COSString certString = (COSString)cert.getDictionaryObject(
                                        COSName.getPDFName( "Cert" ) );
                                    byte[] certData = certString.getBytes();
                                    CertificateFactory factory = CertificateFactory.getInstance( "X.509" );
                                    ByteArrayInputStream certStream = new ByteArrayInputStream( certData );
                                    Collection certs = factory.generateCertificates( certStream );
                                    System.out.println( "certs=" + certs );
                                }
                                else if( subFilter.getName().equals( "adbe.pkcs7.sha1" ) )
                                {
                                    COSString certString = (COSString)cert.getDictionaryObject(
                                        COSName.CONTENTS );
                                    byte[] certData = certString.getBytes();
                                    CertificateFactory factory = CertificateFactory.getInstance( "X.509" );
                                    ByteArrayInputStream certStream = new ByteArrayInputStream( certData );
                                    Collection certs = factory.generateCertificates( certStream );
                                    System.out.println( "certs=" + certs );
                                }
                                else
                                {
                                    System.err.println( "Unknown certificate type:" + subFilter );
                                }
                            }
                            else
                            {
                                throw new IOException( "Missing subfilter for cert dictionary" );
                            }
                        }
                        else
                        {
                            System.out.println( "Signature found, but no certificate" );
                        }
                    }
                }
            }
            finally
            {
                if( document != null )
                {
                    document.close();
                }
            }
        }
    }
View Full Code Here

        }

        FileOutputStream fos = new FileOutputStream(outFile);

        // sign
        PDDocument doc = PDDocument.load(inFile);
        signDetached(doc, fos, tsaClient);
        doc.close();
    }
View Full Code Here

     * @throws IOException If there is an error generating the highlight file.
     */
    public static void main(String[] args) throws IOException
    {
        PDFHighlighter xmlExtractor = new PDFHighlighter();
        PDDocument doc = null;
        try
        {
            if( args.length < 2 )
            {
                usage();
            }
            String[] highlightStrings = new String[ args.length - 1];
            System.arraycopy( args, 1, highlightStrings, 0, highlightStrings.length );
            doc = PDDocument.load( args[0] );

            xmlExtractor.generateXMLHighlight(
                doc,
                highlightStrings,
                new OutputStreamWriter( System.out ) );
        }
        finally
        {
            if( doc != null )
            {
                doc.close();
            }
        }
    }
View Full Code Here

     *
     * @return The extracted document
     * @throws IOException If there is an IOError
     */
    public PDDocument extract() throws IOException {
        PDDocument extractedDocument = new PDDocument();
        extractedDocument.setDocumentInformation(sourceDocument.getDocumentInformation());
        extractedDocument.getDocumentCatalog().setViewerPreferences(
                sourceDocument.getDocumentCatalog().getViewerPreferences());
       
        for (int i = startPage; i <= endPage; i++) {
            PDPage page = sourceDocument.getPage(i - 1);
            PDPage imported = extractedDocument.importPage(page);
            imported.setCropBox(page.getCropBox());
            imported.setMediaBox(page.getMediaBox());
            imported.setResources(page.getResources());
            imported.setRotation(page.getRotation());
        }
View Full Code Here

        pdfBuilder.createPage(properties);
        PDPage page = pdfStructure.getPage();

        //create template
        pdfBuilder.createTemplate(page);
        PDDocument template = pdfStructure.getTemplate();
       
        //create /AcroForm
        pdfBuilder.createAcroForm(template);
        PDAcroForm acroForm = pdfStructure.getAcroForm();

        // AcroForm contains singature fields
        pdfBuilder.createSignatureField(acroForm);
        PDSignatureField pdSignatureField = pdfStructure.getSignatureField();
       
        // create signature
        pdfBuilder.createSignature(pdSignatureField, page, properties.getSignatureFieldName());
      
        // that is /AcroForm/DR entry
        pdfBuilder.createAcroFormDictionary(acroForm, pdSignatureField);
       
        // create AffineTransform
        pdfBuilder.createAffineTransform(properties.getAffineTransformParams());
        AffineTransform transform = pdfStructure.getAffineTransform();
      
        // rectangle, formatter, image. /AcroForm/DR/XObject contains that form
        pdfBuilder.createSignatureRectangle(pdSignatureField, properties);
        pdfBuilder.createFormaterRectangle(properties.getFormaterRectangleParams());
        PDRectangle formater = pdfStructure.getFormaterRectangle();
        pdfBuilder.createSignatureImage(template, properties.getImage());

        // create form stream, form and  resource.
        pdfBuilder.createHolderFormStream(template);
        PDStream holderFormStream = pdfStructure.getHolderFormStream();
        pdfBuilder.createHolderFormResources();
        PDResources holderFormResources = pdfStructure.getHolderFormResources();
        pdfBuilder.createHolderForm(holderFormResources, holderFormStream, formater);
       
        // that is /AP entry the appearance dictionary.
        pdfBuilder.createAppearanceDictionary(pdfStructure.getHolderForm(), pdSignatureField);
       
        // inner form stream, form and resource (hlder form containts inner form)
        pdfBuilder.createInnerFormStream(template);
        pdfBuilder.createInnerFormResource();
        PDResources innerFormResource = pdfStructure.getInnerFormResources();
        pdfBuilder.createInnerForm(innerFormResource, pdfStructure.getInnterFormStream(), formater);
        PDFormXObject innerForm = pdfStructure.getInnerForm();
      
        // inner form must be in the holder form as we wrote
        pdfBuilder.insertInnerFormToHolerResources(innerForm, holderFormResources);
       
        //  Image form is in this structure: /AcroForm/DR/FRM0/Resources/XObject/n0
        pdfBuilder.createImageFormStream(template);
        PDStream imageFormStream = pdfStructure.getImageFormStream();
        pdfBuilder.createImageFormResources();
        PDResources imageFormResources = pdfStructure.getImageFormResources();
        pdfBuilder.createImageForm(imageFormResources, innerFormResource, imageFormStream, formater,
                transform, pdfStructure.getImage());
      
        // now inject procSetArray
        pdfBuilder.injectProcSetArray(innerForm, page, innerFormResource, imageFormResources,
                holderFormResources, pdfStructure.getProcSet());

        COSName imgFormName = pdfStructure.getImageFormName();
        COSName imgName = pdfStructure.getImageName();
        COSName innerFormName = pdfStructure.getInnerFormName();

        // now create Streams of AP
        pdfBuilder.injectAppearanceStreams(holderFormStream, imageFormStream, imageFormStream,
                imgFormName, imgName, innerFormName, properties);
        pdfBuilder.createVisualSignature(template);
        pdfBuilder.createWidgetDictionary(pdSignatureField, holderFormResources);
       
        ByteArrayInputStream in = pdfStructure.getTemplateAppearanceStream();
        logger.info("stream returning started, size= " + in.available());
       
        // we must close the document
        template.close();
       
        // return result of the stream
        return in;
    }
View Full Code Here

     */
    public void createPDFFromImage( String inputFile, String image, String outputFile )
            throws IOException
    {
        // the document
        PDDocument doc = null;
        try
        {
            doc = PDDocument.load( inputFile );

            //we will add the image to the first page.
            PDPage page = doc.getPage(0);

            PDImageXObject ximage;
            if( image.toLowerCase().endsWith( ".jpg" ) )
            {
                ximage = JPEGFactory.createFromStream(doc, new FileInputStream(image));
            }
            else if (image.toLowerCase().endsWith(".tif") || image.toLowerCase().endsWith(".tiff"))
            {
                ximage = CCITTFactory.createFromRandomAccess(doc, new RandomAccessFile(new File(image),"r"));
            }
            else if (image.toLowerCase().endsWith(".gif") ||
                    image.toLowerCase().endsWith(".bmp") ||
                    image.toLowerCase().endsWith(".png"))
            {
                BufferedImage bim = ImageIO.read(new File(image));
                ximage = LosslessFactory.createFromImage(doc, bim);
            }
            else
            {
                throw new IOException( "Image type not supported: " + image );
            }
            PDPageContentStream contentStream = new PDPageContentStream(doc, page, true, true);

            //contentStream.drawImage(ximage, 20, 20 );
            // better method inspired by http://stackoverflow.com/a/22318681/535646
            float scale = 1f; // reduce this value if the image is too large
            contentStream.drawXObject(ximage, 20, 20, ximage.getWidth()*scale, ximage.getHeight()*scale);

            contentStream.close();
            doc.save( outputFile );
        }
        finally
        {
            if( doc != null )
            {
                doc.close();
            }
        }
    }
View Full Code Here

        {
            usage();
        }
        else
        {
            PDDocument document = null;
            try
            {
                document = PDDocument.load( args[0] );
                if( document.isEncrypted() )
                {
                    System.err.println( "Error: Cannot add bookmark destination to encrypted documents." );
                    System.exit( 1 );
                }

                if( document.getNumberOfPages() < 2 )
                {
                    throw new IOException( "Error: The PDF must have at least 2 pages.");
                }
                PDDocumentOutline bookmarks = document.getDocumentCatalog().getDocumentOutline();
                if( bookmarks == null )
                {
                    throw new IOException( "Error: The PDF does not contain any bookmarks" );
                }
                PDOutlineItem item = bookmarks.getFirstChild().getNextSibling();
                PDDestination dest = item.getDestination();
                PDActionGoTo action = new PDActionGoTo();
                action.setDestination(dest);
                document.getDocumentCatalog().setOpenAction(action);

                document.save( args[1] );
            }
            finally
            {
                if( document != null )
                {
                    document.close();
                }
            }
        }
    }
View Full Code Here

TOP

Related Classes of org.apache.pdfbox.pdmodel.PDDocument

Copyright © 2018 www.massapicom. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.