Package org.apache.pdfbox.pdmodel

Examples of org.apache.pdfbox.pdmodel.PDDocument


     *
     * @throws COSVisitorException If an error occurs while generating the data.
     */
    public void write(COSDocument doc) throws COSVisitorException
    {
        PDDocument pdDoc = new PDDocument( doc );
        write( pdDoc );
    }
View Full Code Here


        {
            usage();
        }
        else
        {
            PDDocument document = null;
            List<PDDocument> documents = null;
            try
            {
                if (useNonSeqParser)
                {
                    document = PDDocument.loadNonSeq(new File(pdfFile), password);
                }
                else
                {
                    document = PDDocument.load(pdfFile);
                    if( document.isEncrypted() )
                    {
                        try
                        {
                            StandardDecryptionMaterial sdm = new StandardDecryptionMaterial(password);
                            document.openProtection(sdm);
                        }
                        catch( InvalidPasswordException e )
                        {
                            if( args.length == 4 )//they supplied the wrong password
                            {
                                System.err.println( "Error: The supplied password is incorrect." );
                                System.exit( 2 );
                            }
                            else
                            {
                                //they didn't supply a password and the default of "" was wrong.
                                System.err.println( "Error: The document is encrypted." );
                                usage();
                            }
                        }
                    }
                }

                int numberOfPages = document.getNumberOfPages();
                boolean startEndPageSet = false;
                if (startPage != null)
                {
                    splitter.setStartPage(Integer.parseInt( startPage ));
                    startEndPageSet = true;
                    if (split == null)
                    {
                        splitter.setSplitAtPage(numberOfPages);
                    }
                }
                if (endPage != null)
                {
                    splitter.setEndPage(Integer.parseInt( endPage ));
                    startEndPageSet = true;
                    if (split == null)
                    {
                        splitter.setSplitAtPage(Integer.parseInt( endPage ));
                    }
                }
                if (split != null)
                {
                    splitter.setSplitAtPage( Integer.parseInt( split ) );
                }
                else
                {
                    if (!startEndPageSet)
                    {
                        splitter.setSplitAtPage(1);
                    }
                }
                   
                documents = splitter.split( document );
                for( int i=0; i<documents.size(); i++ )
                {
                    PDDocument doc = documents.get( i );
                    String fileName = pdfFile.substring(0, pdfFile.length()-4 ) + "-" + i + ".pdf";
                    writeDocument( doc, fileName );
                    doc.close();
                }

            }
            finally
            {
                if( document != null )
                {
                    document.close();
                }
                for( int i=0; documents != null && i<documents.size(); i++ )
                {
                    PDDocument doc = (PDDocument)documents.get( i );
                    doc.close();
                }
            }
        }
    }
View Full Code Here

            String userPassword = "";
            String ownerPassword = "";

            int keyLength = 40;

            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

    {
        // set visible singature image Input stream
        signatureImageStream(jpegStream);

        // create PD document
        PDDocument document = PDDocument.load(documentStream);

        // calculate height an width of document
        calculatePageSize(document, page);

        document.close();
    }
