Example usage for com.lowagie.text.pdf PdfOutline PdfOutline

List of usage examples for com.lowagie.text.pdf PdfOutline PdfOutline

Introduction

In this page you can find the example usage for com.lowagie.text.pdf PdfOutline PdfOutline.

Prototype


public PdfOutline(PdfOutline parent, PdfDestination destination, Paragraph title) 

Source Link

Document

Constructs a PdfOutline.

Usage

From source file:ambit.data.qmrf.Qmrf_Xml_Pdf.java

License:Open Source License

public void xml2pdf(InputSource xml, OutputStream pdf) {

    try {/*from   w  ww .  j  a v  a 2 s  .c  o  m*/
        Document document = new Document(PageSize.A4, 80, 50, 30, 65);

        PdfWriter writer = PdfWriter.getInstance(document, pdf);
        //writer.setViewerPreferences(PdfWriter.HideMenubar| PdfWriter.HideToolbar);
        writer.setViewerPreferences(PdfWriter.PageModeUseThumbs | PdfWriter.PageModeUseOutlines);
        //PdfOutline root = writer.getDirectContent().getRootOutline();
        //new PdfOutline(root, new PDFAction("http://nina.acad.bg/qmrf"), "a bookmark");

        //writer.addFileAttachment(arg0, arg1, arg2, arg3)

        if (docBuilder == null)
            docBuilder = docBuilderFactory.newDocumentBuilder();
        docBuilder.setErrorHandler(new SimpleErrorHandler(getClass().getName()));
        QMRFSchemaResolver resolver = new QMRFSchemaResolver("http://ambit.acad.bg/qmrf/qmrf.dtd", null);
        resolver.setIgnoreSystemID(true);
        docBuilder.setEntityResolver(resolver);

        org.w3c.dom.Document doc = null;
        try {
            doc = docBuilder.parse(xml);
        } catch (Exception x) {
            document.addCreationDate();
            document.addCreator(getClass().getName());
            document.open();
            document.add(new Paragraph(new Chunk(x.getMessage())));
            document.close();
            return;
        }

        document.addCreationDate();
        document.addCreator(getClass().getName());
        document.addKeywords(replaceTags(findNodeValue("keywords", doc)));
        document.addTitle(replaceTags(findNodeValue("QSAR_title", doc)));

        try {
            NodeList info = doc.getElementsByTagName("QMRF");
            for (int i = 0; i < info.getLength(); i++)
                document.addSubject(findAttributeValue("name", info.item(i)) + '.'
                        + findAttributeValue("version", info.item(i)));
        } catch (Exception x) {
            document.addSubject("QMRF");
        }
        try {
            document.addAuthor(listNodeAttributes(doc, "qmrf_authors", "author_ref", "author", att_author,
                    new Boolean(true)));
        } catch (Exception x) {
            document.addAuthor(getClass().getName());
        }

        document.open();
        PdfContentByte cb = writer.getDirectContent();

        try {
            headerTable(document, doc);
        } catch (Exception x) {
            document.add(new Paragraph(new Chunk(x.getMessage())));
            document.close();
            return;
        }

        PdfOutline root = writer.getDirectContent().getRootOutline();

        for (int i = 0; i < subchapters.length; i++)

            try {
                int align = Paragraph.ALIGN_LEFT;
                if (Mode.chapter == (Mode) subchapters[i][2]) {
                    document.add(new Paragraph(new Chunk('\n')));
                    PdfPTable table = new PdfPTable(1);

                    table.setWidthPercentage(100);

                    StringBuffer b = new StringBuffer();
                    b.append(findAttributeValue(subchapters[i][0].toString(), xml_attribute_chapter, doc));
                    b.append('.');
                    b.append(findAttributeValue(subchapters[i][0].toString(), xml_attribute_name, doc));

                    String bookmark = b.toString();

                    Chunk title = new Chunk(bookmark);
                    title.setLocalDestination(bookmark);
                    title.setFont(bfont);

                    PdfDestination destination = new PdfDestination(PdfDestination.FITH);
                    PdfOutline outline = new PdfOutline(root, destination, bookmark);

                    Paragraph p = new Paragraph(title);

                    PdfPCell cell = new PdfPCell(p);
                    cell.setBackgroundColor(chapterColor);
                    table.addCell(cell);
                    document.add(table);
                    float pos = writer.getVerticalPosition(false);
                    if (pos < 90)
                        document.newPage();
                } else {
                    Phrase phrase = new Phrase();
                    switch ((Mode) subchapters[i][2]) {
                    case title: {
                        StringBuffer b = new StringBuffer();
                        String cn = findAttributeValue(subchapters[i][0].toString(), xml_attribute_chapter,
                                doc);
                        if (cn == null)
                            break;

                        b.append(findAttributeValue(subchapters[i][0].toString(), xml_attribute_chapter, doc));
                        b.append('.');
                        b.append(findAttributeValue(subchapters[i][0].toString(), xml_attribute_name, doc));

                        String subchapterBookmark = b.toString();
                        b.append(':');

                        Chunk title = new Chunk(b.toString());
                        title.setLocalDestination(subchapterBookmark);
                        title.setFont(bfont);
                        phrase.add(title);

                        PdfDestination destination = new PdfDestination(PdfDestination.FITBH);
                        PdfOutline outline = new PdfOutline(root, destination, subchapterBookmark);

                        break;

                    }
                    case text: {
                        createNodePhrase(subchapters[i][0].toString(), doc, phrase, font);
                        align = Paragraph.ALIGN_JUSTIFIED;
                        break;
                    }
                    case answer: {
                        String a = findAnswer(subchapters[i][0].toString(), doc);
                        if (a != null) {
                            Chunk answer = new Chunk(a);
                            answer.setFont(font);
                            phrase.add(answer);
                        }
                        break;
                    }
                    case dataset: {
                        StringBuffer b = new StringBuffer();
                        b.append(findDataAvailable(subchapters[i][0].toString(), doc));
                        Chunk dataset = new Chunk(b.toString());
                        dataset.setFont(font);
                        phrase.add(dataset);
                        break;
                    }
                    case attachments: {
                        PdfPTable table = getAttachmentsAsTable(doc, "attachment_training_data");
                        if (table != null) {
                            phrase.add(new Paragraph("Training set(s)"));
                            phrase.add(table);
                        }
                        table = getAttachmentsAsTable(doc, "attachment_validation_data");
                        if (table != null) {
                            phrase.add(new Paragraph("Test set(s)"));
                            phrase.add(table);
                        }
                        table = getAttachmentsAsTable(doc, "attachment_documents");
                        if (table != null) {
                            phrase.add(new Paragraph("Supporting information"));
                            phrase.add(table);
                        }
                        break;
                        /*
                        StringBuffer b = new StringBuffer();
                        b.append("Training set(s)\n");
                         b.append(listAttachments(doc,"attachment_training_data"));
                         b.append("Test set(s)\n");
                         b.append(listAttachments(doc,"attachment_validation_data"));
                         b.append("Supporting information\n");
                         b.append(listAttachments(doc,"attachment_documents"));
                        Chunk attachments = new Chunk(b.toString());
                        attachments.setFont(font);
                        phrase.add(attachments);
                                
                        break;
                        */
                    }
                    case reference: {
                        try {
                            String value = listNodeAttributes(doc, subchapters[i][0].toString(),
                                    subchapters[i][3].toString(), subchapters[i][4].toString(),
                                    (String[]) subchapters[i][5], (Boolean) subchapters[i][6]);

                            Chunk reference = new Chunk(value);
                            reference.setFont(font);
                            align = Paragraph.ALIGN_JUSTIFIED;
                            phrase.add(reference);
                        } catch (Exception x) {

                        }
                        break;

                    }
                    }

                    Paragraph p = new Paragraph(phrase);
                    p.setAlignment(align);
                    document.add(p);
                    float pos = writer.getVerticalPosition(false);
                    /*
                    cb.moveTo(0, pos);
                    cb.lineTo(PageSize.A4.width(), pos);
                    cb.stroke();
                    */
                    if (pos < 90)
                        document.newPage();
                }
            } catch (Exception x) {
                x.printStackTrace();
            }

        document.close();

    } catch (Exception e) {
        e.printStackTrace();
        System.err.println(e.getMessage());
    }
}

