使用 iTextpdf 复制 PDF 文件的第一页
以下是使用 iTextpdf 复制第一页 PDF 的示例代码:
import com.itextpdf.text.Document;
import com.itextpdf.text.pdf.PdfCopy;
import com.itextpdf.text.pdf.PdfReader;
import com.itextpdf.text.pdf.SimpleBookmark;
import java.io.FileOutputStream;
import java.util.List;
public class CopyFirstPagePdf {
public static void main(String[] args) {
try {
// 读取原始 PDF
PdfReader reader = new PdfReader('original.pdf');
// 获取书签
List bookmarks = SimpleBookmark.getBookmark(reader);
// 创建新的 PDF
Document document = new Document(reader.getPageSize(1));
PdfCopy copy = new PdfCopy(document, new FileOutputStream('first_page.pdf'));
document.open();
// 复制第一页
copy.addPage(copy.getImportedPage(reader, 1));
// 添加书签
if (bookmarks != null) {
copy.setOutlines(bookmarks);
}
// 关闭文档
document.close();
reader.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
该示例代码首先读取原始 PDF,然后获取书签。接着,它创建一个新的 PDF,只复制第一页并添加书签。最后,它关闭文档和阅读器。
请注意,该示例假设原始 PDF 具有书签。如果原始 PDF 没有书签,则不需要获取和添加书签。
原文地址: https://www.cveoy.top/t/topic/m775 著作权归作者所有。请勿转载和采集!