如何使用 Java批量编辑 PDF 文档

150 阅读5分钟

持续创作,加速成长!这是我参与「掘金日新计划 · 10 月更文挑战」的第7天,点击查看活动详情

假设有 100 个 PDF 文件,每个文件都需要相同的编辑操作。在这种情况下,手动执行更改是没有意义的:该过程的低效率最终会产生比任务本身更多的问题。大规模更改 PDF 文档的最有效方法是以编程方式进行。

在本文中,我将演示四种易于使用的 API 解决方案,它们允许您以编程方式在 PDF 文档中大规模添加、删除或旋转页面。这些解决方案提供以下特定服务:

  1. 将一个 PDF 文档中的页面插入/复制到另一个文档中
  2. 从 PDF 文档中删除/删除页面
  3. 旋转 PDF 文档中的所有页面
  4. 旋转 PDF 文档中的特定范围/页面子集

安装 API 客户端

在深入研究每个 API 解决方案的用例和参数之前,我们的第一步是安装 Cloudmersive API 客户端。如下所示:

<repositories>
    <repository>
        <id>jitpack.io</id>
        <url>https://jitpack.io</url>
    </repository>
</repositories>

然后我们可以在依赖项中包含以下引用,使 JitPack 能够编译库:

<dependencies>
<dependency>
    <groupId>com.github.Cloudmersive</groupId>
    <artifactId>Cloudmersive.APIClient.Java</artifactId>
    <version>v4.25</version>
</dependency>
</dependencies>

或者,我们可以通过在存储库末尾的根 build.gradle 中包含以下内容来安装Gradle:

allprojects {
	repositories {
		...
		maven { url 'https://jitpack.io' }
	}
}

之后,我们可以在 build.gradle 中添加依赖:

dependencies {
        implementation 'com.github.Cloudmersive:Cloudmersive.APIClient.Java:v4.25'
}

最后,我们需要在文件顶部包含以下导入:

// Import classes:
//import com.cloudmersive.client.invoker.ApiClient;
//import com.cloudmersive.client.invoker.ApiException;
//import com.cloudmersive.client.invoker.Configuration;
//import com.cloudmersive.client.invoker.auth.*;
//import com.cloudmersive.client.EditPdfApi;

将页面从一个 PDF 插入、复制到另一个

此 API 的参数允许我们准确指定要从哪些页面开始和结束复制,以及将这些复制的页面插入目标文档的具体位置。虽然源文件和目标文件输入很容易确认,但在配置以下三个参数时,我们需要更加注意:

  1. pageStartSource : 开始复制内容的页面(从 1 开始);此页面的内容将包含在目标文件中。
  2. pageEndSource 要从中复制内容的最后一页(从 1 开始);此页面的内容将包含在目标文件中。
  3. pageInsertBeforeDestination 目标 PDF 中应包含复制内容的页面(从 1 开始)。

随着我们的参数平方,我们可以像这样构造 API 调用:

ApiClient defaultClient = Configuration.getDefaultApiClient();

// Configure API key authorization: Apikey
ApiKeyAuth Apikey = (ApiKeyAuth) defaultClient.getAuthentication("Apikey");
Apikey.setApiKey("YOUR API KEY");
// Uncomment the following line to set a prefix for the API key, e.g. "Token" (defaults to null)
//Apikey.setApiKeyPrefix("Token");

EditPdfApi apiInstance = new EditPdfApi();
File sourceFile = new File("/path/to/inputfile"); // File | Source PDF file to copy pages from.
File destinationFile = new File("/path/to/inputfile"); // File | Destination PDF file to copy pages into.
Integer pageStartSource = 56; // Integer | Page number (1 based) to start copying pages from (inclusive) in the Source file.
Integer pageEndSource = 56; // Integer | Page number (1 based) to stop copying pages pages from (inclusive) in the Source file.
Integer pageInsertBeforeDesitnation = 56; // Integer | Page number (1 based) to insert the pages before in the Destination file.
try {
    byte[] result = apiInstance.editPdfInsertPages(sourceFile, destinationFile, pageStartSource, pageEndSource, pageInsertBeforeDesitnation);
    System.out.println(result);
} catch (ApiException e) {
    System.err.println("Exception when calling EditPdfApi#editPdfInsertPages");
    e.printStackTrace();
}

从 PDF 文档中删除、删除页面

要从输入 PDF 中删除页面,我们必须包含 PDF 文件路径,然后满足以下参数:

  1. pageStart : 指定从哪个页面(从 1 开始)开始删除,并删除该页面
  2. pageEnd : 指定从哪个页面(从 1 开始)完成删除,并删除该页面

