Monday, November 3, 2014

Creating Multipage pdf using pdfbox



Creating multiple page  pdf using pdfbox is easy , if you know the basics in pdfbox. For creating pdf using pdfbox you must create pdf document first.

PDDocument doc = new PDDocument();

This will create a blank pdf document. Then you have to create a page for this document

PDPage page = new PDPage();

Then add the page to document

doc.addPage( page );

then you can add content to the page using contentStream

PDPageContentStream contentStream =new PDPageContentStream(doc, page);

so now we are going to add another page to the document using the same procedure

PDPage page1 = new PDPage();

 doc.addPage(page1);

 PDPageContentStream contentStream1 =new PDPageContentStream(doc, page1);

finally you have close the content stream to store what you written to page. Then give a name to save this file

contentStream.close();

contentStream1.close();

doc.save("d:/test2.pdf" );

if you run all the code that are mentioned in the above, that will create a empty 2 page pdf document on d drive.
The full code is shown below

public static void main(String[] args) throws IOException, COSVisitorException{

    PDDocument doc = new PDDocument();

    PDPage page = new PDPage();

    PDPage page1 = new PDPage();

    doc.addPage( page );

    doc.addPage(page1);

    PDPageContentStream contentStream =

                    new PDPageContentStream(doc, page);

 PDPageContentStream contentStream1 =

                    new PDPageContentStream(doc, page1);

    contentStream.close();

    contentStream1.close();

    doc.save("d:/test22.pdf" );

    System.out.println("done");

    }

Thursday, August 21, 2014

PDFBOX Tutorial - Creating table in pdf Using PDFBOX



Creating table in pdf using PDFBOX is the hectic work ever. Because it don’t have any specific procedure to create table. It uses our hand drawing table model using scale.   If  I want to draw table in A4 size paper, first we have to know the width and height of A4 sheet and then draw lines based on x-axis y-axis mode. Starting x,y values and ending x,y values are required to draw line.

Below is the sample code for creating table in PDFBOX for A4size paper
A4 paper width is 595.27563  and height is 841.8898(in PDFBOX terminology)

In the below code first I created horizontal lines(row- changing y axis value) and then vertical lines(column- changing x axis value) . And also I attached output pdf table as image here
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPage;
import org.apache.pdfbox.pdmodel.common.PDRectangle;
import org.apache.pdfbox.pdmodel.edit.PDPageContentStream;

/**
 *
 * @author Bharathi Raja
 */
public class CreatePDFBOXTable {

    public static void main(String[] args) {
        try {
            createTable();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void createTable() throws Exception {
        String path = "d:\\tablepdf.pdf";  //location to store the pdf file
        PDDocument document = new PDDocument();
        PDPage page = new PDPage(PDPage.PAGE_SIZE_A4);
        document.addPage(page);
        PDPageContentStream contentStream = new PDPageContentStream(document, page);

        PDRectangle mediabox = page.findMediaBox();
        float margin = 50;
        float startX = mediabox.getLowerLeftX() + margin;
        float startY = mediabox.getUpperRightY() - margin;
        final int rows = 3;
        final float rowHeight = 20f;
      
        final float tableWidth = page.findMediaBox().getWidth() - (2 * margin);
       
        //draw the rows
        float nexty = 650;
        for (int i = 0; i <= rows; i++) {
            if (i == 0 || i == 1) {
                contentStream.drawLine(margin, nexty, margin + tableWidth, nexty);
            }
            nexty -= rowHeight;
        }

        contentStream.drawLine(margin, 300, margin + tableWidth, 300);
        int y = 650;
       
        //drawing columns the columns
        float nextx = 50;
       
        int h = 300;
        contentStream.drawLine(nextx, y, nextx, h);
        nextx = 100;
        contentStream.drawLine(nextx, y, nextx, h);
        nextx = 350;
        contentStream.drawLine(nextx, y, nextx, h);
        nextx = 420;
        contentStream.drawLine(nextx, y, nextx, h);
        nextx = 475;
        contentStream.drawLine(nextx, y, nextx, h);
        nextx = 545;
        contentStream.drawLine(nextx, y, nextx, h);
    //now add the text

       
        contentStream.close();

        document.save(path);
        document.close();
        System.out.println("done");
    }

}

Wednesday, June 4, 2014

pdfbox tutorial - pdfbox encrypt pdf- password protected pdf

pdfbox  tutorial - pdfbox encrypt pdf
use the below link to check out various options for PDFBOX Encryption

http://pdfbox.apache.org/commandline/#encrypt

below code used to apply encryption to the file

here
 encrypt.encrypt( args );
 
the medium to pass password to the file
 
for examlpe
 
change the  encrypt.encrypt( args ); to  
 encrypt.encrypt( new String[]{"-U","mypassword"} ); 
 
if u try to open the file now means it will ask a password so here our password is 
mypassword
 
and change the infile and outfile as location to ur existing pdf file 

import java.io.FileInputStream;
import java.io.InputStream;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;

import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.encryption.AccessPermission;
import org.apache.pdfbox.pdmodel.encryption.PublicKeyProtectionPolicy;
import org.apache.pdfbox.pdmodel.encryption.PublicKeyRecipient;
import org.apache.pdfbox.pdmodel.encryption.StandardProtectionPolicy;

/**
 * This will read a document from the filesystem, encrypt it and and then write
 * the results to the filesystem. <br/><br/>
 *
 * @author  <a href="mailto:ben@benlitchfield.com">Ben Litchfield</a>
 * @version $Revision: 1.9 $
 */
public class Encrypt
{
    private Encrypt()
    {
    }

    /**
     * This is the entry point for the application.
     *
     * @param args The command-line arguments.
     *
     * @throws Exception If there is an error decrypting the document.
     */
    public static void main( String[] args ) throws Exception
    {
        Encrypt encrypt = new Encrypt();
        encrypt.encrypt( args );
    }

    private void encrypt( String[] args ) throws Exception
    {
        if( args.length < 1 )
        {
            usage();
        }
        else
        {
            AccessPermission ap = new AccessPermission();

            String infile = null;
            String outfile = null;
            String certFile = null;
            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();
                }
            }
        }
    }

