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.xstudiosys.pdfxmp.XMPUtil.java

License:Open Source License

/**
 * Will read the XMPMetadata from the given pdf file, closing the file
 * afterwards.//from w ww  . j a v  a 2s . com
 * 
 * @param inputStream
 *            The inputStream representing a PDF-file to read the
 *            XMPMetadata from.
 * @return The XMPMetadata object found in the file or null if none is
 *         found.
 * @throws IOException
 */
public static XMPMetadata readRawXMP(InputStream inputStream) throws IOException {
    PDDocument document = null;

    try {
        document = PDDocument.load(inputStream);
        if (document.isEncrypted()) {
            throw new EncryptionNotSupportedException("Error: Cannot read metadata from encrypted document.");
        }

        return getXMPMetadata(document);

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

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./*from w ww .  jav  a  2s . c  o  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();
        }
    }
}

From source file:org.xwiki.test.misc.PDFTest.java

License:Open Source License

private String getPDFContent(URL url) throws Exception {
    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
    InputStream is = connection.getInputStream();
    PDDocument pdd = PDDocument.load(is);
    String text;/*from   ww  w.  java  2 s.  c om*/
    try {
        PDFText2HTML stripper = new PDFText2HTML();
        text = stripper.getText(pdd);
    } finally {
        if (pdd != null) {
            pdd.close();
        }
        if (is != null) {
            is.close();
        }
    }
    return text;
}

From source file:org.xwiki.test.misc.PDFTest.java

License:Open Source License

private Map<String, PDImageXObject> getImages(URL url) throws Exception {
    Map<String, PDImageXObject> results = new HashMap<>();

    PDDocument document = PDDocument.load(IOUtils.toByteArray(url));
    try {//from   w  w  w. java  2s . c o  m
        for (PDPage page : document.getDocumentCatalog().getPages()) {
            PDResources pdResources = page.getResources();
            for (COSName name : pdResources.getXObjectNames()) {
                if (pdResources.isImageXObject(name)) {
                    PDImageXObject pdxObjectImage = (PDImageXObject) pdResources.getXObject(name);
                    results.put(name.getName(), pdxObjectImage);
                }
            }
        }
    } finally {
        if (document != null) {
            document.close();
        }
    }

    return results;
}

From source file:org.xwiki.test.misc.PDFTest.java

License:Open Source License

private Map<String, String> extractURLs(URL url) throws Exception {
    Map<String, String> urls = new HashMap<String, String>();
    PDDocument document = null;
    try {/*from w  ww. j av  a2 s .  co m*/
        document = PDDocument.load(IOUtils.toByteArray(url));
        for (Map.Entry<String, PDAction> entry : extractLinks(document).entrySet()) {
            if (entry.getValue() instanceof PDActionURI) {
                PDActionURI uri = (PDActionURI) entry.getValue();
                urls.put(entry.getKey(), uri.getURI());
            }
        }
    } finally {
        if (document != null) {
            document.close();
        }
    }
    return urls;
}

From source file:org.xwiki.test.misc.PDFTest.java

License:Open Source License

private Map<String, String> extractToLinks(URL url, int tocPageIndex) throws Exception {
    Map<String, String> internalLinks = new HashMap<String, String>();
    PDDocument document = null;
    try {//from ww w.ja  v  a2 s  .c o  m
        document = PDDocument.load(IOUtils.toByteArray(url));
        PDPage tocPage = document.getDocumentCatalog().getPages().get(tocPageIndex);
        for (Map.Entry<String, PDAction> entry : extractLinks(tocPage).entrySet()) {
            if (entry.getValue() instanceof PDActionGoTo) {
                PDActionGoTo anchor = (PDActionGoTo) entry.getValue();
                internalLinks.put(entry.getKey(), getDestinationText(anchor.getDestination()));
            }
        }
    } finally {
        if (document != null) {
            document.close();
        }
    }
    return internalLinks;
}

From source file:patient_records_mng_sys.balamu.java

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed

    String latta = "Lotta";
    System.out.println("Dagakara" + latta + " Balla");
    // String var="Testing";
    // jLabel1.setText("HelloMto! "+var+"");
    String bloody = "1227";
    try {//w  ww . j  a v  a  2  s.c om

        System.out.println("Create Simple PDF file with Text");
        String fileName = "patientReport.pdf"; // name of our file

        PDDocument doc = new PDDocument();
        PDPage page = new PDPage();

        doc.addPage(page);

        PDPageContentStream content = new PDPageContentStream(doc, page);

        content.beginText();
        content.setFont(PDType1Font.HELVETICA, 20);
        content.moveTextPositionByAmount(220, 750);
        content.drawString("Patient Report Form");
        content.endText();

        int x = 80;
        int y = 700;
        String spac = "        ";
        String documen = "PatientID" + spac + "PatientName" + spac + "Clinic" + spac + "Diagnose";

        content.beginText();
        content.setFont(PDType1Font.HELVETICA, 16);
        content.moveTextPositionByAmount(x, 710);
        content.drawString(documen);
        content.endText();

        //To add from database//
        Connection conn = null;
        try {
            Class.forName("com.mysql.jdbc.Driver");
            conn = DriverManager.getConnection("jdbc:mysql://localhost/itp?" + "user=root&password=sparksndl");
            Statement sqlState = conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,
                    ResultSet.CONCUR_UPDATABLE);
            String selectStuff = "Select `ID`,`patient_id`,`clinicName`,`diagnosis`,`dateOfEntry`,`allergiesIdentified`,`Remarks`,`nextClinicDate`,`ward` FROM `medical_records` WHERE `patient_id` LIKE "
                    + bloody + " ";
            rows = sqlState.executeQuery(selectStuff);
            Object[] tempRow;
            String[] records;
            while (rows.next()) {
                //tempRow=new Object[]{rows.getString(1),rows.getString(2),rows.getString(3),rows.getString(4),rows.getDate(5),rows.getString(6),rows.getString(7),rows.getString(8)};
                //dTableModel.addRow(tempRow);
                String id = rows.getString(1);
                String name = "Classified";
                String clinic = rows.getString(3);
                String diagnose = rows.getString(4);
                String aller = rows.getString(6);
                String remark = rows.getString(7);
                String space = "                 ";
                String document = id + space + space + space + name + space + space + clinic + space + diagnose;
                content.beginText();
                content.setFont(PDType1Font.HELVETICA, 8);
                content.moveTextPositionByAmount(x, y);
                content.drawString(document);

                content.endText();
                y = y - 12;

            }

        } catch (ClassNotFoundException | SQLException e) {
            e.printStackTrace();
        }

        //Over//

        content.close();
        doc.save(fileName);
        doc.close();

        System.out.println("your file created in : " + System.getProperty("user.dir"));

    } catch (IOException | COSVisitorException e) {

        System.out.println(e.getMessage());

    }

    // TODO add your handling code here:
}