From source file:ambit2.data.qmrf.Qmrf_Xml_Pdf.java

License:Open Source License

public void xml2pdf(InputSource xml, OutputStream pdf) {

    try {/*from   w  ww .  ja  v a 2s .  c  o m*/
        Document document = new Document(PageSize.A4, 80, 50, 30, 65);

        PdfWriter writer = PdfWriter.getInstance(document, pdf);
        //writer.setViewerPreferences(PdfWriter.HideMenubar| PdfWriter.HideToolbar);
        writer.setViewerPreferences(PdfWriter.PageModeUseThumbs | PdfWriter.PageModeUseOutlines);
        //PdfOutline root = writer.getDirectContent().getRootOutline();
        //new PdfOutline(root, new PDFAction("http://nina.acad.bg/qmrf"), "a bookmark");

        //writer.addFileAttachment(arg0, arg1, arg2, arg3)

        if (docBuilder == null)
            docBuilder = docBuilderFactory.newDocumentBuilder();
        docBuilder.setErrorHandler(new SimpleErrorHandler(getClass().getName()));
        QMRFSchemaResolver resolver = new QMRFSchemaResolver("http://ambit2.acad.bg/qmrf/qmrf.dtd", null);
        resolver.setIgnoreSystemID(true);
        docBuilder.setEntityResolver(resolver);

        org.w3c.dom.Document doc = null;
        try {
            doc = docBuilder.parse(xml);
        } catch (Exception x) {
            document.addCreationDate();
            document.addCreator(getClass().getName());
            document.open();
            document.add(new Paragraph(new Chunk(x.getMessage())));
            document.close();
            return;
        }

        document.addCreationDate();
        document.addCreator(getClass().getName());
        document.addKeywords(replaceTags(findNodeValue("keywords", doc)));
        document.addTitle(replaceTags(findNodeValue("QSAR_title", doc)));

        try {
            NodeList info = doc.getElementsByTagName("QMRF");
            for (int i = 0; i < info.getLength(); i++)
                document.addSubject(findAttributeValue("name", info.item(i)) + '.'
                        + findAttributeValue("version", info.item(i)));
        } catch (Exception x) {
            document.addSubject("QMRF");
        }
        try {
            document.addAuthor(listNodeAttributes(doc, "qmrf_authors", "author_ref", "author", att_author,
                    new Boolean(true)));
        } catch (Exception x) {
            document.addAuthor(getClass().getName());
        }

        document.open();
        PdfContentByte cb = writer.getDirectContent();

        try {
            headerTable(document, doc);
        } catch (Exception x) {
            document.add(new Paragraph(new Chunk(x.getMessage())));
            document.close();
            return;
        }

        PdfOutline root = writer.getDirectContent().getRootOutline();

        for (int i = 0; i < subchapters.length; i++)

            try {
                int align = Paragraph.ALIGN_LEFT;
                if (Mode.chapter == (Mode) subchapters[i][2]) {
                    document.add(new Paragraph(new Chunk('\n')));
                    PdfPTable table = new PdfPTable(1);

                    table.setWidthPercentage(100);

                    StringBuffer b = new StringBuffer();
                    b.append(findAttributeValue(subchapters[i][0].toString(), xml_attribute_chapter, doc));
                    b.append('.');
                    b.append(findAttributeValue(subchapters[i][0].toString(), xml_attribute_name, doc));

                    String bookmark = b.toString();

                    Chunk title = new Chunk(bookmark);
                    title.setLocalDestination(bookmark);
                    title.setFont(bfont);

                    PdfDestination destination = new PdfDestination(PdfDestination.FITH);
                    PdfOutline outline = new PdfOutline(root, destination, bookmark);

                    Paragraph p = new Paragraph(title);

                    PdfPCell cell = new PdfPCell(p);
                    cell.setBackgroundColor(chapterColor);
                    table.addCell(cell);
                    document.add(table);
                    float pos = writer.getVerticalPosition(false);
                    if (pos < 90)
                        document.newPage();
                } else {
                    Phrase phrase = new Phrase();
                    switch ((Mode) subchapters[i][2]) {
                    case title: {
                        StringBuffer b = new StringBuffer();
                        String cn = findAttributeValue(subchapters[i][0].toString(), xml_attribute_chapter,
                                doc);
                        if (cn == null)
                            break;

                        b.append(findAttributeValue(subchapters[i][0].toString(), xml_attribute_chapter, doc));
                        b.append('.');
                        b.append(findAttributeValue(subchapters[i][0].toString(), xml_attribute_name, doc));

                        String subchapterBookmark = b.toString();
                        b.append(':');

                        Chunk title = new Chunk(b.toString());
                        title.setLocalDestination(subchapterBookmark);
                        title.setFont(bfont);
                        phrase.add(title);

                        PdfDestination destination = new PdfDestination(PdfDestination.FITBH);
                        PdfOutline outline = new PdfOutline(root, destination, subchapterBookmark);

                        break;

                    }
                    case text: {
                        createNodePhrase(subchapters[i][0].toString(), doc, phrase, font);
                        align = Paragraph.ALIGN_JUSTIFIED;
                        break;
                    }
                    case answer: {
                        String a = findAnswer(subchapters[i][0].toString(), doc);
                        if (a != null) {
                            Chunk answer = new Chunk(a);
                            answer.setFont(font);
                            phrase.add(answer);
                        }
                        break;
                    }
                    case dataset: {
                        StringBuffer b = new StringBuffer();
                        b.append(findDataAvailable(subchapters[i][0].toString(), doc));
                        Chunk dataset = new Chunk(b.toString());
                        dataset.setFont(font);
                        phrase.add(dataset);
                        break;
                    }
                    case attachments: {
                        PdfPTable table = getAttachmentsAsTable(doc, "attachment_training_data");
                        if (table != null) {
                            phrase.add(new Paragraph("Training set(s)"));
                            phrase.add(table);
                        }
                        table = getAttachmentsAsTable(doc, "attachment_validation_data");
                        if (table != null) {
                            phrase.add(new Paragraph("Test set(s)"));
                            phrase.add(table);
                        }
                        table = getAttachmentsAsTable(doc, "attachment_documents");
                        if (table != null) {
                            phrase.add(new Paragraph("Supporting information"));
                            phrase.add(table);
                        }
                        break;
                        /*
                        StringBuffer b = new StringBuffer();
                        b.append("Training set(s)\n");
                         b.append(listAttachments(doc,"attachment_training_data"));
                         b.append("Test set(s)\n");
                         b.append(listAttachments(doc,"attachment_validation_data"));
                         b.append("Supporting information\n");
                         b.append(listAttachments(doc,"attachment_documents"));
                        Chunk attachments = new Chunk(b.toString());
                        attachments.setFont(font);
                        phrase.add(attachments);
                                
                        break;
                        */
                    }
                    case reference: {
                        try {
                            String value = listNodeAttributes(doc, subchapters[i][0].toString(),
                                    subchapters[i][3].toString(), subchapters[i][4].toString(),
                                    (String[]) subchapters[i][5], (Boolean) subchapters[i][6]);

                            Chunk reference = new Chunk(value);
                            reference.setFont(font);
                            align = Paragraph.ALIGN_JUSTIFIED;
                            phrase.add(reference);
                        } catch (Exception x) {

                        }
                        break;

                    }
                    }

                    Paragraph p = new Paragraph(phrase);
                    p.setAlignment(align);
                    document.add(p);
                    float pos = writer.getVerticalPosition(false);
                    /*
                    cb.moveTo(0, pos);
                    cb.lineTo(PageSize.A4.width(), pos);
                    cb.stroke();
                    */
                    if (pos < 90)
                        document.newPage();
                }
            } catch (Exception x) {
                x.printStackTrace();
            }

        document.close();

    } catch (Exception e) {
        e.printStackTrace();
        System.err.println(e.getMessage());
    }
}

