Como eu frequentemente baixo alguns e-books em formato PDF, às vezes alguns bons livros não têm favoritos ao baixar, e não parece uma leitura inteira, então decidi escrever um gadget, analisar o texto em um formato específico em Um marcador e, em seguida, salve -o no formato PDF.
A idéia geral é copiar as informações do diretório das apresentações abaixo de Douban, JD.com, Dangdang e Amazon.
A estrutura do diretório é a seguinte:
A cópia do código é a seguinte:
Capítulo 1 Visão geral HTTP 3
1.1 Multimedia Messenger 4 da Http Internet 4
1.2 Web Client and Server 4
1.3 Recurso 5
1.3.1 Mídia Tipo 6
1.3.2 URI 7
1.3.3 URL 7
1.3.4 Urn 8
1.4 Transação 9
1.4.1 Método 9
1.4.2 Código de status 10
1.4.3 Páginas da web podem conter vários objetos 10
1.5 Mensagem 11
1.6 Conexão 13
Cada linha possui números de página e é separada por espaços.
Após o processamento, o resultado é:
A lógica principal é:
A cópia do código é a seguinte:
pacote org.fra.pdf.bussiness;
importar java.io.bufferedReader;
importar java.io.fileOutputStream;
importar java.io.ioException;
importar java.util.arraylist;
importar java.util.hashmap;
importar java.util.list;
importar java.util.stack;
import com.itextpdf.text.documentException;
importar com.itextpdf.text.pdf.inthashtable;
import com.itextpdf.text.pdf.pdfarray;
import com.itextpdf.text.pdf.pdfdictionary;
importar com.itextpdf.text.pdf.pdfindireCreceference;
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;
classe pública addpdfoutlinefromtxt {
Stack privado <sorllineinfo> parairoutLousestack = new Stack <sorllineinfo> ();
public void CreatePdf (String Destpdf, String Sourcepdf,
BufferredReader Bufread, int Pattern) lança ioException,
DocumentException {
if (padrão! = addbookmarkconstants.reserved_old_outline
&& Pattern! = AddBookMarkConstants.Reserved_None
&& Pattern! = AddBookMarkConstants.Reserved_First_Outline)
retornar;
// leia no arquivo pdf
Leitor pdfreader = new PDFReader (SourCepDF);
List <hashmap <string, object >> contornos = new ArrayList <hashmap <string, object >> ();
if (padrão == addbookmarkconstants.reserved_old_outline) {
outlines.addall (Simplebookmark.getbookmark (leitor));
} else if (padrony == addbookmarkconstants.reserved_first_outline) {
addfirstoutLineReedPdf (contornos, leitor);
}
AddBookmarks (BUFREAD, FORCLINAS, NULL, 0);
// Crie um novo Stamper
Pdfstamper stedper = novo pdfstamper (leitor, new FileOutputStream (
destpdf));
sTamper.setOutLines (contornos);
stamper.close ();
}
Private Void AddBookmarks (BufferReader Bufread,
Lista <hashmap <string, objeto >> esboços,
Hashmap <string, objeto> pré -uoutline, int prelevel)
lança ioexception {
String contentFormatLine = null;
bufread.mark (1);
if ((contentFormatLine = bufread.readline ())! = null) {
FormattedBookmark Bookmark = parseFormattedText (contentFormatLine);
Hashmap <string, object> map = parsebookmarktohashmap (marcador);
int nível = markmark.getLevel ();
// Se n == m, então é da mesma camada.
if (nível == prelevel) {
outlines.add (mapa);
AddBookmarks (BUFREAD, delineadores, mapa, nível);
}
// Se n> m, então é certo que a linha é o filho da linha anterior, a nova Arraylist infantil e adicionada a esta Arraylist
caso contrário, se (nível> prelevel) {
Lista <hashmap <string, object >> crianças = new ArrayList <hashmap <string, object >> ();
crianças.Add (mapa);
preutline.put ("crianças", crianças);
// Recorde informações de esboço sobre crianças
ParteloutLousestack.push (novo OutlineInfo (pré -escravo, contornos,
prelevel));
addbookmarks (bufread, crianças, mapa, nível);
}
// Se n <m, isso significa que a criança foi adicionada e devolvida ao nível superior, e o bufread voltará à linha
else if (nível <prelevel) {
bufread.reset ();
OutLineInfo obj = parairoutLousestack.pop ();
addbookmarks (bufread, obj.getOutlines (), obj.getpreoutline (),
obj.getprelevel ());
}
}
}
Hashmap privado <string, objeto> parsebookmarktohashmap (
FormattedBookmark Bookmark) {
Hashmap <string, object> map = new hashmap <string, object> ();
map.put ("title", markmark.gettitle ());
map.put ("ação", "goto");
map.put ("Page", Bookmark.getPage () + "Fit");
mapa de retorno;
}
Private FormattedBookmark ParseFormattedText (String contentFormatLine) {
FormattedBookmark Bookmark = new FormattedBookMark ();
String title = "";
String destpage = "";
// Quando não há número de página no final da string, geralmente é o nome do livro, se o formato estiver correto.
int lastSpaceIndex = ContentFormatLine.LastIndexOf ("");
if (lastSpaceIndex == -1) {
title = contentFormatLine;
destpage = "1";
} outro {
title = contentFormatline.substring (0, lastSpaceIndex);
destpage = contentFormatline.substring (lastspaceIndex + 1);
}
String [] titlesplit = title.split ("");
int dotCount = titlesplit [0] .split ("//."). comprimento - 1;
markmark.setLevel (DotCount);
Markmark.setPage (Destpage);
markmark.settitle (título);
Retornar marcador;
}
private vazio addfirstoutlineRereadervedpdf (
Lista <hashmap <string, objeto >> esboços, PDFReader Reader) {
Catálogo pdfdictionary = reader.getCatalog ();
PdfObject obj = pdfreader.getpdfobjectrelease (catálogo
.get (pdfname.outlines));
// Sem marcador
if (obj == null ||! obj.isdictionary ())
retornar;
Pdfdictionary OutinesDictionary = (pdfdictionary) obj;
// Obtenha o primeiro marcador
Pdfdictionary FirstoutLine = (pdfdictionary) pdfreader
.getpdfobjectRelease (outlinesdictionary.get (pdfname.first));
Pdfstring titleObj = FirstoutLine.getasstring ((pdfname.title));
Title string = titleObj.Tounicodestring ();
PDFARRAY DEST = FIRSTINGLINE.GETASARRAY (PDFNAME.DEST);
if (dest == null) {
Pdfdictionary ação = (pdfdictionary) pdfreader
.getpdfobjectRelease (FirstOutline.get (pdfname.a));
if (ação! = null) {
if (pdfname.goto.equals (pdfreader.getpdfobjectrelease (ação
.get (pdfname.s)))) {
dest = (pdFarray) pdfreader.getpdfobjectrelease (ação
.get (pdfname.d));
}
}
}
String deststr = parsedestString (dest, leitor);
String [] DECODEST = DESTSTR.SPLIT ("");
int num = Integer.ValueOf (decodestre [0]);
Hashmap <string, object> map = new hashmap <string, object> ();
map.put ("título", título);
map.put ("ação", "goto");
map.put ("página", num + "fit");
outlines.add (mapa);
}
Parsedeststring de String Private (PDFARRAY DEST, PDFReader Reader) {
String deststr = "";
if (dest.isString ()) {
deststr = dest.toString ();
} else if (dest.isname ()) {
deststr = pdfname.decodename (dest.toString ());
} else if (dest.esArray ()) {
Páginas inThashTable = new inthashTable ();
int numpages = leitor.getNumberOfPages ();
for (int k = 1; k <= numpages; ++ k) {
páginas.put (leitor.getpageorigref (k) .getNumber (), k);
leitor.releasePage (k);
}
deststr = makebookmarkparam ((pdFarray) dest, páginas);
}
retornar 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);
} outro {
s.append (páginas.get (getNumber ((pdfindirecreceference) obj)));
}
S.APPEND ('') .APNEND (DEST.GETPDFOBJET (1) .ToString (). Substring (1));
for (int k = 2; k <dest.size (); ++ k) {
S.APPEND ('') .APNEND (DEST.GETPDFOBJET (k) .ToString ());
}
retornar s.toString ();
}
private int getNumber (indireto pdfindirectReference) {
Pdfdictionary pdfobj = (pdfdictionary) pdfreader
.getpdfobjectrelease (indireto);
if (pdfobj.contains (pdfname.type)
&& pdfobj.get (pdfname.type) .equals (pdfname.pages)
&& pdfobj.contains (pdfname.kids)) {
PDFARRAY KIDS = (PDFARRAY) PDFOBJ.GET (PDFNAME.KIDS);
Indirect = (PDFindirCereference) KIDS.GETPDFOBJECT (0);
}
return indirect.getNumber ();
}
}