简体   繁体   English

在不使用iText的情况下编辑现有的PDF

[英]Editing an existing PDF without using iText

I want to add an index page to existing PDF file. 我想将索引页添加到现有的PDF文件中。 And add page numbers to the page of the pdf file. 并将页码添加到pdf文件的页面。
All the suggested solutions point towards creating a new pdf and merging the existing pdf file with the new one. 所有建议的解决方案都指向创建新的pdf并将现有的pdf文件与新的pdf文件合并。

Is there any other way for this ?? 还有其他方法吗? Also I dont want to use itext since its not free for commercial uses. 我也不想使用itext,因为它不是免费用于商业用途。

According to your comments to the original question, you think in PDFBox 根据您对原始问题的评论,您认为是在PDFBox中

for adding a new page & content, you need to create a new pdf add new content and then merge the existing pdf. 要添加新的页面和内容,您需要创建一个新的pdf文件并添加新的内容,然后合并现有的pdf文件。 I wanted to avoid the merging step. 我想避免合并步骤。 Renaming is not the issue 重命名不是问题

You might want to try something like this: 您可能想要尝试这样的事情:

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");

EDIT: In a comment to the answer the question arose how to insert a new page at specific index(page number). 编辑:在对答案的评论中,出现了一个问题,即如何在特定的索引(页面编号)处插入新页面。 To do this, obviously the doc.addPage(page) has to be changed somehow. 为此,显然必须以某种方式更改doc.addPage(page)

Originally this PDDocument method is defined like this: 最初,此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();
}

We merely need a similar function which merely does not simply add the page to the kids but instead adds it at a given index. 我们只需要一个类似的函数,它不仅可以简单地add页面add到孩子中,还可以将其添加到给定的索引中。 Thus a helper method like the following in our code will do: 因此,在我们的代码中,如下所示的辅助方法将起作用:

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();
}

If you now replace the line 如果现在更换线

doc.addPage(page);

in the code of the original answer by 在原始答案的代码中

addPage(doc, page, 0);

the empty page is added up front. 空页被添加到前面。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM