Ways to add bookmarks to PDFs using Java (PDF bookmark creation) _java

Source: Internet
Author: User
Tags goto pdfobject stringbuffer

Because I often download some of the PDF format e-books, sometimes some good books are downloaded without bookmarks, read up feeling that there is no overall feeling, so decided to write a small tool, the specific format of the text into a bookmark, and then saved to the PDF format.
The overall idea is from the watercress ah, Jing Dong Ah, when Ah, Amazon under the introduction can be copy out of the directory information, take the "HTTP authoritative guide" as an example:
The structure of the directory is as follows:

Copy Code code as follows:

1th Chapter HTTP Overview 3
1.1 http--Internet Multimedia Messenger 4
1.2 Web client and server 4
1.3 Resources 5
1.3.1 Media type 6
1.3.2 URI 7
1.3.3 URL 7
1.3.4 URN 8
1.4 Business 9
1.4.1 Method 9
1.4.2 Status Code 10
1.4.3 Web pages can contain multiple objects 10
1.5 Message 11
1.6 Connection 13

Each line is followed by a page number and is separated by a space.
After processing, the result is:

The main logic is:

Copy Code code as follows:

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
Read into PDF file
Pdfreader reader = new Pdfreader (sourcepdf);

        list         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);
New Stamper
Pdfstamper stamper = new Pdfstamper (reader, New FileOutputStream (
Destpdf));

Stamper.setoutlines (outlines);
Stamper.close ();
}

private void Addbookmarks (BufferedReader bufread,
ListHashmap<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 ();
If the n==m, then the same layer, this time, add to the ArrayList, continue to read down
if (level = = Prelevel) {
Outlines.add (map);
Addbookmarks (Bufread, outlines, map, level);
}
If n>m, then it is certain that the line is the child of the previous line, the new one kids ArrayList, and added to this ArrayList
else if (Level > Prelevel) {
listKids.add (map);
Preoutline.put ("Kids", Kids);
Record the outline information of a child
Parentoutlinestack.push (New Outlineinfo (Preoutline, outlines,
Prelevel));
Addbookmarks (Bufread, kids, map, level);
}
If n<m, then that means the child is up, back to the top, bufread backwards line
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 = "";

       //When there is no page number at the end of the string, it is usually the name of the book, if the format is correct.
        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 (
ListPdfdictionary Catalog = Reader.getcatalog ();
Pdfobject obj = pdfreader.getpdfobjectrelease (catalog
. Get (Pdfname.outlines));
No bookmarks
if (obj = null | |!obj.isdictionary ())
Return
Pdfdictionary outlinesdictionary = (pdfdictionary) obj;
Get the first bookmark
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 ();
}
}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.