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.spotter.eclipse.ui.viewers.ResourceViewer.java

License:Apache License

private ImageData createImageDataFromPdf(String resourceFile) {
    try {//from w  ww  .j a v a  2 s  .  co  m
        PDDocument document = PDDocument.load(resourceFile);
        @SuppressWarnings("unchecked")
        List<PDPage> pages = document.getDocumentCatalog().getAllPages();
        if (pages.isEmpty()) {
            throw new SWTException(SWT.ERROR_INVALID_IMAGE);
        }
        BufferedImage bufferedImage = pages.get(0).convertToImage(PDF_IMAGE_TYPE, PDF_VIEW_RESOLUTION);
        return ImageUtils.convertToImageData(bufferedImage);
    } catch (IOException e) {
        throw new SWTException(SWT.ERROR_IO);
    }
}

From source file:org.swiftexplorer.gui.preview.PdfPanel.java

License:Apache License

public synchronized void setPdf(PDDocument pdf) {
    listImagePages.clear();//from   ww  w.j  a  v  a 2s. c om
    if (pdf == null)
        return;
    try {
        if (pdf.isEncrypted()) {
            logger.info("Failed attempt at previewing an encrypted PDF");
            return;
        }
        PDDocumentCatalog cat = pdf.getDocumentCatalog();
        @SuppressWarnings("unchecked")
        List<PDPage> pages = cat.getAllPages();
        if (pages != null && !pages.isEmpty()) {
            for (PDPage page : pages) {
                listImagePages.add(page.convertToImage());
                if (listImagePages.size() >= maxPageToPreview)
                    break;
            }
        }
    } catch (IOException e) {
        logger.error("Error occurred while opening the pdf document", e);
    } finally {
        if (pdf != null) {
            try {
                pdf.close();
            } catch (IOException ex) {
                logger.error("Error occurred while closing the pdf document", ex);
            }
        }
    }
    repaint();
}

From source file:org.tnc.doctrack.behaviours.docTrackBehaviours.java

License:Open Source License

private Result[] extractQRfromPDF(InputStream PDF) throws Exception {
    System.out.println("TNC - DocTrack  - extractQRfromPDF starting....");
    //Initialize variable for QR decoding.

    PDDocument document = null;
    String password = "";
    String prefix = null;/* w w w  . j  a v a  2 s  .c o  m*/
    boolean addKey = false;
    Result[] QR = null;
    try {
        //read PDF document 
        document = PDDocument.loadNonSeq(PDF, null, password);
        //Check permission to PDF
        AccessPermission ap = document.getCurrentAccessPermission();
        if (!ap.canExtractContent()) {
            System.out.println(
                    "TNC - DocTrack  Error - extractQRfromPDF - You do not have permission to extract images from PDF.");
            throw new IOException(
                    "TNC - DocTrack  Error - extractQRfromPDF - You do not have permission to extract images from PDF.");
        }
        //Iterate throw the PDF pages. 
        List<?> pages = document.getDocumentCatalog().getAllPages();
        Iterator<?> iter = pages.iterator();
        while (iter.hasNext()) {
            PDPage page = (PDPage) iter.next();
            PDResources resources = page.getResources();
            // extract all XObjectImages which are part of the page resources
            System.out.println("TNC - DocTrack  - extractQRfromPDF - Try to process image and find QR code");
            QR = processResources(resources, prefix, addKey);
        }

    } finally {
        if ((document != null)) {
            try {
                document.close();
            } catch (Exception e) {

            }

        }
    }
    System.out.println("TNC - DocTrack  - extractQRfromPDF finished. QR code string : " + QR);
    return QR;
}

From source file:org.wangwei.pdf.AddImageToPDF.java

License:Apache License

/**
 * Add an image to an existing PDF document.
 *
 * @param inputFile The input PDF to add the image to.
 * @param image The filename of the image to put in the PDF.
 * @param outputFile The file to write to the pdf to.
 * @throws IOException If there is an error writing the data.
 * @throws COSVisitorException If there is an error writing the PDF.
 *//*ww  w.j av  a  2 s . c  o m*/
