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");

    }