Package org.pdfbox.pdmodel

Examples of org.pdfbox.pdmodel.PDDocument


            String userPassword = "";
            String ownerPassword = "";
           
            int keyLength = 48;

            PDDocument document = null;

            try
            {
                for( int i=0; i<args.length; i++ )
                {
                    String key = args[i];
                    if( key.equals( "-O" ) )
                    {
                        ownerPassword = args[++i];
                    }
                    else if( key.equals( "-U" ) )
                    {
                        userPassword = args[++i];
                    }
                    else if( key.equals( "-canAssemble" ) )
                    {
                        ap.setCanAssembleDocument(args[++i].equalsIgnoreCase( "true" ));
                    }
                    else if( key.equals( "-canExtractContent" ) )
                    {
                        ap.setCanExtractContent( args[++i].equalsIgnoreCase( "true" ) );
                    }
                    else if( key.equals( "-canExtractForAccessibility" ) )
                    {
                        ap.setCanExtractForAccessibility( args[++i].equalsIgnoreCase( "true" ) );
                    }
                    else if( key.equals( "-canFillInForm" ) )
                    {
                        ap.setCanFillInForm( args[++i].equalsIgnoreCase( "true" ) );
                    }
                    else if( key.equals( "-canModify" ) )
                    {
                        ap.setCanModify( args[++i].equalsIgnoreCase( "true" ) );
                    }
                    else if( key.equals( "-canModifyAnnotations" ) )
                    {
                        ap.setCanModifyAnnotations( args[++i].equalsIgnoreCase( "true" ) );
                    }
                    else if( key.equals( "-canPrint" ) )
                    {
                        ap.setCanPrint( args[++i].equalsIgnoreCase( "true" ) );
                    }
                    else if( key.equals( "-canPrintDegraded" ) )
                    {
                        ap.setCanPrintDegraded( args[++i].equalsIgnoreCase( "true" ) );
                    }
                    else if( key.equals( "-certFile" ) )
                    {
                        certFile = args[++i];
                    }
                    else if( key.equals( "-keyLength" ) )
                    {
                        try
                        {
                            keyLength = Integer.parseInt( args[++i] );
                        }
                        catch( NumberFormatException e )
                        {
                            throw new NumberFormatException(
                                "Error: -keyLength is not an integer '" + args[i] + "'" );
                        }
                    }
                    else if( infile == null )
                    {
                        infile = key;
                    }
                    else if( outfile == null )
                    {
                        outfile = key;
                    }
                    else
                    {
                        usage();
                    }
                }
                if( infile == null )
                {
                    usage();
                }
                if( outfile == null )
                {
                    outfile = infile;
                }
                document = PDDocument.load( infile );

                if( !document.isEncrypted() )
                {
                    if( certFile != null )
                    {
                        PublicKeyProtectionPolicy ppp = new PublicKeyProtectionPolicy();
                        PublicKeyRecipient recip = new PublicKeyRecipient();
                        recip.setPermission(ap);
                       
                       
                        CertificateFactory cf = CertificateFactory.getInstance("X.509");                           
                        InputStream inStream = new FileInputStream(certFile);
                        X509Certificate certificate = (X509Certificate)cf.generateCertificate(inStream);
                        inStream.close();
                       
                        recip.setX509(certificate);
                       
                        ppp.addRecipient(recip);
                       
                        ppp.setEncryptionKeyLength(keyLength);
                       
                        document.protect(ppp);
                    }
                    else
                    {
                        StandardProtectionPolicy spp =
                            new StandardProtectionPolicy(ownerPassword, userPassword, ap);                       
                        spp.setEncryptionKeyLength(keyLength);
                        document.protect(spp);
                    }
                    document.save( outfile );
                }
                else
                {
                    System.err.println( "Error: Document is already encrypted." );
                }
            }
            finally
            {
                if( document != null )
                {
                    document.close();
                }
            }
        }
    }
View Full Code Here


        if( pdfFile == null )
        {
            usage();
        }

        PDDocument document = null;
        try
        {
            document = PDDocument.load( pdfFile );

            if( document.isEncrypted() )
            {
                document.decrypt( password );
            }
            if( silentPrint )
            {
                document.silentPrint();
            }
            else
            {
                document.print();
            }
        }
        finally
        {
            if( document != null )
            {
                document.close();
            }
        }
    }
