Example usage for org.apache.pdfbox.pdmodel PDDocument getDocumentCatalog

List of usage examples for org.apache.pdfbox.pdmodel PDDocument getDocumentCatalog

Introduction

In this page you can find the example usage for org.apache.pdfbox.pdmodel PDDocument getDocumentCatalog.

Prototype

public PDDocumentCatalog getDocumentCatalog() 

Source Link

Document

This will get the document CATALOG.

Usage

From source file:org.pdfmetamodifier.IOHelper.java

License:Apache License

/**
 * Save Outlines (bookmarks).//w ww . j a v a2s. co m
 * 
 * @param pdfFile
 *            Source PDF file.
 * @param outlinesFile
 *            File with Outlines (bookmarks) in user-frendly format.
 * @throws IOException
 */
/*
 * See:
 *      https://svn.apache.org/viewvc/pdfbox/trunk/examples/src/main/java/org/apache/pdfbox/examples/pdmodel/PrintBookmarks.java?view=markup
 */
public static void saveOutlines(final File pdfFile, final File outlinesFile) throws IOException {
    PDDocument document = null;
    try {
        // Read PDF file.
        document = PDDocument.load(pdfFile);
        if (document.isEncrypted()) {
            throw new IOException("Document is encrypted.");
        }

        // Get data from PDF file.
        final PDDocumentCatalog catalog = document.getDocumentCatalog();

        final PDDocumentOutline outlines = catalog.getDocumentOutline();

        final PDPageTree pages = catalog.getPages();

        final PDDocumentNameDictionary namesDictionary = new PDDocumentNameDictionary(catalog);
        final PDDestinationNameTreeNode destinations = namesDictionary.getDests();

        // Convert.
        final List<String> lines = OutlineHelper.outlinesToLineList(outlines, pages, destinations);

        // Write line list into the text file.
        Files.write(outlinesFile.toPath(), lines);
    } finally {
        if (document != null) {
            document.close();
        }
    }
}

From source file:org.pdfmetamodifier.IOHelper.java

License:Apache License

/**
 * Update Outlines (bookmarks).//w  ww  .  ja  v a  2s  .  c o  m
 * 
 * @param pdfFile
 *            Source PDF file.
 * @param outlinesFile
 *            File with Outlines (bookmarks) in user-frendly format.
 * @throws IOException
 */
/*
 * See:
 *      https://svn.apache.org/viewvc/pdfbox/trunk/examples/src/main/java/org/apache/pdfbox/examples/pdmodel/CreateBookmarks.java?view=markup
 */
public static void updateOutlines(final File pdfFile, final File outlinesFile) throws IOException {
    // Read bookmark list from text file.
    final List<String> lines = Files.readAllLines(outlinesFile.toPath());

    PDDocument document = null;
    try {
        // Open PDF file.
        document = PDDocument.load(pdfFile);
        if (document.isEncrypted()) {
            throw new IOException("Document is encrypted.");
        }

        // Get data from PDF file.
        final PDDocumentCatalog catalog = document.getDocumentCatalog();

        final PDPageTree pages = catalog.getPages();

        // Convert.
        final PDDocumentOutline outlines = OutlineHelper.lineListToOutlines(pages, lines);

        // Set outlines.
        catalog.setDocumentOutline(outlines);

        // Create temporary PDF file for result.
        if (TEMP_PDF.exists()) {
            TEMP_PDF.delete();
        }

        // Save result to temporary PDF file.
        document.save(TEMP_PDF);

        // Replace original PDF file.
        pdfFile.delete();
        Files.move(Paths.get(TEMP_PDF.toURI()), Paths.get(pdfFile.toURI()));
    } finally {
        if (document != null) {
            document.close();
        }
    }
}

From source file:org.pdfmetamodifier.IOHelper.java

License:Apache License

/**
 * Save all Attached (embedded) files to some directory.
 * /*from  w ww. j  a  va  2  s . c  om*/
 * @param pdfFile
 *            Source PDF file.
 * @param outputDir
 *            Target directory.
 * @throws IOException
 */
/*
 * See:
 *      https://svn.apache.org/viewvc/pdfbox/trunk/examples/src/main/java/org/apache/pdfbox/examples/pdmodel/ExtractEmbeddedFiles.java?view=markup
 */
