1500字范文,内容丰富有趣,写作好帮手!
1500字范文 > pdf按照页码分割 java_java使用itext按页码拆分pdf文件

pdf按照页码分割 java_java使用itext按页码拆分pdf文件

时间:2022-06-30 14:16:36

相关推荐

pdf按照页码分割 java_java使用itext按页码拆分pdf文件

java使用itext按页码拆分pdf文件,代码实现如下:

/**

* @author

*

* @param inputStream Input PDF file

* @param outputStream Output PDF file

* @param fromPage start page from input PDF file

* @param toPage end page from input PDF file

*/

public static void splitPDF(InputStream inputStream,

OutputStream outputStream, int fromPage, int toPage) {

Document document = new Document();

try {

PdfReader inputPDF = new PdfReader(inputStream);

int totalPages = inputPDF.getNumberOfPages();

//make fromPage equals to toPage if it is greater

if(fromPage > toPage ) {

fromPage = toPage;

}

if(toPage > totalPages) {

toPage = totalPages;

}

// Create a writer for the outputstream

PdfWriter writer = PdfWriter.getInstance(document, outputStream);

document.open();

PdfContentByte cb = writer.getDirectContent(); // Holds the PDF data

PdfImportedPage page;

while(fromPage <= toPage) {

document.newPage();

page = writer.getImportedPage(inputPDF, fromPage);

cb.addTemplate(page, 0, 0);

fromPage++;

}

outputStream.flush();

document.close();

outputStream.close();

} catch (Exception e) {

e.printStackTrace();

} finally {

if (document.isOpen())

document.close();

try {

if (outputStream != null)

outputStream.close();

} catch (IOException ioe) {

ioe.printStackTrace();

}

}

}

使用示例如下,将一个20页的pdf文件拆分成1-12和13-20页两个pdf文件:

public static void main(String[] args) {

try {

MergePDF.splitPDF(new FileInputStream("C:\\input.pdf"),

new FileOutputStream("C:\\output1.pdf"), 1, 12);

MergePDF.splitPDF(new FileInputStream("C:\\input.pdf"),

new FileOutputStream("C:\\output2.pdf"), 13, 20);

} catch (Exception e) {

e.printStackTrace();

}

}

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。