怎样实用Java实现合并、拆分PDF文档

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

怎样实用Java实现合并、拆分PDF文档

  2021-04-03 我要评论

前言

处理PDF文档时,我们可以通过合并的方式,来任意组几个不同的PDF文件或者通过拆分将一个文件分解成多个子文件,这样的好处是对文档的存储、管理很方便。下面将通过Java程序代码介绍具体的PDF合并、拆分的方法。

工具:Free Spire.PDF for Java 2.0.0 (免费版)

注:2.0.0版本的比之前的1.1.0版本在功能上做了很大提升,支持所有收费版的功能,只是在文档页数上有一定限制,要求不超过10页,但是对于常规的不是很大的文件,这个类库就非常实用。

jar文件导入:

方法一

步骤 1:在Java程序中新建一个文件夹可命名为Lib。下载安装包后,解压,将解压后的文件夹下的子文件夹lib中的Spire.Pdf.jar和Spire.Common.jar两个文件复制到新建的文件夹下,如下图:

步骤2:建好文件夹后,引用两个文件:选中这两个jar文件,点击鼠标右键,选择“Build Path” – “Add to Build Path”。

方法二

通过maven仓库安装导入

【示例1】合并PDF

import com.spire.pdf.*;
import java.io.*;

public class Merge2 {
	public static void main(String[] args) throws Exception {
    
		String outputFile = "output/mergeFilesByStream.pdf";
    FileInputStream stream1 = new FileInputStream(new File("sample1.pdf"));
    FileInputStream stream2 = new FileInputStream(new File("sample2.pdf"));
    FileInputStream stream3 = new FileInputStream(new File("sample3.pdf"));
    //加载PDF示例文档
    InputStream[] streams = new FileInputStream[]{stream1, stream2, stream3};

    //合并PDF文档
    PdfDocumentBase doc = PdfDocument.mergeFiles(streams);

    //保存文档
    doc.save(outputFile);
    doc.close();
  }
}

合并前:

合并后:

【示例2】拆分PDF文档

测试文档:

1. 按每一页单独拆分

import com.spire.pdf.*;

public class SplitPDF1 {
	public static void main(String[] args)
	{
	//加载需要拆分的PDF文档
  PdfDocument doc = new PdfDocument();
  doc.loadFromFile("test.pdf");

  //调用方法split()将PDF文档按每一页拆分为单独的文档
  doc.split("output/splitDocument-{0}.pdf", 0);
  doc.close();
	}
}

拆分结果:

2. 按指定页数范围拆分

import com.spire.pdf.*; 
import com.spire.pdf.graphics.PdfMargins; 
 
import java.awt.geom.Point2D; 
 
public class SplitPDF2 { 
  public static void main(String[] args) 
  { 
 
    //加载需要拆分的PDF文档 
    PdfDocument doc = new PdfDocument(); 
    doc.loadFromFile("test.pdf"); 
 
    //新建第1个PDF文档1 
    PdfDocument newpdf1 = new PdfDocument(); 
    PdfPageBase page; 
 
    //将原PDF文档的第1、2页拆分,并保存到newpdf1 
    for(int i = 0;i<2;i++) 
    { 
      page = newpdf1.getPages().add(doc.getPages().get(i).getSize(), new PdfMargins(0)); 
      doc.getPages().get(i).createTemplate().draw(page, new Point2D.Float(0,0)); 
    } 
    newpdf1.saveToFile("split/result1.pdf"); 
 
    //新建第2个PDF文档 
    PdfDocument newpdf2 = new PdfDocument(); 
 
    //将原PDF文档的第3、4页拆分,并保存到newpdf2 
    for(int i = 2;i<4;i++) 
    { 
      page = newpdf2.getPages().add(doc.getPages().get(i).getSize(), new PdfMargins(0)); 
      doc.getPages().get(i).createTemplate().draw(page, new Point2D.Float(0,0)); 
    } 
    newpdf2.saveToFile("split/result2.pdf"); 
  } 
} 

拆分结果:

您可能感兴趣的文章:

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们