【发布时间】:2015-12-20 14:09:39
【问题描述】:
我有两个 pdf:
- Master.pdf:包含带有书签、大纲(目录)的页面。
- Child.pdf:单页文件。
Child.pdf 页面需要作为第 n 页(在我的情况下为第 10 页)附加到 Master.pdf。
生成的 PDF 应具有新页面的新大纲项(新书签)。现有的书签也应该继续正常工作。实际上:应该重构现有的大纲树。
我可以通过 iText API 实现这一点吗?有什么有用的示例吗?
public class ConcatenateBookmarks {
public static final String SRC1 = "C:\\c\\spring-in-action.pdf";
public static final String SRC2 = "C:\\c\\SPD-DUAL DS.pdf";
public static final String DEST = "C:\\c\\final.pdf";
/**
* Manipulates a PDF file src with the file dest as result
*
* @param src
* the original PDF
* @param dest
* the resulting PDF
* @throws IOException
* @throws DocumentException
*/
public void manipulatePdf(String[] src, String dest) throws IOException, DocumentException {
int POINT = 3;
Document document = new Document();
PdfSmartCopy copy = new PdfSmartCopy(document, new FileOutputStream(dest));
document.open();
PdfReader reader;
int page_offset = 0;
int n;
// Create a list for the bookmarks
ArrayList<HashMap<String, Object>> bookmarks = new ArrayList<HashMap<String, Object>>();
List<HashMap<String, Object>> tmp;
for (int i = 0; i < 1/* src.length */; i++) {
reader = new PdfReader(src[i]);
PdfReader reader2 = new PdfReader(src[1]);
int pagesCount = reader2.getNumberOfPages();
page_offset = pagesCount;
if (i == 0) {
HashMap<String, String> map = SimpleNamedDestination.getNamedDestination(reader, false);
SimpleNamedDestination.exportToXML(map, new FileOutputStream(dest), "ISO8859-1", false);
copy.addNamedDestinations(map, 0);
}
tmp = SimpleBookmark.getBookmark(reader);
// this level have to
// separate up to n don't
// change and after the
// should shift
SimpleBookmark.shiftPageNumbers(tmp, page_offset,
new int[] { POINT, reader.getNumberOfPages() + pagesCount });
bookmarks.addAll(tmp);
// add the pages
n = reader.getNumberOfPages();
page_offset += n;
for (int page = 0; page < n;) {
copy.addPage(copy.getImportedPage(reader, ++page));
if (page == POINT) // add child pages to nth point
{
for (int page2 = 0; page2 < pagesCount;) {
copy.addPage(copy.getImportedPage(reader2, ++page2));
}
}
}
copy.freeReader(reader);
reader.close();
}
// Add the merged bookmarks
copy.setOutlines(bookmarks);
// step 5
document.close();
}
/**
* Main method.
*
* @param args
* no arguments needed
* @throws DocumentException
* @throws IOException
* @throws SQLException
*/
public static void main(String[] args) throws IOException, DocumentException, SQLException {
new ConcatenateBookmarks().manipulatePdf(new String[] { SRC1, SRC2 }, DEST);
}
}
【问题讨论】:
-
向我们展示您已经尝试过的内容。向我们展示您的代码。
-
请见谅。立即添加代码。