1

Java将 PDF 拆分为多个 PDF 文件

 1 year ago
source link: https://blog.51cto.com/u_15656056/5564237
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

对于职场人士来说, PDF明显要比Word受欢迎, 不仅是因为其安全性高,而且传输速度比较快。PDF中的内容过多时就会导致PDF文件过大,传输速度就会变慢, 我们当初选择使用PDF就是看重传输速度快的优点, 如果不拆分的话就会影响传输速率。 一份页面较多且内容复杂的PDF文件不仅在传输方面很麻烦,对它进行阅览也会给很多人带来不便。在这样的情况下,我们就需要进行对这份PDF文件进行拆分。

程序环境:

在程序中导入jar,如下两种方法:

手动引入。将​ ​Free Spire.PDF for Java​​下载到本地,解压,找到lib文件夹下的Spire.Doc.jar文件。在IDEA中打开如下界面,将本地路径中的jar文件引入Java程序:

如果您想通过 ​ ​Maven​​安装,则可以在 pom.xml 文件中添加以下代码导入 JAR 文件。

<repositories>

<repository>

<id>com.e-iceblue</id>

<url>https://repo.e-iceblue.cn/repository/maven-public/</url>

</repository>

</repositories>
<dependencies>
<dependency>
<groupId>e-iceblue</groupId>
<artifactId>spire.pdf.free</artifactId>
<version>5.1.0</version>
</dependency>
</dependencies>

将 PDF 拆分为单页

以下是详细步骤。

  • 创建一个PdfDcoument 对象。
  • ​使用PdfDocument.loadFromFile() 方法加载 PDF 文档。
  • 使用PdfDocument.split(string destFilePattern, int startNumber) 方法将文档拆分为单页PDF。

【Java】

import com.spire.pdf.PdfDocument;

public class SplitPdfByEachPage {

public static void main(String[] args) {

//指定输入文件路径
String inputFile = "成都简介.pdf";

//指定输出目录
String outputDirectory = "C:\\Users\\Tina\\Desktop\\PDF for java\\";
;
//创建一个PdfDocument对象
PdfDocument doc = new PdfDocument();

//加载PDF文件
doc.loadFromFile(inputFile);

//将 PDF 拆分为单页 PDF
doc.split(outputDirectory + "output-{0}.pdf", 1);
}
Java将 PDF 拆分为多个 PDF 文件_拆分PDF

按页面范围拆分PDF

以下是详细步骤。

  • 在初始化PdfDocument对象时加载PDF源文件。
  • 创建两个额外的PdfDocument对象。
  • 使用PdfDocument.insertPage()方法将源文件的第一页导入到第一个文档。
  • 使用PdfDocument.insertPageRange()方法将剩余页面从源文件导入到第二个文档。
  • 使用PdfDocument.saveToFile()方法将两个文档保存为单独的 PDF 文件。

【Java】

import com.spire.pdf.PdfDocument;

public class SplitPdfByPageRange {

public static void main(String[] args) {

//指定输入文件路径
String inputFile = "成都简介.pdf";

//指定输出目录
String outputDirectory = "C:\\Users\\Tina\\Desktop\\PDF for java\\";

//在初始化 PdfDocument 对象时加载源 PDF 文件
PdfDocument sourceDoc = new PdfDocument(inputFile);

//创建两个额外的 PdfDocument对象
PdfDocument newDoc_1 = new PdfDocument();
PdfDocument newDoc_2 = new PdfDocument();

//将源文件的第一页插入到第一个文档中
newDoc_1.insertPage(sourceDoc, 0);

//将源文件的其余页面插入第二个文档
newDoc_2.insertPageRange(sourceDoc, 1, sourceDoc.getPages().getCount() - 1);

//将两个文档另存为 PDF 文件
newDoc_1.saveToFile(outputDirectory + "output-1.pdf");
newDoc_2.saveToFile(outputDirectory + "output-2.pdf");
}
}
Java将 PDF 拆分为多个 PDF 文件_java_02

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK