Package org.apache.pdfbox.pdmodel

Examples of org.apache.pdfbox.pdmodel.PDDocument


        mergeDocuments(true, scratchFile);
    }

    private void mergeDocuments(boolean isNonSeq, RandomAccess scratchFile) throws IOException
    {
        PDDocument destination = null;
        InputStream sourceFile;
        PDDocument source;
        if (sources != null && sources.size() > 0)
        {
            ArrayList<PDDocument> tobeclosed = new ArrayList<PDDocument>();

            try
            {
                Iterator<InputStream> sit = sources.iterator();
                destination = new PDDocument();

                while (sit.hasNext())
                {
                    sourceFile = sit.next();
                    if (isNonSeq)
View Full Code Here


   
    /**
     * Test of extract method, of class org.apache.pdfbox.util.PageExtractor.
     */
    public void testExtract() throws Exception {
        PDDocument sourcePdf = null;
        PDDocument result = null;
        try {
            try {
                // this should work for most users
                sourcePdf = PDDocument.load("src/test/resources/input/cweb.pdf");
            } catch(IOException e) {
                // in case your directory structure is different, just change this to be the correct path
                sourcePdf = PDDocument.load("pdfbox/pdfbox/src/test/resources/input/cweb.pdf");
            }
            PageExtractor instance = new PageExtractor(sourcePdf);
            result = instance.extract();
            assertEquals(sourcePdf.getNumberOfPages(), result.getNumberOfPages());
            closeDoc(result);
           
            instance = new PageExtractor(sourcePdf, 1, 1);
            result = instance.extract();
            assertEquals(1, result.getNumberOfPages());
            closeDoc(result);
           
            instance = new PageExtractor(sourcePdf, 1, 5);
            result = instance.extract();
            assertEquals(5, result.getNumberOfPages());
            closeDoc(result);
           
            instance = new PageExtractor(sourcePdf, 5, 10);
            result = instance.extract();
            assertEquals(6, result.getNumberOfPages());
            closeDoc(result);
           
            instance = new PageExtractor(sourcePdf, 2, 1);
            result = instance.extract();
            assertEquals(0, result.getNumberOfPages());
            closeDoc(result);
        } finally {
            closeDoc(sourcePdf);
            closeDoc(result);
        }
View Full Code Here

     *
     * @throws IOException If there is an error writing the data.
     */
    public void create(String file) throws IOException
    {
        PDDocument document = null;
        try
        {
            document = new PDDocument();
            PDPage page = new PDPage();
            document.addPage(page);

            // type 2 (exponential) function with attributes
            // can be used by both shadings
            COSDictionary fdict = new COSDictionary();
            fdict.setInt(COSName.FUNCTION_TYPE, 2);
            COSArray domain = new COSArray();
            domain.add(COSInteger.get(0));
            domain.add(COSInteger.get(1));
            COSArray c0 = new COSArray();
            c0.add(COSFloat.get("1"));
            c0.add(COSFloat.get("0"));
            c0.add(COSFloat.get("0"));
            COSArray c1 = new COSArray();
            c1.add(COSFloat.get("0.5"));
            c1.add(COSFloat.get("1"));
            c1.add(COSFloat.get("0.5"));
            fdict.setItem(COSName.DOMAIN, domain);
            fdict.setItem(COSName.C0, c0);
            fdict.setItem(COSName.C1, c1);
            fdict.setInt(COSName.N, 1);
            PDFunctionType2 func = new PDFunctionType2(fdict);

            // axial shading with attributes
            PDShadingType2 axialShading = new PDShadingType2(new COSDictionary());
            axialShading.setColorSpace(PDDeviceRGB.INSTANCE);
            axialShading.setShadingType(PDShading.SHADING_TYPE2);
            COSArray coords1 = new COSArray();
            coords1.add(COSInteger.get(100));
            coords1.add(COSInteger.get(400));
            coords1.add(COSInteger.get(400));
            coords1.add(COSInteger.get(600));
            axialShading.setCoords(coords1);
            axialShading.setFunction(func);

            // radial shading with attributes
            PDShadingType3 radialShading = new PDShadingType3(new COSDictionary());
            radialShading.setColorSpace(PDDeviceRGB.INSTANCE);
            radialShading.setShadingType(PDShading.SHADING_TYPE3);
            COSArray coords2 = new COSArray();
            coords2.add(COSInteger.get(100));
            coords2.add(COSInteger.get(400));
            coords2.add(COSInteger.get(50)); // radius1
            coords2.add(COSInteger.get(400));
            coords2.add(COSInteger.get(600));
            coords2.add(COSInteger.get(150)); // radius2
            radialShading.setCoords(coords2);
            radialShading.setFunction(func);

            // create resources
            PDResources resources = new PDResources();
            page.setResources(resources);
           
            // add shading to resources

            // use put() if you want a specific name
            resources.put(COSName.getPDFName("shax"), axialShading);
           
            // use add() if you want PDFBox to decide the name for you
            COSName radialShadingName = resources.add(radialShading);

            // invoke shading from content stream
            // the raw command is "/name sh"
            // replace "name" with the name of the shading
            // compress parameter is set to false so that you can see the stream in a text editor
            PDPageContentStream contentStream = new PDPageContentStream(document, page, true, false);
            contentStream.appendRawCommands("/shax sh\n");
            contentStream.appendRawCommands("/" + radialShadingName.getName() + " sh\n");
            contentStream.close();
           
            document.save(file);
            document.close();
           
            // render the PDF and save it into a PNG file
            document = PDDocument.loadNonSeq(new File(file));
            BufferedImage bim = new PDFRenderer(document).renderImageWithDPI(0, 300);
            ImageIO.write(bim, "png", new File(file + ".png"));
            document.close();
        }
        finally
        {
            if (document != null)
            {
                document.close();
            }
        }
    }
View Full Code Here

    {
        File mainPDF = createMainPDF();
        File overlay1 = createOverlay1();
        File targetFile = new File(testResultsDir, "text-with-form-overlay.pdf");

        PDDocument targetDoc = PDDocument.load(mainPDF);
        PDDocument overlay1Doc = PDDocument.load(overlay1);
        try
        {
            LayerUtility layerUtil = new LayerUtility(targetDoc);
            PDFormXObject form = layerUtil.importPageAsForm(overlay1Doc, 0);
            PDPage targetPage = targetDoc.getPage(0);
            layerUtil.wrapInSaveRestore(targetPage);
            AffineTransform at = new AffineTransform();
            PDOptionalContentGroup ocg = layerUtil.appendFormAsLayer(
                    targetPage, form, at, "overlay");

            //This is how the layer could be disabled after adding it
            //catalog.getOCProperties().setGroupEnabled(ocg.getName(), false);

            targetDoc.save(targetFile.getAbsolutePath());
        }
        finally
        {
            targetDoc.close();
            overlay1Doc.close();
        }

        PDDocument doc = PDDocument.load(targetFile);
        try
        {
            PDDocumentCatalog catalog = doc.getDocumentCatalog();

            //OCGs require PDF 1.5 or later
            //TODO need some comfortable way to enable/check the PDF version
            //assertEquals("%PDF-1.5", doc.getDocument().getHeaderString());
            //assertEquals("1.5", catalog.getVersion());

            PDPage page = doc.getPage(0);
            PDOptionalContentGroup ocg = (PDOptionalContentGroup)page.getResources()
                    .getProperties(COSName.getPDFName("MC0"));
            assertNotNull(ocg);
            assertEquals("overlay", ocg.getName());

            PDOptionalContentProperties ocgs = catalog.getOCProperties();
            PDOptionalContentGroup overlay = ocgs.getGroup("overlay");
            assertEquals(ocg.getName(), overlay.getName());
        }
        finally
        {
            doc.close();
        }
    }
View Full Code Here

    }

    private File createMainPDF() throws IOException
    {
        File targetFile = new File(testResultsDir, "text-doc.pdf");
        PDDocument doc = new PDDocument();
        try
        {
            //Create new page
            PDPage page = new PDPage();
            doc.addPage(page);
            PDResources resources = page.getResources();
            if( resources == null )
            {
                resources = new PDResources();
                page.setResources( resources );
            }

            final String[] text = new String[] {
                    "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Integer fermentum lacus in eros",
                    "condimentum eget tristique risus viverra. Sed ac sem et lectus ultrices placerat. Nam",
                    "fringilla tincidunt nulla id euismod. Vivamus eget mauris dui. Mauris luctus ullamcorper",
                    "leo, et laoreet diam suscipit et. Nulla viverra commodo sagittis. Integer vitae rhoncus velit.",
                    "Mauris porttitor ipsum in est sagittis non luctus purus molestie. Sed placerat aliquet",
                    "vulputate."
            };

            //Setup page content stream and paint background/title
            PDPageContentStream contentStream = new PDPageContentStream(doc, page, false, false);
            PDFont font = PDType1Font.HELVETICA_BOLD;
            contentStream.beginText();
            contentStream.moveTextPositionByAmount(50, 720);
            contentStream.setFont(font, 14);
            contentStream.drawString("Simple test document with text.");
            contentStream.endText();
            font = PDType1Font.HELVETICA;
            contentStream.beginText();
            int fontSize = 12;
            contentStream.setFont(font, fontSize);
            contentStream.moveTextPositionByAmount(50, 700);
            for (String line : text)
            {
                contentStream.moveTextPositionByAmount(0, -fontSize * 1.2f);
                contentStream.drawString(line);
            }
            contentStream.endText();
            contentStream.close();

            doc.save(targetFile.getAbsolutePath());
        }
        finally
        {
            doc.close();
        }
        return targetFile;
    }
View Full Code Here

     * @throws IOException If there is an error writing the data.
     */
    public void doIt( String message, String  outfile ) throws IOException
    {
        // the document
        PDDocument doc = null;
        try
        {
            doc = new PDDocument();

            PDFont font = PDType1Font.HELVETICA;
            PDPage page = new PDPage(PDRectangle.A4);
            page.setRotation(90);
            doc.addPage(page);
            PDRectangle pageSize = page.getMediaBox();
            float pageWidth = pageSize.getWidth();
            float fontSize = 12;
            float stringWidth = font.getStringWidth( message )*fontSize/1000f;
            float startX = 100;
            float startY = 100;
            PDPageContentStream contentStream = new PDPageContentStream(doc, page, false, false);
            // add the rotation using the current transformation matrix
            // including a translation of pageWidth to use the lower left corner as 0,0 reference
            contentStream.concatenate2CTM(0, 1, -1, 0, pageWidth, 0);
            contentStream.setFont( font, fontSize );
            contentStream.beginText();
            contentStream.moveTextPositionByAmount(startX, startY);
            contentStream.drawString( message);
            contentStream.moveTextPositionByAmount(0, 100);
            contentStream.drawString( message);
            contentStream.moveTextPositionByAmount(100, 100);
            contentStream.drawString( message);
            contentStream.endText();
           
            contentStream.drawLine(startX-2, startY-2, startX-2, startY+200+fontSize);
            contentStream.drawLine(startX-2, startY+200+fontSize, startX+100+stringWidth+2, startY+200+fontSize);
            contentStream.drawLine(startX+100+stringWidth+2, startY+200+fontSize, startX+100+stringWidth+2, startY-2);
            contentStream.drawLine(startX+100+stringWidth+2, startY-2, startX-2, startY-2);
            contentStream.close();

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

    }

    private File createOverlay1() throws IOException
    {
        File targetFile = new File(testResultsDir, "overlay1.pdf");
        PDDocument doc = new PDDocument();
        try
        {
            //Create new page
            PDPage page = new PDPage();
            doc.addPage(page);
            PDResources resources = page.getResources();
            if( resources == null )
            {
                resources = new PDResources();
                page.setResources( resources );
            }

            //Setup page content stream and paint background/title
            PDPageContentStream contentStream = new PDPageContentStream(doc, page, false, false);
            PDFont font = PDType1Font.HELVETICA_BOLD;
            contentStream.setNonStrokingColor(Color.LIGHT_GRAY);
            contentStream.beginText();
            float fontSize = 96;
            contentStream.setFont(font, fontSize);
            String text = "OVERLAY";
            //float sw = font.getStringWidth(text);
            //Too bad, base 14 fonts don't return character metrics.
            PDRectangle crop = page.getCropBox();
            float cx = crop.getWidth() / 2f;
            float cy = crop.getHeight() / 2f;
            AffineTransform transform = new AffineTransform();
            transform.translate(cx, cy);
            transform.rotate(Math.toRadians(45));
            transform.translate(-190 /* sw/2 */, 0);
            contentStream.setTextMatrix(transform);
            contentStream.drawString(text);
            contentStream.endText();
            contentStream.close();

            doc.save(targetFile.getAbsolutePath());
        }
        finally
        {
            doc.close();
        }
        return targetFile;
    }
View Full Code Here

    {
        String formTemplate = "src/main/resources/org/apache/pdfbox/examples/acroforms/FillFormField.pdf";
        String filledForm = "target/examples-output/FillFormField.pdf";
       
        // load the document
        PDDocument pdfDocument = PDDocument
                .loadNonSeq(new File(formTemplate),null);

        // get the document catalog
        PDAcroForm acroForm = pdfDocument.getDocumentCatalog().getAcroForm();
       
        // as there might not be an AcroForm entry a null check is necessary
        if (acroForm != null)
        {
            // Retrieve an individual field and set it's value.
            PDFieldTreeNode field = acroForm.getField( "sampleField" );
            field.setValue("Text Entry");

            // If a field is nested within the form tree a fully qualified name
            // might be provided to access the field.
            field = acroForm.getField( "fieldsContainer.nestedSampleField" );
            field.setValue("Text Entry");
        }

        // Save and close the filled out form.
        pdfDocument.save(filledForm);
        pdfDocument.close();
    }
View Full Code Here

     *
     * @throws IOException If there is an problem creating the new document.
     */
    protected PDDocument createNewDocument() throws IOException
    {
        PDDocument document = new PDDocument();
        document.setDocumentInformation(getSourceDocument().getDocumentInformation());
        document.getDocumentCatalog().setViewerPreferences(
                getSourceDocument().getDocumentCatalog().getViewerPreferences());
        return document;
    }
View Full Code Here

        {
            usage();
        }
        else
        {
            PDDocument document = null;
            try
            {
                document = PDDocument.load( args[0] );
                if( document.isEncrypted() )
                {
                    try
                    {
                        StandardDecryptionMaterial sdm = new StandardDecryptionMaterial("");
                        document.openProtection(sdm);
                    }
                    catch( InvalidPasswordException e )
                    {
                        System.err.println( "Error: Document is encrypted with a password." );
                        System.exit( 1 );
                    }
                }
                PrintTextLocations printer = new PrintTextLocations();
                int pageNum = 0;
                for( PDPage page : document.getPages() )
                {
                    pageNum++;
                    System.out.println( "Processing page: " + pageNum );
                    PDStream contents = page.getStream();
                    if( contents != null )
                    {
                        printer.processPage(page);
                    }
                }
            }
            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.