From source file:classroom.filmfestival_c.Movies20.java

@SuppressWarnings("unchecked")
public static void main(String[] args) {
    // step 1/*w ww  . j  ava  2 s . c  om*/
    Rectangle rect = PageSize.A4.rotate();
    Document document = new Document(rect);
    try {
        // step 2
        OutputStream os = new FileOutputStream(RESULT);
        PdfWriter writer = PdfWriter.getInstance(document, os);
        Rectangle art = new Rectangle(rect.getLeft(36), rect.getBottom(36), rect.getRight(36), rect.getTop(36));
        writer.setBoxSize("art", art);
        writer.setViewerPreferences(PdfWriter.PageModeUseOutlines);
        // step 3
        document.open();
        // step 4

        PdfOutline root = writer.getDirectContent().getRootOutline();

        Session session = (Session) MySessionFactory.currentSession();
        Query q = session.createQuery(
                "select distinct festival.id.day from FestivalScreening as festival order by festival.id.day");
        java.util.List<Date> days = q.list();

        for (Date day : days) {
            GregorianCalendar gc = new GregorianCalendar();
            gc.setTime(day);
            if (gc.get(GregorianCalendar.YEAR) != YEAR)
                continue;
            createSheet(session, day, writer);
            new PdfOutline(root, new PdfDestination(PdfDestination.FIT), day.toString());
            document.newPage();
        }
        // step 5
        document.close();
    } catch (IOException e) {
        LOGGER.error("IOException: ", e);
    } catch (DocumentException e) {
        LOGGER.error("DocumentException: ", e);
    }
}