From source file:patient_records_mng_sys.send.java

private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton3ActionPerformed

    String email1 = email.getText();

    String EMAIL_REGEX = "^[\\w-_\\.+]*[\\w-_\\.]\\@([\\w]+\\.)+[\\w]+[\\w]$";

    Boolean b = email1.matches(EMAIL_REGEX);

    if (b == true) {

        System.out.println("Correct Email");
        // String bloody=(String)search_key.getSelectedItem();
        //this.test();
        //Create the PDF Document//

        try {/*  w  w  w  . ja  v  a 2 s . c  o m*/
            String key = (String) search_key.getSelectedItem();
            System.out.println("Creating PDF File");
            String fileName = "patientReport.pdf"; // name of our file

            PDDocument doc = new PDDocument();
            PDPage page = new PDPage();

            doc.addPage(page);

            PDPageContentStream content = new PDPageContentStream(doc, page);

            content.beginText();
            content.setFont(PDType1Font.HELVETICA, 20);
            content.moveTextPositionByAmount(220, 750);
            content.drawString("Patient Report Form");
            content.endText();

            int x = 80;
            int y = 700;
            String spac = "        ";
            String documen = "PatientID" + spac + "PatientName" + spac + "Clinic" + spac + "Diagnose";

            content.beginText();
            content.setFont(PDType1Font.HELVETICA, 16);
            content.moveTextPositionByAmount(x, 710);
            content.drawString(documen);
            content.endText();

            //To add from database//
            // Connection conn=null;
            try {
                Class.forName("com.mysql.jdbc.Driver");
                ///conn = DriverManager.getConnection("jdbc:mysql://localhost/itp?"+"user=root&password=sparksndl");
                //conn = DriverManager.getConnection("jdbc:mysql://localhost/itp?"+"user="+user+"&password="+pass+"");
                Statement sqlState = conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,
                        ResultSet.CONCUR_UPDATABLE);
                String selectStuff = "Select `ID`,`patient_id`,`clinicName`,`diagnosis`,`dateOfEntry`,`allergiesIdentified`,`Remarks`,`nextClinicDate`,`ward` FROM `medical_records` WHERE `patient_id` LIKE "
                        + key + " ";
                rows = sqlState.executeQuery(selectStuff);
                Object[] tempRow;
                String[] records;
                if (rows.next()) {
                    while (rows.next()) {
                        String id = rows.getString(1);
                        String name = "Classified";
                        String clinic = rows.getString(3);
                        String diagnose = rows.getString(4);
                        String aller = rows.getString(6);
                        String remark = rows.getString(7);
                        String space = "                 ";
                        String document = id + space + space + space + name + space + space + clinic + space
                                + diagnose;
                        content.beginText();
                        content.setFont(PDType1Font.HELVETICA, 8);
                        content.moveTextPositionByAmount(x, y);
                        content.drawString(document);

                        content.endText();
                        y = y - 12;
                    }
                } else {
                    JOptionPane.showMessageDialog(null,
                            "ID entry not available,Please register the patient or try again");
                }

            } catch (ClassNotFoundException | SQLException e) {
                System.out.println("Provide Correct Index");
                //e.printStackTrace();
            }

            //Document Creation Over//

            content.close();
            doc.save(fileName);
            doc.close();

            System.out.println("your report has been created in : " + System.getProperty("user.dir"));

        } catch (IOException | COSVisitorException e) {

            System.out.println(e.getMessage());

        }
        // String test="jsandunil@gmail.com";
        emailer mailme = new emailer();
        mailme.sendFromGMail(email1);

        //mailme.
        //Document Over//

    } else

        JOptionPane.showMessageDialog(null, "Incorrect Email Provided.", "Email Address Format",
                JOptionPane.ERROR_MESSAGE);

    // TODO add your handling code here:
}