    /**
     * This will print a usage message.
     */
    private static void usage()
    {
        System.err.println( "usage: java org.apache.pdfbox.Encrypt [options] <inputfile> [outputfile]" );
        System.err.println( "   -O <password>                            " +
                                            "Set the owner password(ignored if cert is set)" );
        System.err.println( "   -U <password>                            " +
                                            "Set the user password(ignored if cert is set)" );
        System.err.println( "   -certFile <path to cert>                 Path to X.509 certificate" );
        System.err.println( "   -canAssemble <true|false>                Set the assemble permission" );
        System.err.println( "   -canExtractContent <true|false>          Set the extraction permission" );
        System.err.println( "   -canExtractForAccessibility <true|false> Set the extraction permission" );
        System.err.println( "   -canFillInForm <true|false>              Set the fill in form permission" );
        System.err.println( "   -canModify <true|false>                  Set the modify permission" );
        System.err.println( "   -canModifyAnnotations <true|false>       Set the modify annots permission" );
        System.err.println( "   -canPrint <true|false>                   Set the print permission" );
        System.err.println( "   -canPrintDegraded <true|false>           Set the print degraded permission" );
        System.err.println( "   -keyLength <length>                      The length of the key in bits(40)" );
        System.err.println( "\nNote: By default all permissions are set to true!" );
        System.exit( 1 );
    }

}

Thursday, April 10, 2014

PDFBOX tutorial - Create New PDF Document and Writing Text inside that PDF Document Using PDFBox- A4 size pdf

Here am going to explaing how to create a A4 size PDF using PDFBox library

import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPage;
import org.apache.pdfbox.pdmodel.edit.PDPageContentStream;
import org.apache.pdfbox.pdmodel.font.PDFont;
import org.apache.pdfbox.pdmodel.font.PDType1Font;

/**
 *
 * @author Bharathi
 */
public class Printing1 {

    public static void main(String[] args) throws Exception {



        PDDocument document = new PDDocument();
        PDPage page = new PDPage(PDPage.PAGE_SIZE_A4);

        document.addPage(page);
        PDPageContentStream contentStream = new PDPageContentStream(document, page);
        PDFont pdfFont = PDType1Font.HELVETICA;
        float fontSize = 12;
        contentStream.beginText();
        contentStream.setFont(pdfFont, fontSize);
        contentStream.moveTextPositionByAmount(100, 100);
        contentStream.drawString("Customer Name    : Bharathiraja");
        contentStream.endText();


        contentStream.close();
        document.save("d:/demo123.pdf");
        document.close();
        System.out.println("Done");
    }
}

-----------------------------------------------------
Step1: Create a empty PDF document using PDDocument class
Step2: Create a page based on your requirement. PDPage has more options like A4,A3 etc


Step3: ContentStream is used to write text inside the document. It uses the x axis and y axis concept to place text in the Document
Step4: close the stream and save the document inside your hard disk and close the document