import java.io.File; import java.io.IOException; import java.util.Random; import org.apache.pdfbox.io.MemoryUsageSetting; import org.apache.pdfbox.multipdf.PDFMergerUtility; 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 MergePDFs { public static void main(String[] args) { try { //Creating PDF document object String myPDF1 = "docs/my_doc1.pdf"; PDDocument document1 = new PDDocument(); //Add Random number of Pages in your document Random generator = new Random(); int myCount = generator.nextInt(10) + 1; for(int i=0; i < myCount; i++){ PDPage page = new PDPage(PDRectangle.LETTER); document1.addPage(page); addText(document1,page,i+1); } document1.save(myPDF1); document1.close(); //Creating PDF document object String myPDF2 = "docs/my_doc2.pdf"; PDDocument document2 = new PDDocument(); //Add Random number of Pages in your document int newCount = generator.nextInt(10) + myCount + 1; for(int i=myCount; i < newCount; i++){ PDPage page = new PDPage(PDRectangle.LETTER); document2.addPage(page); addText(document2,page,i+1); } document2.save(myPDF2); document2.close(); //Now let's merge the 2 documents //instantiate the merge utility class File file1 = new File(myPDF1); File file2 = new File(myPDF2); PDFMergerUtility pdfMerger = new PDFMergerUtility(); pdfMerger.setDestinationFileName("docs/merged.pdf"); pdfMerger.addSource(file1); pdfMerger.addSource(file2); pdfMerger.mergeDocuments(MemoryUsageSetting.setupMainMemoryOnly()); file1.delete(); file2.delete(); } 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(); } } }
All one can think and do in a short time is to think what one already knows and to do as one has always done!
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.