public void createPDFFromImage(String inputFile, String image, String outputFile)
        throws IOException, COSVisitorException {
    // the document
    PDDocument doc = null;
    try {
        doc = PDDocument.load(inputFile);

        // we will add the image to the first page.
        PDPage page = (PDPage) doc.getDocumentCatalog().getAllPages().get(0);

        PDXObjectImage ximage = null;
        if (image.toLowerCase().endsWith(".jpg")) {
            ximage = new PDJpeg(doc, new FileInputStream(image));
        } else if (image.toLowerCase().endsWith(".tif") || image.toLowerCase().endsWith(".tiff")) {
            ximage = new PDCcitt(doc, new RandomAccessFile(new File(image), "r"));
        } else {
            BufferedImage awtImage = ImageIO.read(new File(image));
            ximage = new PDPixelMap(doc, awtImage);
        }
        PDPageContentStream contentStream = new PDPageContentStream(doc, page, true, true);

        // contentStream.drawImage(ximage, 20, 20 );
        // better method inspired by http://stackoverflow.com/a/22318681/535646
        float scale = 1f; // reduce this value if the image is too large
        contentStream.drawXObject(ximage, 20, 20, ximage.getWidth() * scale, ximage.getHeight() * scale);

        contentStream.close();
        doc.save(outputFile);
    } finally {
        if (doc != null) {
            doc.close();
        }
    }
}

From source file:org.xcmis.renditions.impl.PDFDocumentRenditionProvider.java

License:Open Source License

/**
 * {@inheritDoc}//from w ww. j  ava  2 s.  c o  m
 */
public RenditionContentStream getRenditionStream(ContentStream stream) throws IOException {
    PDDocument pdf = null;
    try {
        pdf = PDDocument.load(stream.getStream());
        PDPage page = (PDPage) pdf.getDocumentCatalog().getAllPages().get(0);
        BufferedImage image = page.convertToImage();
        // Determine scale and be sure both width and height are not greater the max
        int scale = (int) Math.max(Math.floor((image.getHeight() / maxHeight) + 1.0d),
                Math.floor((image.getWidth() / maxWidth) + 1.0d));
        int height = image.getHeight() / scale;
        int width = image.getWidth() / scale;
        BufferedImage scaledImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        Graphics2D graphics2D = scaledImage.createGraphics();
        graphics2D.setRenderingHint(RenderingHints.KEY_INTERPOLATION,
                RenderingHints.VALUE_INTERPOLATION_BILINEAR);
        graphics2D.drawImage(image, 0, 0, width, height, null);
        graphics2D.dispose();

        ByteArrayOutputStream out = new ByteArrayOutputStream();
        ImageIO.write(scaledImage, "png", out);
        RenditionContentStream renditionStream = new RenditionContentStream(out.toByteArray(), null,
                new MimeType("image", " png"), getKind(), height, width);
        return renditionStream;
    } finally {
        if (pdf != null) {
            pdf.close();
        }
    }
}

From source file:org.xstudiosys.pdfxmp.AddMetadataFromDocInfo.java

License:Apache License

/**
 * This will print the documents data.// w w w  .j a  v  a2s  .c o m
 *
 * @param args The command line arguments.
 *
 * @throws Exception If there is an error parsing the document.
 */
public static void main(String[] args) throws Exception {
    if (args.length != 2) {
        usage();
    } else {
        PDDocument document = null;

        try {
            document = PDDocument.load(args[0]);
            if (document.isEncrypted()) {
                System.err.println("Error: Cannot add metadata to encrypted document.");
                System.exit(1);
            }
            PDDocumentCatalog catalog = document.getDocumentCatalog();
            PDDocumentInformation info = document.getDocumentInformation();

            XMPMetadata metadata = new XMPMetadata();

            XMPSchemaPDF pdfSchema = metadata.addPDFSchema();
            pdfSchema.setKeywords(info.getKeywords());
            pdfSchema.setProducer(info.getProducer());

            XMPSchemaBasic basicSchema = metadata.addBasicSchema();
            basicSchema.setModifyDate(info.getModificationDate());
            basicSchema.setCreateDate(info.getCreationDate());
            basicSchema.setCreatorTool(info.getCreator());
            basicSchema.setMetadataDate(new GregorianCalendar());

            XMPSchemaDublinCore dcSchema = metadata.addDublinCoreSchema();
            dcSchema.setTitle(info.getTitle());
            dcSchema.addCreator("PDFBox");
            dcSchema.setDescription(info.getSubject());

            PDMetadata metadataStream = new PDMetadata(document);
            metadataStream.importXMPMetadata(metadata);
            catalog.setMetadata(metadataStream);

            document.save(args[1]);
        } finally {
            if (document != null) {
                document.close();
            }
        }
    }
}