我们可以像这样构造我们的页面删除 API 调用,再次从我们的 API 密钥授权片段开始:

ApiClient defaultClient = Configuration.getDefaultApiClient();

// Configure API key authorization: Apikey
ApiKeyAuth Apikey = (ApiKeyAuth) defaultClient.getAuthentication("Apikey");
Apikey.setApiKey("YOUR API KEY");
// Uncomment the following line to set a prefix for the API key, e.g. "Token" (defaults to null)
//Apikey.setApiKeyPrefix("Token");

EditPdfApi apiInstance = new EditPdfApi();
File inputFile = new File("/path/to/inputfile"); // File | Input file to perform the operation on.
Integer pageStart = 56; // Integer | Page number (1 based) to start deleting pages from (inclusive).
Integer pageEnd = 56; // Integer | Page number (1 based) to stop deleting pages from (inclusive).
try {
    byte[] result = apiInstance.editPdfDeletePages(inputFile, pageStart, pageEnd);
    System.out.println(result);
} catch (ApiException e) {
    System.err.println("Exception when calling EditPdfApi#editPdfDeletePages");
    e.printStackTrace();
}

旋转 PDF 文档中的所有页面

当 PDF 文件中的每一页都错误地旋转到相同的角度时,我们只需要密切关注rotationAngle这个解决方案中的参数,因为它只接受正(向右旋转)和负(向左旋转)整数,它们只能是 90 度的倍数。一旦我们正确指定了这个参数,我们就可以构建 API,如下面的示例所示:

ApiClient defaultClient = Configuration.getDefaultApiClient();

// Configure API key authorization: Apikey
ApiKeyAuth Apikey = (ApiKeyAuth) defaultClient.getAuthentication("Apikey");
Apikey.setApiKey("YOUR API KEY");
// Uncomment the following line to set a prefix for the API key, e.g. "Token" (defaults to null)
//Apikey.setApiKeyPrefix("Token");

EditPdfApi apiInstance = new EditPdfApi();
File inputFile = new File("/path/to/inputfile"); // File | Input file to perform the operation on.
Integer rotationAngle = 56; // Integer | The angle to rotate the page in degrees, must be a multiple of 90 degrees, e.g. 90, 180, 270, or -90, -180, -270, etc.
try {
    byte[] result = apiInstance.editPdfRotateAllPages(inputFile, rotationAngle);
    System.out.println(result);
} catch (ApiException e) {
    System.err.println("Exception when calling EditPdfApi#editPdfRotateAllPages");
    e.printStackTrace();

旋转 PDF 文档中的范围、页面子集

当 PDF 文档中只有特定页面子集需要旋转调整时,我们只需要再次配置旋转角度,以及指定操作应该从哪里开始和结束的两个参数:

  1. rotationAngle 定义指定页面将旋转多少度;接受正(向右旋转)和负(向左旋转)整数,它们是 90 度的倍数
  2. pageStart : 指定子集中的哪一页(从 1 开始),并包含该页
  3. pageEnd 指定要在子集中的哪个页面(基于 1)完成,并包含此页面
ApiClient defaultClient = Configuration.getDefaultApiClient();

// Configure API key authorization: Apikey
ApiKeyAuth Apikey = (ApiKeyAuth) defaultClient.getAuthentication("Apikey");
Apikey.setApiKey("YOUR API KEY");
// Uncomment the following line to set a prefix for the API key, e.g. "Token" (defaults to null)
//Apikey.setApiKeyPrefix("Token");

EditPdfApi apiInstance = new EditPdfApi();
File inputFile = new File("/path/to/inputfile"); // File | Input file to perform the operation on.
Integer rotationAngle = 56; // Integer | The angle to rotate the page in degrees, must be a multiple of 90 degrees, e.g. 90, 180, 270, or -90, -180, -270, etc.
Integer pageStart = 56; // Integer | Page number (1 based) to start rotating pages from (inclusive).
Integer pageEnd = 56; // Integer | Page number (1 based) to stop rotating pages from (inclusive).
try {
    byte[] result = apiInstance.editPdfRotatePageRange(inputFile, rotationAngle, pageStart, pageEnd);
    System.out.println(result);
} catch (ApiException e) {
    System.err.println("Exception when calling EditPdfApi#editPdfRotatePageRange");
    e.printStackTrace();
}

使用上述示例构建 API 调用后,一切就绪:不再需要代码。每个 API 响应都会为新的 PDF 文件生成一个编码字符串,可用于根据需要生成新文件或更新现有文档。