I want to save all the pages of a PDDocument in a seperate pdf file. I programmed it like this:
int numberOfPages = pdDocument.getNumberOfPages();
for (int i = 0; i < numberOfPages; i++) {
PDDocument pageDocument = new PDDocument();
PDPage page = pdDocument.getPage(i);
pageDocument.add(page);
pageDocument.save("c:\temp\page" + (i+1));
}
Is this the correct way to do it? Do I have to create each time a new PDDocument and add the page to it or is there a better way to save the pages of a PDDocument individually?
To be more clear: I want to save each page in a PDDocument in separate pdfs. So, if I have a PDDocument with 25 pages in it, I want to save each page in a separate pdf.
Like this:
-page1.pdf
-page2.pdf
-page3.pdf
...
-page25.pdf
I'm just wondering if I have to make a new PDDocument object for each page to save it to a pdf.
Please try (untested):
PDDocument pageDocument = new PDDocument();
for (int i = 0; i < pdDocument.getNumberOfPages(); i++) {
pageDocument.add(pdDocument.getPage(i));
}
pageDocument.save("c:\temp\page");
It should be possible to add multiple pages to a PDDocument.
Use splitter to split the PDDocument into seperate PDDocuments, simple example can be
Splitter splitter = new Splitter();
splitter.setStartPage(start); //page to start from
splitter.setEndPage(end); //page to end at
List<PDDocument> splittedItems = splitter.split(doc); //doc is original document
for(int index = 0; index < splittedItem.length(); index++){
splittedItem[index].save("destination to save");
}
In your case it would be,
int numberOfPages = pdDocument.getNumberOfPages();
Splitter splitter = new Splitter();
splitter.setStartPage(1);
splitter.setEndPage(numberOfPages); //page to end at
List<PDDocument> splittedItems = splitter.split(pdDocument);
for(int index = 0; index < splittedItem.length(); index++){
splittedItem[index].save("c:\temp\page" + (index+1));
}
For more information you can check out documentation https://pdfbox.apache.org/docs/2.0.3/javadocs/org/apache/pdfbox/multipdf/Splitter.html
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.