0

我想在现有 PDF 文件中添加索引页。并将页码添加到 pdf 文件的页面。
所有建议的解决方案都指向创建一个新的 pdf 并将现有的 pdf 文件与新的文件合并。

这个还有别的办法吗??我也不想使用 itext,因为它不能免费用于商业用途。

4

1 回答 1

1

根据您对原始问题的评论,您认为 PDFBox

要添加新页面和内容,您需要创建一个新的 pdf 添加新内容,然后合并现有的 pdf。我想避免合并步骤。重命名不是问题

您可能想尝试这样的事情:

PDDocument doc = PDDocument.load(new FileInputStream(new File("original.pdf")));
PDPage page = new PDPage();
// fill page
doc.addPage(page);
doc.save("original-plus-page.pdf");

编辑:在对答案的评论中,出现了如何在特定索引(页码)处插入新页面的问题。要做到这一点,显然doc.addPage(page)必须以某种方式改变。

最初这个PDDocument方法是这样定义的:

/**
 * This will add a page to the document.  This is a convenience method, that
 * will add the page to the root of the hierarchy and set the parent of the
 * page to the root.
 *
 * @param page The page to add to the document.
 */
public void addPage( PDPage page )
{
    PDPageNode rootPages = getDocumentCatalog().getPages();
    rootPages.getKids().add( page );
    page.setParent( rootPages );
    rootPages.updateCount();
}

我们只需要一个类似的函数,它不仅仅是add将页面简单地提供给孩子,而是将其添加到给定的索引处。因此,在我们的代码中类似下面的辅助方法就可以了:

public static void addPage(PDDocument doc, int index, PDPage page)
{
    PDPageNode rootPages = doc.getDocumentCatalog().getPages();
    rootPages.getKids().add(index, page);
    page.setParent(rootPages);
    rootPages.updateCount();
}

如果您现在替换该行

doc.addPage(page);

在原始答案的代码中

addPage(doc, page, 0);

空白页是预先添加的。

于 2013-05-06T16:05:34.343 回答