From source file:pdf.DailyReportPDF.java

public void createDailyReportPNG(String path) throws IOException {
    File file = new File(path);
    PDDocument doc = PDDocument.load(file);
    PDFRenderer renderer = new PDFRenderer(doc);
    BufferedImage image = renderer.renderImage(0);
    SimpleDateFormat sdf = new SimpleDateFormat("dd.MM.yyyy.");
    ImageIO.write(image, "PNG",
            new File("pdf_docs\\daily_reports_picture\\" + "drpic-" + sdf.format(dateOfDailyReport) + ".png"));
    doc.close();
}

From source file:pdf.DailyReportPDF.java

public String createDailyReport() throws IOException {
    PDDocument document = PDDocument.load(template);
    //prva strana
    PDPage page = document.getPage(0);/*from w w w  .j  a v  a 2 s.  c o  m*/
    contentStream = new PDPageContentStream(document, page, PDPageContentStream.AppendMode.PREPEND, false);

    this.insertProducts();
    this.dailyReportInfo();
    contentStream.close();
    SimpleDateFormat sdf = new SimpleDateFormat("dd.MM.yyyy.");
    String path = "pdf_docs\\daily_reports\\" + "daily_report_" + dateOfDailyReport.getTime() + ".pdf";
    document.save(path);
    //createDailyReportPNG(path);
    document.close();

    return path;
}