From source file:com.amphisoft.epub2pdf.content.XhtmlHandler.java

License:Open Source License

private void addToBookmarks(String currentFile, String aName) { // curFileCP, aName
    try {//from  w  w w  . j  ava2 s. c o m
        StringBuilder lookupSB = new StringBuilder();
        String currentFileBaseName = new File(currentFile).getName();
        String currentFileEpubRooted = null;
        for (String spineRef : sourceEpub.getOpf().spineHrefs()) {
            if (spineRef.endsWith(currentFileBaseName)) {
                currentFileEpubRooted = spineRef;
                break;
            }
        }
        if (currentFileEpubRooted == null) {
            //throw new Exception();
        }
        lookupSB.append(currentFileEpubRooted);
        if (aName != null && !aName.isEmpty()) {
            lookupSB.append('#');
            lookupSB.append(aName);
        }
        String lookup = lookupSB.toString();
        NavPoint nP = sourceEpub.getNcx().findNavPoint(lookup);
        TreeNode<TocTreeNode> npNode = TocTreeNode.findInTreeByNavPoint(tocTree, nP);
        if (nP != null) {
            document.newPage();

            PdfOutline pdfOutlineParent = bookmarkRoot;
            if (npNode != null) {
                TreeNode<TocTreeNode> parent = npNode.getParent();
                if (parent != null) {
                    TocTreeNode parentTTN = parent.getValue();
                    if (parentTTN != null && parentTTN.getPdfOutline() != null) {
                        pdfOutlineParent = parentTTN.getPdfOutline();
                    }
                }
            }

            PdfDestination here = new PdfDestination(PdfDestination.FIT);
            PdfOutline pdfTocEntry = new PdfOutline(pdfOutlineParent, here, nP.getNavLabelText());
            if (npNode != null) {
                npNode.getValue().setPdfDestination(here);
                npNode.getValue().setPdfOutline(pdfTocEntry);
            }
        } else {
            //throw new Exception("NCX lookup fail: " + lookup);
        }
    } catch (Exception e) {
        //printlnerr("Failed to update PDF bookmarks with Anchor " + aName + ": " + e.getMessage());
    }
}