View Full Code Here

        importer.importFDF( args );
    }

    private void importFDF( String[] args ) throws Exception
    {
        PDDocument pdf = null;
        FDFDocument fdf = null;

        try
        {
            if( args.length != 3 )
            {
                usage();
            }
            else
            {
                ImportFDF importer = new ImportFDF();

                pdf = PDDocument.load( args[0] );
                fdf = FDFDocument.load( args[1] );
                importer.importFDF( pdf, fdf );
               
                pdf.save( args[2] );
            }
        }
        finally
        {
            close( fdf );
View Full Code Here

        exporter.exportFDF( args );
    }

    private void exportFDF( String[] args ) throws Exception
    {
        PDDocument pdf = null;
        FDFDocument fdf = null;

        try
        {
            if( args.length != 1 && args.length != 2 )
            {
                usage();
            }
            else
            {
                pdf = PDDocument.load( args[0] );
                PDAcroForm form = pdf.getDocumentCatalog().getAcroForm();
                if( form == null )
                {
                    System.err.println( "Error: This PDF does not contain a form." );
                }
                else
View Full Code Here

        }
        else
        {

            Writer output = null;
            PDDocument document = null;
            try
            {
                try
                {
                    //basically try to load it from a url first and if the URL
                    //is not recognized then try to load it from the file system.
                    URL url = new URL( pdfFile );
                    document = PDDocument.load( url );
                    String fileName = url.getFile();
                    if( textFile == null && fileName.length() >4 )
                    {
                        File outputFile =
                            new File( fileName.substring( 0, fileName.length() -4 ) + ".txt" );
                        textFile = outputFile.getName();
                    }
                }
                catch( MalformedURLException e )
                {
                    document = PDDocument.load( pdfFile );
                    if( textFile == null && pdfFile.length() >4 )
                    {
                        textFile = pdfFile.substring( 0, pdfFile.length() -4 ) + ".txt";
                    }
                }
   
                //document.print();
                if( document.isEncrypted() )
                {
                    StandardDecryptionMaterial sdm = new StandardDecryptionMaterial( password );                   
                    document.openProtection( sdm );
                    AccessPermission ap = document.getCurrentAccessPermission();
                   
                    if( ! ap.canExtractContent() )
                    {
                        throw new IOException( "You do not have permission to extract text" );
                    }
                }
                if( toConsole )
                {
                    output = new OutputStreamWriter( System.out );
                }
                else
                {
                    if( encoding != null )
                    {
                        output = new OutputStreamWriter(
                            new FileOutputStream( textFile ), encoding );
                    }
                    else
                    {
                        //use default encoding
                        output = new OutputStreamWriter(
                            new FileOutputStream( textFile ) );
                    }
                }
   
                PDFTextStripper stripper = null;
                if(toHTML)
                {
                   stripper = new PDFText2HTML();
                }
                else
                {
                   stripper = new PDFTextStripper();
                }
                stripper.setSortByPosition( sort );
                stripper.setStartPage( startPage );
                stripper.setEndPage( endPage );
                stripper.writeText( document, output );
            }
            finally
            {
                if( output != null )
                {
                    output.close();
                }
                if( document != null )
                {
                    document.close();
                }
            }
        }
    }
View Full Code Here

        if( outputFile == null || outputFile.equals(inputFile))
        {
            usage();
        }

        PDDocument doc = null;
        try
        {
            doc = PDDocument.load( inputFile );
            if( doc.isEncrypted() )
            {
                try
                {
                    doc.decrypt( password );
                }
                catch( InvalidPasswordException e )
                {
                    if( !password.equals( "" ) )//they supplied the wrong password
                    {
                        System.err.println( "Error: The supplied password is incorrect." );
                        System.exit( 2 );
                    }
                    else
                    {
                        //they didn't suppply a password and the default of "" was wrong.
                        System.err.println( "Error: The document is encrypted." );
                        usage();
                    }
                }
            }
            ConvertColorspace converter = new ConvertColorspace();
            converter.replaceColors(doc, colorEquivalents, destColorspace );
            doc.save( outputFile );
        }
        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

     * @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();
            }
        }
    }
View Full Code Here

                    try {
                        parser = new PDFParser(new BufferedInputStream(in));
                        parser.parse();

                        PDDocument document = parser.getPDDocument();
                        try {
                            CharArrayWriter writer = new CharArrayWriter();

                            PDFTextStripper stripper = new PDFTextStripper();
                            stripper.setLineSeparator("\n");
                            stripper.writeText(document, writer);

                            delegate = new CharArrayReader(writer.toCharArray());
                        } finally {
                            document.close();
                        }
                    } finally {
                        in.close();
                    }
                }
View Full Code Here

                    try {
                        parser = new PDFParser(new BufferedInputStream(in));
                        parser.parse();

                        PDDocument document = parser.getPDDocument();
                        try {
                            CharArrayWriter writer = new CharArrayWriter();

                            PDFTextStripper stripper = new PDFTextStripper();
                            stripper.setLineSeparator("\n");
                            stripper.writeText(document, writer);

                            delegate = new CharArrayReader(writer.toCharArray());
                        } finally {
                            document.close();
                        }
                    } catch (Exception e) {
                        // it may happen that PDFParser throws a runtime
                        // exception when parsing certain pdf documents
                        throw new IOException(e.getMessage());
View Full Code Here

TOP

Related Classes of org.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.