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

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

Introduction

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

Prototype

@Override
public void close() throws IOException 

Source Link

Document

This will close the underlying COSDocument object.

Usage

From source file:org.pdfmetamodifier.IOHelper.java

License:Apache License

/**
 * Update Outlines (bookmarks).//from  ww w .j  a  va2 s. c om
 * 
 * @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 Metadata.//from  w w  w.  ja v  a  2 s .c o m
 * 
 * @param pdfFile
 *            Source PDF file.
 * @param metadataFile
 *            File with Metadata in user-frendly format.
 * @throws IOException
 */
/*
 * See:
 *      https://svn.apache.org/viewvc/pdfbox/trunk/examples/src/main/java/org/apache/pdfbox/examples/pdmodel/ExtractMetadata.java?view=markup
 */
public static void saveMetadata(final File pdfFile, final File metadataFile) 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 PDDocumentInformation information = document.getDocumentInformation();

        // Convert.
        final List<String> lines = MetadataHelper.metadataToLineList(information);

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

From source file:org.pdfmetamodifier.IOHelper.java

License:Apache License

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

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

        // Convert.
        final PDDocumentInformation information = MetadataHelper.stringListToMetadata(lines);

        // Set Metadata.
        document.setDocumentInformation(information);

        // 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 w  w  .ja v  a 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   w  w  w  . jav  a 2 s .c o m*/
 * @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./* ww  w  . ja v  a  2  s.  com*/
 * 
 * @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.pensco.CreateStatementsOp.java

License:Open Source License

protected Blob buildPDF(String inCustomer, Calendar inStart, Calendar inEnd)
        throws IOException, COSVisitorException {

    Blob result = null;/*  www  .j a  v  a  2 s. c  om*/

    PDDocument pdfDoc = new PDDocument();
    PDPage page = new PDPage();
    pdfDoc.addPage(page);
    PDRectangle rect = page.getMediaBox();
    float rectH = rect.getHeight();

    PDFont font = PDType1Font.HELVETICA;
    PDFont fontBold = PDType1Font.HELVETICA_BOLD;
    PDFont fontOblique = PDType1Font.HELVETICA_OBLIQUE;
    PDPageContentStream contentStream = new PDPageContentStream(pdfDoc, page);

    int line = 0;

    contentStream.beginText();
    contentStream.setFont(fontOblique, 10);
    contentStream.moveTextPositionByAmount(230, 20);
    contentStream.drawString("(Statement randomly generated)");
    contentStream.endText();

    line += 3;
    contentStream.beginText();
    contentStream.setFont(fontBold, 12);
    contentStream.moveTextPositionByAmount(300, rectH - 20 * (++line));
    contentStream.drawString(inCustomer);
    contentStream.endText();

    contentStream.beginText();
    contentStream.setFont(fontBold, 12);
    contentStream.moveTextPositionByAmount(300, rectH - 20 * (++line));
    contentStream.drawString(
            "Statement from " + yyyyMMdd.format(inStart.getTime()) + " to " + yyyyMMdd.format(inEnd.getTime()));
    contentStream.endText();

    line += 3;
    statementLines = ToolsMisc.randomInt(3, 9);
    boolean isDebit = false;
    for (int i = 1; i <= statementLines; ++i) {
        contentStream.beginText();
        contentStream.setFont(font, 12);
        contentStream.moveTextPositionByAmount(100, rectH - 20 * line);
        contentStream.drawString("" + i);
        contentStream.endText();

        contentStream.beginText();
        contentStream.setFont(font, 12);
        contentStream.moveTextPositionByAmount(120, rectH - 20 * line);
        isDebit = ToolsMisc.randomInt(0, 10) > 7;
        if (isDebit) {
            contentStream.drawString("Withdraw Funds to account " + MiscUtils.getSomeUID(6));
        } else {
            contentStream.drawString("Add Funds to account " + MiscUtils.getSomeUID(6));
        }
        contentStream.endText();

        contentStream.beginText();
        if (isDebit) {
            contentStream.setFont(fontOblique, 12);
            contentStream.moveTextPositionByAmount(350, rectH - 20 * line);
        } else {
            contentStream.setFont(font, 12);
            contentStream.moveTextPositionByAmount(450, rectH - 20 * line);
        }
        contentStream.drawString("" + ToolsMisc.randomInt(1000, 9000) + "." + ToolsMisc.randomInt(10, 90));
        contentStream.endText();

        line += 1;
    }
    contentStream.close();
    contentStream = null;

    if (logoImage != null) {
        PDXObjectImage ximage = new PDPixelMap(pdfDoc, logoImage);

        contentStream = new PDPageContentStream(pdfDoc, page, true, true);
        contentStream.endMarkedContentSequence();
        contentStream.drawXObject(ximage, 10, rectH - 20 - ximage.getHeight(), ximage.getWidth(),
                ximage.getHeight());
        contentStream.close();
        contentStream = null;
    }

    result = MiscUtils.saveInTempFile(pdfDoc);
    pdfDoc.close();

    return result;

}

From source file:org.primaresearch.pdf.PageToPdfConverterUsingPdfBox.java

License:Apache License

public void convert(Collection<Page> pages, String targetPdf) {
    try {//from   w  ww. j a v a2  s . co m
        // Create a new empty document
        PDDocument document = new PDDocument();

        //Metadata (use first page)
        if (pages.size() > 0)
            addMetadata(document, pages.iterator().next());

        //Font
        createFont(document);

        //Add pages
        for (Iterator<Page> it = pages.iterator(); it.hasNext();)
            addPage(document, it.next());

        // Save the newly created document
        document.save(targetPdf);

        // finally make sure that the document is properly
        // closed.
        document.close();
    } catch (Exception exc) {
        exc.printStackTrace();
    }
}

From source file:org.primaresearch.pdf.PageToPdfConverterUsingPdfBox.java

License:Apache License

public void convert(Page page, String targetPdf) {
    try {//ww  w.  jav a  2s. com
        // Create a new empty document
        PDDocument document = new PDDocument();

        //Metadata
        addMetadata(document, page);

        //Font
        createFont(document);

        //Add page
        addPage(document, page);

        // Save the newly created document
        document.save(targetPdf);

        // finally make sure that the document is properly
        // closed.
        document.close();

    } catch (Exception exc) {
        exc.printStackTrace();
    }
}

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);
    /*/*  w  ww .  ja v a 2s.c  om*/
    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;
}