Add Remove PDF Pages - Apache PDFBox example

import java.io.File;
import java.io.IOException;
import java.util.Random;

import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPage;
import org.apache.pdfbox.pdmodel.PDPageContentStream;
import org.apache.pdfbox.pdmodel.common.PDRectangle;
import org.apache.pdfbox.pdmodel.font.PDType1Font;


public class AddRemovePDFPages {

	public static void main(String[] args) {

		try {

			//Creating PDF document object 
			String myPDF = "docs/my_doc.pdf";
			PDDocument document = new PDDocument();

			//Add Random number of Pages in your document
			Random generator = new Random();
			int myCount = generator.nextInt(20) + 1;
			for(int i=0; i < myCount; i++){
				PDPage page = new PDPage(PDRectangle.LETTER);
				document.addPage(page);
				addText(document,page,i+1);
			}

			//Saving the document
			document.save(myPDF);
			//Closing the document  
			document.close();

			//Let load the PDF for manipulation now
			File file = new File(myPDF);
			PDDocument doc = PDDocument.load(file);

			//Let's get rid of a Random page
			int pageNo = generator.nextInt(myCount) + 1;
			doc.removePage(pageNo);

			//Saving the document
			doc.save(myPDF);
			//Closing the document  
			doc.close();

			//It fun time now lets see what happened, 
			//how many pages were added and which one got deleted!


		} catch (IOException e) {
			e.printStackTrace();
		}

	}

	private static void addText(PDDocument document, PDPage page, int pageNo) {

		try {

			PDPageContentStream contentStream = new PDPageContentStream(document, page, PDPageContentStream.AppendMode.APPEND, true);
			contentStream.beginText(); 
			contentStream.setFont(PDType1Font.HELVETICA, 12);
			contentStream.newLineAtOffset(25,750);
			contentStream.showText("This is Page No: " + pageNo);      
			contentStream.endText();
			contentStream.close();

		} catch (IOException e) {
			e.printStackTrace();
		}

	}


}

No comments:

Post a Comment

NO JUNK, Please try to keep this clean and related to the topic at hand.
Comments are for users to ask questions, collaborate or improve on existing.