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

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

/**

* @author viralpatel.net

*

* @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();

}

}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值