From source file:com.amphisoft.epub2pdf.Converter.java

License:Open Source License

public void convert(String epubPath) throws IOException, DocumentException {
    File epubFile = new File(epubPath);
    if (!(epubFile.canRead())) {
        throw new IOException("Could not read " + epubPath);
    } else {//www.  ja  va2  s. c  o  m
        System.err.println("Converting " + epubFile.getAbsolutePath());
    }
    String epubFilename = epubFile.getName();
    String epubFilenameBase = epubFilename.substring(0, epubFilename.length() - 5);
    String pdfFilename = epubFilenameBase + ".pdf";

    File outputFile = new File(outputDir.getAbsolutePath() + File.separator + pdfFilename);

    epubIn = Epub.fromFile(epubPath);
    XhtmlHandler.setSourceEpub(epubIn);

    Opf opf = epubIn.getOpf();
    List<String> contentPaths = opf.spineHrefs();
    List<File> contentFiles = new ArrayList<File>();
    for (String path : contentPaths) {
        contentFiles.add(new File(epubIn.getContentRoot(), path));
    }
    Ncx ncx = epubIn.getNcx();

    List<NavPoint> ncxToc = new ArrayList<NavPoint>();
    if (ncx != null) {
        ncxToc.addAll(ncx.getNavPointsFlat());
    }

    Tree<TocTreeNode> tocTree = TocTreeNode.buildTocTree(ncx);
    XhtmlHandler.setTocTree(tocTree);

    Document doc = new Document();
    boolean pageSizeOK = doc.setPageSize(pageSize);
    boolean marginsOK = doc.setMargins(marginLeftPt, marginRightPt, marginTopPt, marginBottomPt);

    System.err.println("Writing PDF to " + outputFile.getAbsolutePath());
    PdfWriter writer = PdfWriter.getInstance(doc, new FileOutputStream(outputFile));
    writer.setStrictImageSequence(true);
    PdfOutline bookmarkRoot = null;

    if (!(pageSizeOK && marginsOK)) {
        throw new RuntimeException("Failed to set PDF page size a/o margins");
    }

    int fileCount = contentFiles.size();
    printlnerr("Processing " + fileCount + " HTML file(s): ");
    int currentFile = 0;

    for (File file : contentFiles) {
        currentFile++;

        char progressChar;

        int mod10 = currentFile % 10;
        if (mod10 == 5)
            progressChar = '5';
        else if (mod10 == 0)
            progressChar = '0';
        else
            progressChar = '.';

        printerr(progressChar);
        if (!(doc.isOpen())) {
            doc.open();
            doc.newPage();
            bookmarkRoot = writer.getRootOutline();
            XhtmlHandler.setBookmarkRoot(bookmarkRoot);
        }
        NavPoint fileLevelNP = Ncx.findNavPoint(ncxToc, file.getName());
        TreeNode<TocTreeNode> npNode = TocTreeNode.findInTreeByNavPoint(tocTree, fileLevelNP);

        if (fileLevelNP != null) {
            doc.newPage();
            PdfOutline pdfOutlineParent = bookmarkRoot;
            if (npNode != null) {
                TreeNode<TocTreeNode> parent = npNode.getParent();
                if (parent != null) {
                    TocTreeNode parentTTN = parent.getValue();
                    if (parentTTN != null && parentTTN.getPdfOutline() != null) {
                        pdfOutlineParent = parentTTN.getPdfOutline();
                    }
                }
            }

            PdfDestination here = new PdfDestination(PdfDestination.FIT);
            PdfOutline pdfTocEntry = new PdfOutline(pdfOutlineParent, here, fileLevelNP.getNavLabelText());
            if (npNode != null) {
                npNode.getValue().setPdfDestination(here);
                npNode.getValue().setPdfOutline(pdfTocEntry);
            }
        }
        XhtmlHandler.process(file.getCanonicalPath(), doc);
    }
    printlnerr();

    doc.close();
    System.err.println("PDF written to " + outputFile.getAbsolutePath());
    epubIn.cleanup();
}