public static void saveAttachments(final File pdfFile, final File outputDir) throws IOException {
    PDDocument document = null;
    try {
        // Read PDF file.
        document = PDDocument.load(pdfFile);
        if (document.isEncrypted()) {
            throw new IOException("Document is encrypted.");
        }

        // Extract Embedded (attached) files.
        final PDDocumentNameDictionary documentNameDictionary = new PDDocumentNameDictionary(
                document.getDocumentCatalog());
        final PDEmbeddedFilesNameTreeNode embeddedFilesNameTree = documentNameDictionary.getEmbeddedFiles();
        if (embeddedFilesNameTree != null) {
            extractFiles(outputDir, embeddedFilesNameTree.getNames());

            final List<PDNameTreeNode<PDComplexFileSpecification>> kids = embeddedFilesNameTree.getKids();
            if (kids != null) {
                for (PDNameTreeNode<PDComplexFileSpecification> nameTreeNode : kids) {
                    extractFiles(outputDir, nameTreeNode.getNames());
                }
            }
        }

        // Extract Embedded (attached) from annotations.
        for (PDPage page : document.getPages()) {
            for (PDAnnotation annotation : page.getAnnotations()) {
                if (annotation instanceof PDAnnotationFileAttachment) {
                    final PDAnnotationFileAttachment fileAttach = (PDAnnotationFileAttachment) annotation;

                    final PDComplexFileSpecification fileSpec = (PDComplexFileSpecification) fileAttach
                            .getFile();
                    extractFile(outputDir, fileSpec);
                }
            }
        }
    } finally {
        if (document != null) {
            document.close();
        }
    }
}

From source file:org.pdfmetamodifier.IOHelper.java

License:Apache License

/**
 * Remove all Attached (embedded) files.
 * //from  www .  j av a  2 s.c om
 * @param pdfFile
 *            Source PDF file.
 * @throws IOException
 */
public static void removeAttachments(final File pdfFile) throws IOException {
    PDDocument document = null;
    try {
        // Read PDF file.
        document = PDDocument.load(pdfFile);
        if (document.isEncrypted()) {
            throw new IOException("Document is encrypted.");
        }

        // Clean the tree to the document catalog.
        document.getDocumentCatalog().setNames(null);

        // Create temporary PDF file for result.
        if (TEMP_PDF.exists()) {
            TEMP_PDF.delete();
        }

        // Save result to temporary PDF file.
        document.save(TEMP_PDF);

        // Replace original PDF file.
        pdfFile.delete();
        Files.move(Paths.get(TEMP_PDF.toURI()), Paths.get(pdfFile.toURI()));
    } finally {
        if (document != null) {
            document.close();
        }
    }
}

From source file:org.pdfmetamodifier.IOHelper.java

License:Apache License

/**
 * Add new Attached (embedded) files./*from   w w  w  .  j  a va  2s . c  o m*/
 * 
 * @param pdfFile
 *            Source PDF file.
 * @param attachmentFiles
 *            Files that will be attached (embedded).
 * @throws IOException
 */
/*
 * See:
 *      https://svn.apache.org/viewvc/pdfbox/trunk/examples/src/main/java/org/apache/pdfbox/examples/pdmodel/EmbeddedFiles.java?view=markup
 */
public static void addAttachments(final File pdfFile, final List<File> attachmentFiles) throws IOException {
    PDDocument document = null;
    try {
        // Read PDF file.
        document = PDDocument.load(pdfFile);
        if (document.isEncrypted()) {
            throw new IOException("Document is encrypted.");
        }

        // Embedded (attached) files are stored in a named tree.
        final PDEmbeddedFilesNameTreeNode root = new PDEmbeddedFilesNameTreeNode();
        final List<PDEmbeddedFilesNameTreeNode> kids = new ArrayList<PDEmbeddedFilesNameTreeNode>();
        root.setKids(kids);

        // Add the tree to the document catalog.
        final PDDocumentNameDictionary namesDictionary = new PDDocumentNameDictionary(
                document.getDocumentCatalog());
        namesDictionary.setEmbeddedFiles(root);
        document.getDocumentCatalog().setNames(namesDictionary);

        // For all Embedded (attached) files.
        for (File file : attachmentFiles) {
            final String filename = file.getName();

            // First create the file specification, which holds the Embedded (attached) file.
            final PDComplexFileSpecification complexFileSpecification = new PDComplexFileSpecification();
            complexFileSpecification.setFile(filename);

            // Create a dummy file stream, this would probably normally be a FileInputStream.
            final ByteArrayInputStream fileStream = new ByteArrayInputStream(Files.readAllBytes(file.toPath()));
            final PDEmbeddedFile embededFile = new PDEmbeddedFile(document, fileStream);
            complexFileSpecification.setEmbeddedFile(embededFile);

            // Create a new tree node and add the Embedded (attached) file.
            final PDEmbeddedFilesNameTreeNode embeddedFilesNameTree = new PDEmbeddedFilesNameTreeNode();
            embeddedFilesNameTree.setNames(Collections.singletonMap(filename, complexFileSpecification));

            // Add the new node as kid to the root node.
            kids.add(embeddedFilesNameTree);
        }

        // Create temporary PDF file for result.
        if (TEMP_PDF.exists()) {
            TEMP_PDF.delete();
        }

        // Save result to temporary PDF file.
        document.save(TEMP_PDF);

        // Replace original PDF file.
        pdfFile.delete();
        Files.move(Paths.get(TEMP_PDF.toURI()), Paths.get(pdfFile.toURI()));
    } finally {
        if (document != null) {
            document.close();
        }
    }
}

