package org.fra.pdf.bussiness;
import java.io.BufferedReader;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Stack;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.pdf.IntHashtable;
import com.itextpdf.text.pdf.PdfArray;
import com.itextpdf.text.pdf.PdfDictionary;
import com.itextpdf.text.pdf.PdfIndirectReference;
import com.itextpdf.text.pdf.PdfName;
import com.itextpdf.text.pdf.PdfNumber;
import com.itextpdf.text.pdf.PdfObject;
import com.itextpdf.text.pdf.PdfReader;
import com.itextpdf.text.pdf.PdfStamper;
import com.itextpdf.text.pdf.PdfString;
import com.itextpdf.text.pdf.SimpleBookmark;
public class AddPdfOutLineFromTxt {
private Stack parentOutlineStack = new Stack();
public void createPdf(String destPdf, String sourcePdf,
BufferedReader bufRead, int pattern) throws IOException,
DocumentException {
if (pattern != AddBookmarkConstants.RESERVED_OLD_OUTLINE
&& pattern != AddBookmarkConstants.RESERVED_NONE
&& pattern != AddBookmarkConstants.RESERVED_FIRST_OUTLINE)
return;
// 读入pdf文件
PdfReader reader = new PdfReader(sourcePdf);
List outlines = new ArrayList();
if (pattern == AddBookmarkConstants.RESERVED_OLD_OUTLINE) {
outlines.addAll(SimpleBookmark.getBookmark(reader));
} else if (pattern == AddBookmarkConstants.RESERVED_FIRST_OUTLINE) {
addFirstOutlineReservedPdf(outlines, reader);
}
addBookmarks(bufRead, outlines, null, 0);
// 新建stamper
PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(
destPdf));
stamper.setOutlines(outlines);
stamper.close();
}
private void addBookmarks(BufferedReader bufRead,
List outlines,
HashMap preOutline, int preLevel)
throws IOException {
String contentFormatLine = null;
bufRead.mark(1);
if ((contentFormatLine = bufRead.readLine()) != null) {
FormattedBookmark bookmark = parseFormmattedText(contentFormatLine);
HashMap map = parseBookmarkToHashMap(bookmark);
int level = bookmark.getLevel();
// 如果n==m, 那么是同一层的,这个时候,就加到ArrayList中,继续往下面读取
if (level == preLevel) {
outlines.add(map);
addBookmarks(bufRead, outlines, map, level);
}
// 如果n>m,那么可以肯定,该行是上一行的孩子,, new 一个kids的arraylist,并且加入到这个arraylist中
else if (level > preLevel) {
List kids = new ArrayList();
kids.add(map);
preOutline.put("Kids", kids);
// 记录有孩子的outline信息
parentOutlineStack.push(new OutlineInfo(preOutline, outlines,
preLevel));
addBookmarks(bufRead, kids, map, level);
}
// 如果n