赞
踩
要将一个 PDF 文档拆分为多个 PDF 文档,您可以使用 PDFBox Java API 的 Splitter.split() 方法。
在本教程中,我们将学习使用示例 Java 程序拆分 PDF 文档。
在此示例中,我们将采用多页 PDF,并将此 PDF 文档拆分为多个 PDF,其中每个生成的 PDF 文档仅包含源文档中的一页。
SplitPDFExample.java
import org.apache.pdfbox.multipdf.Splitter;
import org.apache.pdfbox.pdmodel.PDDocument;
import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.Iterator;
public class SplitPDFExample {
public static void main(String[] args) throws IOException {
File file = new File( "/home/tk/sample_pdf.pdf" );
// load pdf file
PDDocument document = PDDocument.load(file);
// instantiating Splitter
Splitter splitter = new Splitter();
// split the pages of a PDF document
List<PDDocument> Pages = splitter.split(document);
// Creating an iterator
Iterator<PDDocument> iterator = Pages.listIterator();
// saving splits as pdf
int i = 0 ;
while (iterator.hasNext()) {
PDDocument pd = iterator.next();
// provide destination path to the PDF split
pd.save( "/home/tk/pdfs/sample_part_" + ++i + ".pdf" );
System.out.println( "Saved /home/tk/pdfs/sample_part_" + i + ".pdf" );
}
System.out.println( "Provided PDF has been split into multiple." );
document.close();
}
}
|
输出
Saved /home/tk/pdfs/sample_part_1.pdf
Saved /home/tk/pdfs/sample_part_2.pdf
Saved /home/tk/pdfs/sample_part_3.pdf
Saved /home/tk/pdfs/sample_part_4.pdf
Saved /home/tk/pdfs/sample_part_5.pdf
Saved /home/tk/pdfs/sample_part_6.pdf
Provided PDF has been split into multiple.
|
以下是将 PDF 文档拆分为多个 PDF 文档的分步指南,这些文档已在源文档中以特定间隔拆分。
SplitPDFAtPageExample.java
import org.apache.pdfbox.multipdf.Splitter;
import org.apache.pdfbox.pdmodel.PDDocument;
import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.Iterator;
public class SplitPDFAtPageExample {
public static void main(String[] args) throws IOException {
File file = new File( "/home/tk/sample_pdf.pdf" );
// load pdf file
PDDocument document = PDDocument.load(file);
// instantiating Splitter
Splitter splitter = new Splitter();
splitter.setSplitAtPage( 2 );
// split the pages of a PDF document
List<PDDocument> Pages = splitter.split(document);
// Creating an iterator
Iterator<PDDocument> iterator = Pages.listIterator();
// saving splits as pdf
int i = 0 ;
while (iterator.hasNext()) {
PDDocument pd = iterator.next();
pd.save( "/home/tk/pdfs/sample_part_" + ++i + ".pdf" );
System.out.println( "Saved /home/tk/pdfs/sample_part_" + i + ".pdf" );
}
// close the document
document.close();
}
}
|
输出
Saved /home/tk/pdfs/sample_part_1.pdf
Saved /home/tk/pdfs/sample_part_2.pdf
Saved /home/tk/pdfs/sample_part_3.pdf
|
默认情况下,splitAtPage 设置为 1。
在本PDFBox 教程中,我们学习了将 PDF 文档拆分为多个 PDF。
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。