From source file:org.xstudiosys.pdfxmp.MarkBuilder.java

License:Open Source License

public void onComplete(PDDocument document) {
    try {/*from   w  w w .  java2  s . co  m*/

        PDDocumentCatalog catalog = document.getDocumentCatalog();
        PDDocumentInformation info = document.getDocumentInformation();

        XMPMetadata metadata = new XMPMetadata();

        XMPSchemaPDF pdfSchema = metadata.addPDFSchema();
        pdfSchema.setKeywords(info.getKeywords());
        pdfSchema.setProducer(info.getProducer());

        XMPSchemaBasic basicSchema = metadata.addBasicSchema();
        basicSchema.setModifyDate(info.getModificationDate());
        basicSchema.setCreateDate(info.getCreationDate());
        basicSchema.setCreatorTool(info.getCreator());
        basicSchema.setMetadataDate(new GregorianCalendar());

        XMPSchemaDublinCore dcSchema = metadata.addDublinCoreSchema();
        dcSchema.setTitle(info.getTitle());
        dcSchema.addCreator("PDFBox");
        dcSchema.setDescription(info.getSubject());

        PDMetadata metadataStream = new PDMetadata(document);
        metadataStream.importXMPMetadata(metadata);
        catalog.setMetadata(metadataStream);
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:org.xstudiosys.pdfxmp.XMPUtil.java

License:Open Source License

static XMPMetadata getXMPMetadata(PDDocument document) throws IOException {
    PDDocumentCatalog catalog = document.getDocumentCatalog();
    PDMetadata metaRaw = catalog.getMetadata();

    if (metaRaw == null) {
        return null;
    }// w ww. j  av  a 2  s .  c o  m

    XMPMetadata meta = new XMPMetadata(XMLUtil.parse(metaRaw.createInputStream()));
    meta.addXMLNSMapping(XMPSchemaBibtex.NAMESPACE, XMPSchemaBibtex.class);
    return meta;
}

From source file:org.xstudiosys.pdfxmp.XMPUtil.java

License:Open Source License

/**
 * Try to write the given BibTexEntries as DublinCore XMP Schemas
 * //  w  ww .  j  av a  2 s. co m
 * Existing DublinCore schemas in the document are removed
 * 
 * @param document
 *            The pdf document to write to.
 * @param entries
 *            The Bibtex entries that are written as schemas
 * @param database
 *            maybenull An optional database which the given bibtex entries
 *            belong to, which will be used to resolve strings. If the
 *            database is null the strings will not be resolved.
 * @throws IOException
 * @throws TransformerException
 */
@SuppressWarnings("unchecked")
public static void writeDublinCore(PDDocument document, Collection<BibtexEntry> entries,
        BibtexDatabase database) throws IOException, TransformerException {

    if (database != null)
        entries = database.resolveForStrings(entries, false);

    PDDocumentCatalog catalog = document.getDocumentCatalog();
    PDMetadata metaRaw = catalog.getMetadata();

    XMPMetadata meta;
    if (metaRaw != null) {
        meta = new XMPMetadata(XMLUtil.parse(metaRaw.createInputStream()));
    } else {
        meta = new XMPMetadata();
    }

    // Remove all current Dublin-Core schemas
    List<XMPSchema> schemas = meta.getSchemasByNamespaceURI(XMPSchemaDublinCore.NAMESPACE);
    for (XMPSchema schema : schemas) {
        schema.getElement().getParentNode().removeChild(schema.getElement());
    }

    for (BibtexEntry entry : entries) {
        XMPSchemaDublinCore dcSchema = new XMPSchemaDublinCore(meta);
        writeToDCSchema(dcSchema, entry, null);
        meta.addSchema(dcSchema);
    }

    // Save to stream and then input that stream to the PDF
    ByteArrayOutputStream os = new ByteArrayOutputStream();
    meta.save(os);
    ByteArrayInputStream is = new ByteArrayInputStream(os.toByteArray());
    PDMetadata metadataStream = new PDMetadata(document, is, false);
    catalog.setMetadata(metadataStream);
}

From source file:org.xstudiosys.pdfxmp.XMPUtil.java

License:Open Source License

/**
 * Try to write the given BibTexEntry in the XMP-stream of the given
 * PDF-file.//  w  w w . ja v a2s.  co m
 * 
 * Throws an IOException if the file cannot be read or written, so the user
 * can remove a lock or cancel the operation.
 * 
 * The method will overwrite existing BibTeX-XMP-data, but keep other
 * existing metadata.
 * 
 * @param file
 *            The file to write the entries to.
 * @param bibtexEntries
 *            The entries to write to the file. *
 * @param database
 *            maybenull An optional database which the given bibtex entries
 *            belong to, which will be used to resolve strings. If the
 *            database is null the strings will not be resolved.
 * @param writePDFInfo
 *            Write information also in PDF document properties
 * @throws TransformerException
 *             If the entry was malformed or unsupported.
 * @throws IOException
 *             If the file could not be written to or could not be found.
 */
@SuppressWarnings("unchecked")
public static void writeXMP(File file, Collection<BibtexEntry> bibtexEntries, BibtexDatabase database,
        boolean writePDFInfo) throws IOException, TransformerException {

    if (database != null)
        bibtexEntries = database.resolveForStrings(bibtexEntries, false);

    PDDocument document = null;

    try {
        document = PDDocument.load(file.getAbsoluteFile());
        if (document.isEncrypted()) {
            throw new EncryptionNotSupportedException("Error: Cannot add metadata to encrypted document.");
        }

        if (writePDFInfo && bibtexEntries.size() == 1) {
            writeDocumentInformation(document, bibtexEntries.iterator().next(), null);
            writeDublinCore(document, bibtexEntries, null);
        }

        PDDocumentCatalog catalog = document.getDocumentCatalog();
        PDMetadata metaRaw = catalog.getMetadata();

        XMPMetadata meta;
        if (metaRaw != null) {
            meta = new XMPMetadata(XMLUtil.parse(metaRaw.createInputStream()));
        } else {
            meta = new XMPMetadata();
        }
        meta.addXMLNSMapping(XMPSchemaBibtex.NAMESPACE, XMPSchemaBibtex.class);

        // Remove all current Bibtex-schemas
        List<XMPSchema> schemas = meta.getSchemasByNamespaceURI(XMPSchemaBibtex.NAMESPACE);
        for (XMPSchema schema : schemas) {
            XMPSchemaBibtex bib = (XMPSchemaBibtex) schema;
            bib.getElement().getParentNode().removeChild(bib.getElement());
        }

        for (BibtexEntry e : bibtexEntries) {
            XMPSchemaBibtex bibtex = new XMPSchemaBibtex(meta);
            meta.addSchema(bibtex);
            bibtex.setBibtexEntry(e, null);
        }

        // Save to stream and then input that stream to the PDF
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        meta.save(os);
        ByteArrayInputStream is = new ByteArrayInputStream(os.toByteArray());
        PDMetadata metadataStream = new PDMetadata(document, is, false);
        catalog.setMetadata(metadataStream);

        // Save
        try {
            document.save(file.getAbsolutePath());
        } catch (COSVisitorException e) {
            throw new TransformerException("Could not write XMP-metadata: " + e.getLocalizedMessage());
        }

    } finally {
        if (document != null) {
            document.close();
        }
    }
}