From source file:com.benfante.minimark.blo.AssessmentPdfBuilder.java

License:Apache License

/**
 * Build the contatenated PDF for a list of assessments.
 *
 * @param assessments The assessments//ww  w .java  2s . c o  m
 * @param baseUrl The base URL for retrieving images and resource. If null it will not be set.
 * @param locale The locale for producing the document. Id null, the default locale will be used.
 * @return The PDF document.
 */
public byte[] buildPdf(List<AssessmentFilling> assessments, String baseUrl, Locale locale) throws Exception {
    ByteArrayOutputStream pdfos = new ByteArrayOutputStream();
    List master = new ArrayList();
    Document document = null;
    PdfCopy writer = null;
    PdfOutline rootOutline = null;
    try {
        int f = 0;
        int pageOffset = 0;
        for (AssessmentFilling assessment : assessments) {
            // we create a reader for a certain document
            PdfReader reader = new PdfReader(buildPdf(assessment, baseUrl, locale));
            reader.consolidateNamedDestinations();
            // we retrieve the total number of pages
            int n = reader.getNumberOfPages();
            List bookmarks = SimpleBookmark.getBookmark(reader);
            if (bookmarks != null) {
                if (pageOffset != 0) {
                    SimpleBookmark.shiftPageNumbers(bookmarks, pageOffset, null);
                }
                master.addAll(bookmarks);
            }
            pageOffset += n;
            if (f == 0) {
                // step 1: creation of a document-object
                document = new Document(reader.getPageSizeWithRotation(1));
                // step 2: we create a writer that listens to the document
                writer = new PdfCopy(document, pdfos);
                writer.setViewerPreferences(PdfWriter.PageModeUseOutlines);
                // step 3: we open the document
                document.open();
                // initialize rootOutline for assessment bookmarks creation
                PdfContentByte cb = writer.getDirectContent();
                rootOutline = cb.getRootOutline();
            }
            // step 4: we add content
            new PdfOutline(rootOutline, new PdfDestination(PdfDestination.FIT),
                    assessment.getLastName() + " " + assessment.getFirstName());
            PdfImportedPage page;
            for (int i = 0; i < n;) {
                ++i;
                page = writer.getImportedPage(reader, i);
                writer.addPage(page);
            }
            PRAcroForm form = reader.getAcroForm();
            if (form != null) {
                writer.copyAcroForm(reader);
            }
            f++;
        }
    } finally {
        if (pdfos != null) {
            try {
                pdfos.close();
            } catch (IOException ioe) {
            }
        }
        if (!master.isEmpty()) {
            writer.setOutlines(master);
        }
        // step 5: we close the document
        if (document != null && document.isOpen()) {
            document.close();
        }
    }
    return pdfos.toByteArray();
}

