由於我經常下載一些pdf格式的電子書,有的時候一些好書下載下來沒有書簽,讀起來感覺沒有整體的感覺,所以決定自己寫一個小工具,將特定格式的文本解析成為書簽,然後保存到pdf格式中。
整體思路是從豆瓣啊、京東啊、當當啊、亞馬遜下面的介紹中可以copy出目錄信息,拿《HTTP權威指南》為例:
目錄的結構如:
代碼如下:
第1章 HTTP 概述 3
1.1 HTTP——因特網的多媒體信使 4
1.2 Web 客戶端和服務器 4
1.3 資源 5
1.3.1 媒體類型 6
1.3.2 URI 7
1.3.3 URL 7
1.3.4 URN 8
1.4 事務 9
1.4.1 方法 9
1.4.2 狀態碼 10
1.4.3 Web 頁面中可以包含多個對象 10
1.5 報文 11
1.6 連接 13
每一行後面都有頁碼,而且是用空格分開的。
處理之後,結果為:
主要的邏輯為:
代碼如下:
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<OutlineInfo> parentOutlineStack = new Stack<OutlineInfo>();
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<HashMap<String, Object>> outlines = new ArrayList<HashMap<String, Object>>();
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<HashMap<String, Object>> outlines,
HashMap<String, Object> preOutline, int preLevel)
throws IOException {
String contentFormatLine = null;
bufRead.mark(1);
if ((contentFormatLine = bufRead.readLine()) != null) {
FormattedBookmark bookmark = parseFormmattedText(contentFormatLine);
HashMap<String, Object> 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<HashMap<String, Object>> kids = new ArrayList<HashMap<String, Object>>();
kids.add(map);
preOutline.put("Kids", kids);
// 記錄有孩子的outline信息
parentOutlineStack.push(new OutlineInfo(preOutline, outlines,
preLevel));
addBookmarks(bufRead, kids, map, level);
}
// 如果n<m , 那麼就是說孩子增加完了,退回到上層,bufRead倒退一行
else if (level < preLevel) {
bufRead.reset();
OutlineInfo obj = parentOutlineStack.pop();
addBookmarks(bufRead, obj.getOutlines(), obj.getPreOutline(),
obj.getPreLevel());
}
}
}
private HashMap<String, Object> parseBookmarkToHashMap(
FormattedBookmark bookmark) {
HashMap<String, Object> map = new HashMap<String, Object>();
map.put("Title", bookmark.getTitle());
map.put("Action", "GoTo");
map.put("Page", bookmark.getPage() + " Fit");
return map;
}
private FormattedBookmark parseFormmattedText(String contentFormatLine) {
FormattedBookmark bookmark = new FormattedBookmark();
String title = "";
String destPage = "";
// 當沒有頁碼在字符串結尾的時候,一般就是書的名字,如果格式正確的話。
int lastSpaceIndex = contentFormatLine.lastIndexOf(" ");
if (lastSpaceIndex == -1) {
title = contentFormatLine;
destPage = "1";
} else {
title = contentFormatLine.substring(0, lastSpaceIndex);
destPage = contentFormatLine.substring(lastSpaceIndex + 1);
}
String[] titleSplit = title.split(" ");
int dotCount = titleSplit[0].split("\\.").length - 1;
bookmark.setLevel(dotCount);
bookmark.setPage(destPage);
bookmark.setTitle(title);
return bookmark;
}
private void addFirstOutlineReservedPdf(
List<HashMap<String, Object>> outlines, PdfReader reader) {
PdfDictionary catalog = reader.getCatalog();
PdfObject obj = PdfReader.getPdfObjectRelease(catalog
.get(PdfName.OUTLINES));
// 沒有書簽
if (obj == null || !obj.isDictionary())
return;
PdfDictionary outlinesDictionary = (PdfDictionary) obj;
// 得到第一個書簽
PdfDictionary firstOutline = (PdfDictionary) PdfReader
.getPdfObjectRelease(outlinesDictionary.get(PdfName.FIRST));
PdfString titleObj = firstOutline.getAsString((PdfName.TITLE));
String title = titleObj.toUnicodeString();
PdfArray dest = firstOutline.getAsArray(PdfName.DEST);
if (dest == null) {
PdfDictionary action = (PdfDictionary) PdfReader
.getPdfObjectRelease(firstOutline.get(PdfName.A));
if (action != null) {
if (PdfName.GOTO.equals(PdfReader.getPdfObjectRelease(action
.get(PdfName.S)))) {
dest = (PdfArray) PdfReader.getPdfObjectRelease(action
.get(PdfName.D));
}
}
}
String destStr = parseDestString(dest, reader);
String[] decodeStr = destStr.split(" ");
int num = Integer.valueOf(decodeStr[0]);
HashMap<String, Object> map = new HashMap<String, Object>();
map.put("Title", title);
map.put("Action", "GoTo");
map.put("Page", num + " Fit");
outlines.add(map);
}
private String parseDestString(PdfArray dest, PdfReader reader) {
String destStr = "";
if (dest.isString()) {
destStr = dest.toString();
} else if (dest.isName()) {
destStr = PdfName.decodeName(dest.toString());
} else if (dest.isArray()) {
IntHashtable pages = new IntHashtable();
int numPages = reader.getNumberOfPages();
for (int k = 1; k <= numPages; ++k) {
pages.put(reader.getPageOrigRef(k).getNumber(), k);
reader.releasePage(k);
}
destStr = makeBookmarkParam((PdfArray) dest, pages);
}
return destStr;
}
private String makeBookmarkParam(PdfArray dest, IntHashtable pages) {
StringBuffer s = new StringBuffer();
PdfObject obj = dest.getPdfObject(0);
if (obj.isNumber()) {
s.append(((PdfNumber) obj).intValue() + 1);
} else {
s.append(pages.get(getNumber((PdfIndirectReference) obj)));
}
s.append(' ').append(dest.getPdfObject(1).toString().substring(1));
for (int k = 2; k < dest.size(); ++k) {
s.append(' ').append(dest.getPdfObject(k).toString());
}
return s.toString();
}
private int getNumber(PdfIndirectReference indirect) {
PdfDictionary pdfObj = (PdfDictionary) PdfReader
.getPdfObjectRelease(indirect);
if (pdfObj.contains(PdfName.TYPE)
&& pdfObj.get(PdfName.TYPE).equals(PdfName.PAGES)
&& pdfObj.contains(PdfName.KIDS)) {
PdfArray kids = (PdfArray) pdfObj.get(PdfName.KIDS);
indirect = (PdfIndirectReference) kids.getPdfObject(0);
}
return indirect.getNumber();
}
}