在这个简短的教程中,我们将带您了解如何使用 Java 旋转 PDF。它包含配置 IDE 的详细信息、一组编写应用程序的说明以及一个可运行的示例代码以使用 Java 旋转 PDF 页面**。还将提供仅更改页面方向或根据应用程序要求更改内容方向的说明。
使用 Java 旋转 PDF 中所有页面的步骤
- 设置 IDE 以添加 Aspose.PDF for Java 以更改 PDF 方向
- 使用 Document class 加载输入 PDF 文件以更改页面方向
- 解析所有页面以翻转每一页
- 通过将长度更改为宽度和宽度更改为高度来更改页面方向
- 使用 Page.setRotate() 方法旋转页面内容
- 将旋转后的 PDF 保存在磁盘上
这些步骤描述了使用 Java* 旋转 PDF 中的单个页面的编程任务。最初,解析加载的 PDF 文件中的页面集合,并利用每个页面的矩形区域将宽度更改为高度,反之亦然。在这种情况下,只有页面长度和宽度会互换,但内容保持在同一方向,也可以使用 Page.setRotate() 方法进行更改。
使用 Java 旋转 PDF 页面的代码
import com.aspose.pdf.*; | |
public class Main { | |
public static void main(String[] args) throws Exception {//Rotate PDF using Java | |
// Load a license | |
License lic = new License(); | |
lic.setLicense("Aspose.Total.lic"); | |
// Load the source PDF whose pages' orientation is to be changed | |
Document doc = new Document("input.pdf"); | |
// Parse through all the pages | |
for (Page page : doc.getPages()) { | |
// Change the page orientation | |
Rectangle r = page.getMediaBox(); | |
double nextHeight = r.getWidth(); | |
double nextWidth = r.getHeight(); | |
double nextLLX = r.getLLX(); | |
double nextLLY = r.getLLY() + (r.getHeight() - nextHeight); | |
page.setMediaBox(new Rectangle(nextLLX, nextLLY, nextLLX + nextWidth, nextLLY + nextHeight)); | |
page.setCropBox(new Rectangle(nextLLX, nextLLY, nextLLX + nextWidth, nextLLY + nextHeight)); | |
// Rotate the page contents | |
page.setRotate(Rotation.on90); | |
// Save the rotated PDF file | |
doc.save("rotated.pdf"); | |
} | |
System.out.println("Done"); | |
} | |
} |
在上述代码中,演示了使用 Java* 每页旋转 PDF 的过程。 Page 类的 MediaBox 属性返回用于通过交换宽度和高度来切换页面尺寸的矩形区域。如果要更改页面内容的方向,请使用旋转枚举器中的 on90、on180 或 on270 值来使用 Page.setRotate() 方法设置角度。
本主题分享了有关更改 PDF 页面和内容方向的详细信息。如果您想了解在 PDF 文件中查找和替换文本的过程,请参阅 如何使用 Java 查找和替换 PDF 中的文本 上的文章。