From source file:com.geek.tutorial.itext.bookmarks.Outline.java

License:Open Source License

public Outline() throws Exception {

    Document document = new Document();
    PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream("outline.pdf"));
    document.open();/*from  ww w  . j a  v  a2s. co m*/

    // Code 1
    document.add(new Chunk("Chapter 1").setLocalDestination("1"));
    document.newPage();

    document.add(new Chunk("Chapter 2").setLocalDestination("2"));
    document.add(new Paragraph(new Chunk("Sub 2.1").setLocalDestination("2.1")));
    document.add(new Paragraph(new Chunk("Sub 2.2").setLocalDestination("2.2")));
    document.newPage();

    document.add(new Chunk("Chapter 3").setLocalDestination("3"));

    // Code 2
    PdfContentByte cb = writer.getDirectContent();
    PdfOutline root = cb.getRootOutline();

    // Code 3
    PdfOutline oline1 = new PdfOutline(root, PdfAction.gotoLocalPage("1", false), "Chapter 1");

    PdfOutline oline2 = new PdfOutline(root, PdfAction.gotoLocalPage("2", false), "Chapter 2");
    oline2.setOpen(false);
    PdfOutline oline2_1 = new PdfOutline(oline2, PdfAction.gotoLocalPage("2.1", false), "Sub 2.1");
    PdfOutline oline2_2 = new PdfOutline(oline2, PdfAction.gotoLocalPage("2.2", false), "Sub 2.2");

    PdfOutline oline3 = new PdfOutline(root, PdfAction.gotoLocalPage("3", false), "Chapter 3");

    document.close();
}

From source file:de.unigoettingen.sub.commons.contentlib.pdflib.PDFManager.java

License:Apache License