From source file:org.pdfsam.pdfbox.component.OutlineMerger.java

License:Open Source License

public OutlineMerger(PDDocument document) {
    requireNonNull(document, "Unable to retrieve bookmarks from a null document.");
    PDDocumentNameDictionary names = document.getDocumentCatalog().getNames();
    if (names != null) {
        this.destinations = names.getDests();
    }//from  w w  w.java 2 s.c o m
    this.outline = Optional.ofNullable(document.getDocumentCatalog().getDocumentOutline());
}

From source file:org.pdfsam.pdfbox.component.PDFBoxOutlineUtils.java

License:Open Source License

/**
 * @param document/* w  w w  .  java 2 s. co  m*/
 * @return the max bookmarks level where a page destination (page destination, named destination, goto action) is defined.
 */
public static int getMaxBookmarkLevel(PDDocument document) {
    PDDestinationNameTreeNode destinations = null;
    PDDocumentNameDictionary names = document.getDocumentCatalog().getNames();
    if (names != null) {
        destinations = names.getDests();
    }
    return getMaxBookmarkLevel(document.getDocumentCatalog().getDocumentOutline(), destinations, 0);
}

From source file:org.pdfsam.pdfbox.PDFBoxOutlineLevelsHandler.java

License:Open Source License

public PDFBoxOutlineLevelsHandler(PDDocument document, String matchingTitleRegEx) {
    requireNonNull(document, "Unable to retrieve bookmarks from a null document.");
    this.document = document;
    this.pages = document.getPages();
    PDDocumentNameDictionary names = document.getDocumentCatalog().getNames();
    if (names != null) {
        this.namedDestinations = names.getDests();
    }/* ww  w. ja  v a  2 s . com*/
    if (isNotBlank(matchingTitleRegEx)) {
        this.titleMatchingPattern = Pattern.compile(matchingTitleRegEx);
    }
}

From source file:org.qifu.util.PdfConvertUtils.java

License:Apache License

public static List<File> toImageFiles(File pdfFile, int resolution) throws Exception {
    PDDocument document = PDDocument.load(pdfFile);
    PDFRenderer pdfRenderer = new PDFRenderer(document);
    /*/*from ww w  . j  a  va2s. c  o  m*/
    List<PDPage> pages = new LinkedList<PDPage>();
    for (int i=0; i < document.getDocumentCatalog().getPages().getCount(); i++) {
       pages.add( document.getDocumentCatalog().getPages().get(i) );
    }
    */
    File tmpDir = new File(Constants.getWorkTmpDir() + "/" + PdfConvertUtils.class.getSimpleName() + "/"
            + System.currentTimeMillis() + "/");
    FileUtils.forceMkdir(tmpDir);
    List<File> files = new LinkedList<File>();
    //int len = String.valueOf(pages.size()+1).length();
    int len = String.valueOf(document.getDocumentCatalog().getPages().getCount() + 1).length();
    //for (int i=0; i<pages.size(); i++) {
    for (int i = 0; i < document.getDocumentCatalog().getPages().getCount(); i++) {
        String name = StringUtils.leftPad(String.valueOf(i + 1), len, "0");
        BufferedImage bufImage = pdfRenderer.renderImageWithDPI(i, resolution, ImageType.RGB);
        File imageFile = new File(tmpDir.getPath() + "/" + name + ".png");
        FileOutputStream fos = new FileOutputStream(imageFile);
        ImageIOUtil.writeImage(bufImage, "png", fos, resolution);
        fos.flush();
        fos.close();
        files.add(imageFile);
    }
    document.close();
    tmpDir = null;
    return files;
}