View Full Code Here

        }
        else
        {

            Writer output = null;
            PDDocument document = null;
            try
            {
                long startTime = startProcessing("Loading PDF "+pdfFile);
                if( outputFile == null && pdfFile.length() >4 )
                {
                    outputFile = new File( pdfFile.substring( 0, pdfFile.length() -4 ) + ext ).getAbsolutePath();
                }
                if (useNonSeqParser)
                {
                    document = PDDocument.loadNonSeq(new File( pdfFile ), password);
                }
                else
                {
                    document = PDDocument.load(pdfFile, force);
                    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" );
                }
               
                stopProcessing("Time for loading: ", startTime);

                if( toConsole )
                {
                    output = new OutputStreamWriter( System.out, encoding );
                }
                else
                {
                    output = new OutputStreamWriter( new FileOutputStream( outputFile ), encoding );
                }

                PDFTextStripper stripper;
                if(toHTML)
                {
                    stripper = new PDFText2HTML();
                }
                else
                {
                    stripper = new PDFTextStripper();
                }
                stripper.setForceParsing( force );
                stripper.setSortByPosition( sort );
                stripper.setShouldSeparateByBeads( separateBeads );
                stripper.setStartPage( startPage );
                stripper.setEndPage( endPage );

                startTime = startProcessing("Starting text extraction");
                if (debug)
                {
                    System.err.println("Writing to "+outputFile);
                }
               
                // Extract text for main document:
                stripper.writeText( document, output );
               
                // ... also for any embedded PDFs:
                PDDocumentCatalog catalog = document.getDocumentCatalog();
                PDDocumentNameDictionary names = catalog.getNames();   
                if (names != null)
                {
                    PDEmbeddedFilesNameTreeNode embeddedFiles = names.getEmbeddedFiles();
                    if (embeddedFiles != null)
                    {
                        Map<String,COSObjectable> embeddedFileNames = embeddedFiles.getNames();
                        if (embeddedFileNames != null) {
                            for (Map.Entry<String,COSObjectable> ent : embeddedFileNames.entrySet())
                            {
                                if (debug)
                                {
                                    System.err.println("Processing embedded file " + ent.getKey() + ":");
                                }
                                PDComplexFileSpecification spec = (PDComplexFileSpecification) ent.getValue();
                                PDEmbeddedFile file = spec.getEmbeddedFile();
                                if (file != null && file.getSubtype().equals("application/pdf"))
                                {
                                    if (debug)
                                    {
                                        System.err.println("  is PDF (size=" + file.getSize() + ")");
                                    }
                                    InputStream fis = file.createInputStream();
                                    PDDocument subDoc = null;
                                    try
                                    {
                                        subDoc = PDDocument.load(fis);
                                    }
                                    finally
                                    {
                                        fis.close();
                                    }
                                    try
                                    {
                                        stripper.writeText( subDoc, output );
                                    }
                                    finally
                                    {
                                        subDoc.close();
                                    }
                                }
                            }
                        }
                    }
View Full Code Here

        exporter.exportXFDF( args );
    }

    private void exportXFDF( 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

        System.exit(1);
    }

    private void extract(String pdfFile, String password, boolean useNonSeq) throws IOException
    {
        PDDocument document = null;
        try
        {
            if (useNonSeq)
            {
                document = PDDocument.loadNonSeq(new File(pdfFile), password);
            }
            else
            {
                document = PDDocument.load(pdfFile);

                if (document.isEncrypted())
                {
                    StandardDecryptionMaterial spm = new StandardDecryptionMaterial(password);
                    document.openProtection(spm);
                }
            }
            AccessPermission ap = document.getCurrentAccessPermission();
            if (! ap.canExtractContent())
            {
                throw new IOException("You do not have permission to extract images");
            }

            for (int i = 0; i < document.getNumberOfPages(); i++) // todo: ITERATOR would be much better
            {
                PDPage page = document.getPage(i);
                ImageGraphicsEngine extractor = new ImageGraphicsEngine(page);
                extractor.run();
            }
        }
        finally
        {
            if (document != null)
            {
                document.close();
            }
        }
    }
View Full Code Here

     *
     * @throws IOException If there is an error writing the data.
     */
    public PDDocument createPDFFromText( Reader text ) throws IOException
    {
        PDDocument doc = null;
        try
        {

            final int margin = 40;
            float height = font.getBoundingBox().getHeight() / 1000;

            //calculate font height and increase by 5 percent.
            height = height*fontSize*1.05f;
            doc = new PDDocument();
            BufferedReader data = new BufferedReader( text );
            String nextLine = null;
            PDPage page = new PDPage();
            PDPageContentStream contentStream = null;
            float y = -1;
            float maxStringLength = page.getMediaBox().getWidth() - 2*margin;

            // There is a special case of creating a PDF document from an empty string.
            boolean textIsEmpty = true;

            while( (nextLine = data.readLine()) != null )
            {

                // The input text is nonEmpty. New pages will be created and added
                // to the PDF document as they are needed, depending on the length of
                // the text.
                textIsEmpty = false;

                String[] lineWords = nextLine.trim().split( " " );
                int lineIndex = 0;
                while( lineIndex < lineWords.length )
                {
                    StringBuffer nextLineToDraw = new StringBuffer();
                    float lengthIfUsingNextWord = 0;
                    do
                    {
                        nextLineToDraw.append( lineWords[lineIndex] );
                        nextLineToDraw.append( " " );
                        lineIndex++;
                        if( lineIndex < lineWords.length )
                        {
                            String lineWithNextWord = nextLineToDraw.toString() + lineWords[lineIndex];
                            lengthIfUsingNextWord =
                                (font.getStringWidth( lineWithNextWord )/1000) * fontSize;
                        }
                    }
                    while( lineIndex < lineWords.length &&
                           lengthIfUsingNextWord < maxStringLength );
                    if( y < margin )
                    {
                        // We have crossed the end-of-page boundary and need to extend the
                        // document by another page.
                        page = new PDPage();
                        doc.addPage( page );
                        if( contentStream != null )
                        {
                            contentStream.endText();
                            contentStream.close();
                        }
                        contentStream = new PDPageContentStream(doc, page);
                        contentStream.setFont( font, fontSize );
                        contentStream.beginText();
                        y = page.getMediaBox().getHeight() - margin + height;
                        contentStream.moveTextPositionByAmount(
                            margin, y );

                    }
                    //System.out.println( "Drawing string at " + x + "," + y );

                    if( contentStream == null )
                    {
                        throw new IOException( "Error:Expected non-null content stream." );
                    }
                    contentStream.moveTextPositionByAmount( 0, -height);
                    y -= height;
                    contentStream.drawString( nextLineToDraw.toString() );
                }


            }

            // If the input text was the empty string, then the above while loop will have short-circuited
            // and we will not have added any PDPages to the document.
            // So in order to make the resultant PDF document readable by Adobe Reader etc, we'll add an empty page.
            if (textIsEmpty)
            {
                doc.addPage(page);
            }

            if( contentStream != null )
            {
                contentStream.endText();
                contentStream.close();
            }
        }
        catch( IOException io )
        {
            if( doc != null )
            {
                doc.close();
            }
            throw io;
        }
        return doc;
    }
View Full Code Here

    {
        // suppress the Dock icon on OS X
        System.setProperty("apple.awt.UIElement", "true");

        TextToPDF app = new TextToPDF();
        PDDocument doc = null;
        try
        {
            if( args.length < 2 )
            {
                app.usage();
            }
            else
            {
                for( int i=0; i<args.length-2; i++ )
                {
                    if( args[i].equals( "-standardFont" ))
                    {
                        i++;
                        app.setFont( getStandardFont( args[i] ));
                    }
                    else if( args[i].equals( "-ttf" ))
                    {
                        i++;
                        PDTrueTypeFont font = PDTrueTypeFont.loadTTF( doc, new File( args[i]));
                        app.setFont( font );
                    }
                    else if( args[i].equals( "-fontSize" ))
                    {
                        i++;
                        app.setFontSize( Integer.parseInt( args[i] ) );
                    }
                    else
                    {
                        throw new IOException( "Unknown argument:" + args[i] );
                    }
                }
                doc = app.createPDFFromText( new FileReader( args[args.length-1] ) );
                doc.save( args[args.length-2] );
            }
        }
        finally
        {
            if( doc != null )
            {
                doc.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

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.