/**
 * ************************************************************************* Sets all the bookmarks which have the same page name for this page.
 * Te hierachical relationships between bookmarks are recognized
 * /*w  w  w.  ja v a  2s .c o  m*/
 * @param writer the writer
 * @param pdfdestination The PDF destination of the page
 * @param pagenumber the name of the page ****************************************** ******************************
 */
private void setBookmarksForPage(PdfWriter writer, PdfDestination pdfdestination, Integer pagenumber) {
    PdfContentByte cb = writer.getDirectContent();
    // PdfOutline rootoutline = cb.getRootOutline();

    // iterate through the tree and find all the bookmarks for this page
    // bookmarks for this page will have the same pagenumber

    if ((structureList == null) || (structureList.isEmpty())) {
        return; // no bookmarks available
    }

    // iterate over all parent bookmarks
    for (PDFBookmark bm : structureList) {
        if (bm.getImageNumber().intValue() == pagenumber.intValue()) {
            // add bookmark
            // rootoutline = cb.getRootOutline(); // get root outline
            PdfOutline outline = new PdfOutline(cb.getRootOutline(), pdfdestination, bm.getContent()); // create
            // a
            // new
            // outline as child
            // of rootoutline
            bm.setPdfOutline(outline);
        }

        checkChildrenBookmarks(bm, pdfdestination, pagenumber); // check for
        // bookmarks
        // children

    }
}

From source file:de.unigoettingen.sub.commons.contentlib.pdflib.PDFManager.java

License:Apache License

/**
 * ************************************************************************* checks all children of a bookmark and see if any of them fits to the
 * appropriate page name/ page number./*from   ww w  . j a v  a 2s. c  om*/
 * 
 * @param parent the parent
 * @param pdfdestination the pdfdestination
 * @param pagenumber ************************************************************** **********
 */
private void checkChildrenBookmarks(PDFBookmark parent, PdfDestination pdfdestination, Integer pagenumber) {
    for (PDFBookmark child : parent.getChildren()) {
        if (child == null) {
            // should not happen, but may happen, if we have a logical
            // <div> which
            // does not link to a phys div
            continue; // get next in loop
        }
        if (child.getImageNumber().intValue() == pagenumber.intValue()) {
            // must set a bookmark for this page
            PDFBookmark childsparent = findParentBookmark(child);
            if (childsparent != null) {
                // parent was found, so add this bookmark to the PDF
                PdfOutline parentOutline = childsparent.getPdfOutline();
                if (parentOutline == null) {
                    // parent doesn't have an outline probably because
                    // it started on a later
                    // page - anyhow write something to logfile
                    LOGGER.error("Parent Bookmark \"" + childsparent.getContent() + "\"has no PdfOutline.");
                } else {
                    PdfOutline outline = new PdfOutline(parentOutline, pdfdestination, child.getContent()); // create
                    // a new outline as child of rootoutline
                    child.setPdfOutline(outline);
                    LOGGER.debug("Bookmark \"" + childsparent.getContent() + "\"set successfully");
                }
            }
        }

        // check children of this child
        checkChildrenBookmarks(child, pdfdestination, pagenumber);
    }

}

From source file:org.areasy.common.doclet.document.Bookmarks.java

License:Open Source License

/**
 * Creates entries for all the given bookmark entry objects.
 * If any of them has child nodes, the method calls itself
 * recursively to process them as well.//from  w  w w . j  av a2 s  .c o m
 *
 * @param parent  The parent PDF outline object.
 * @param entries The bookmark entries for which to add outline objects.
 */
private static void createBookmarks(PdfOutline parent, BookmarkEntry[] entries) {
    if (entries == null)
        return;

    for (int i = 0; i < entries.length; i++) {
        String name = entries[i].getDestinationName();

        PdfAction action = null;

        if (name == null)
            action = new PdfAction();
        else
            action = PdfAction.gotoLocalPage(name, false);

        PdfOutline outline = new PdfOutline(parent, action, entries[i].getLabel());
        outline.setOpen(false);

        createBookmarks(outline, entries[i].getChildren());
    }
}