From source file:org.saiku.web.rest.resources.ExporterResource.java

License:Apache License

/**
 * Export chart to a file.//from   w w w.j  a  v  a2  s  . com
 * @summary Export Chart.
 * @param type The export type (png, svg, jpeg)
 * @param svg The SVG
 * @param size The size
 * @param name The name
 * @return A reponse containing the chart export.
 */
@POST
@Produces({ "image/*" })
@Path("/saiku/chart")
public Response exportChart(@FormParam("type") @DefaultValue("png") String type, @FormParam("svg") String svg,
        @FormParam("size") Integer size, @FormParam("name") String name) {
    try {
        final String imageType = type.toUpperCase();
        Converter converter = Converter.byType("PDF");
        if (converter == null) {
            throw new Exception("Image convert is null");
        }

        //             resp.setContentType(converter.getContentType());
        //             resp.setHeader("Content-disposition", "attachment; filename=chart." + converter.getExtension());
        //             final Integer size = req.getParameter("size") != null? Integer.parseInt(req.getParameter("size")) : null;
        //             final String svgDocument = req.getParameter("svg");
        //             if (svgDocument == null)
        //             {
        //                 resp.sendError(HttpServletResponse.SC_BAD_REQUEST, "Missing 'svg' parameter");
        //                 return;
        //             }
        if (StringUtils.isBlank(svg)) {
            throw new Exception("Missing 'svg' parameter");
        }
        final InputStream in = new ByteArrayInputStream(svg.getBytes("UTF-8"));
        final ByteArrayOutputStream out = new ByteArrayOutputStream();
        converter.convert(in, out, size);
        out.flush();
        byte[] doc = out.toByteArray();
        byte[] b = null;
        if (getVersion() != null && !getVersion().contains("EE")) {
            ByteArrayOutputStream baos = new ByteArrayOutputStream();

            PdfReader reader = new PdfReader(doc);
            PdfStamper pdfStamper = new PdfStamper(reader, baos);

            URL dir_url = ExporterResource.class.getResource("/org/saiku/web/svg/watermark.png");
            Image image = Image.getInstance(dir_url);

            for (int i = 1; i <= reader.getNumberOfPages(); i++) {

                PdfContentByte content = pdfStamper.getOverContent(i);

                image.setAbsolutePosition(450f, 280f);
                /*image.setAbsolutePosition(reader.getPageSize(1).getWidth() - image.getScaledWidth(), reader.getPageSize
                   (1).getHeight() - image.getScaledHeight());*/
                //image.setAlignment(Image.MIDDLE);
                content.addImage(image);
            }
            pdfStamper.close();
            b = baos.toByteArray();
        } else {
            b = doc;
        }

        if (!type.equals("pdf")) {

            PDDocument document = PDDocument.load(new ByteArrayInputStream(b), null);

            PDPageTree pdPages = document.getDocumentCatalog().getPages();
            PDPage page = pdPages.get(0);
            BufferedImage o = new PDFRenderer(document).renderImage(0);
            ByteArrayOutputStream imgb = new ByteArrayOutputStream();
            String ct = "";
            String ext = "";
            if (type.equals("png")) {
                ct = "image/png";
                ext = "png";
            } else if (type.equals("jpg")) {
                ct = "image/jpg";
                ext = "jpg";
            }
            ImageIO.write(o, type, imgb);
            byte[] outfile = imgb.toByteArray();
            if (name == null || name.equals("")) {
                name = "chart";
            }
            return Response.ok(outfile).type(ct)
                    .header("content-disposition", "attachment; filename = " + name + "." + ext)
                    .header("content-length", outfile.length).build();
        } else {
            if (name == null || name.equals("")) {
                name = "chart";
            }
            return Response.ok(b).type(converter.getContentType())
                    .header("content-disposition",
                            "attachment; filename = " + name + "." + converter.getExtension())
                    .header("content-length", b.length).build();
        }
    } catch (Exception e) {
        log.error("Error exporting Chart to  " + type, e);
        return Response.serverError().entity(e.getMessage()).status(Status.INTERNAL_SERVER_ERROR).build();
    }
}