Example usage for com.lowagie.text.pdf PdfWriter createXmpMetadata

List of usage examples for com.lowagie.text.pdf PdfWriter createXmpMetadata

Introduction

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

Prototype

public void createXmpMetadata() 

Source Link

Document

Use this method to creates XMP Metadata based on the metadata in the PdfDocument.

Usage

From source file:be.fedict.eid.applet.service.impl.PdfGenerator.java

License:Open Source License

public byte[] generatePdf(EIdData eIdData) throws DocumentException {
    Document document = new Document();
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    PdfWriter writer = PdfWriter.getInstance(document, baos);

    document.open();/* ww w .j ava 2  s  .c  om*/

    Paragraph titleParagraph = new Paragraph("eID Identity Data");
    titleParagraph.setAlignment(Paragraph.ALIGN_CENTER);

    Font titleFont = titleParagraph.getFont();
    titleFont.setSize((float) 20.0);
    titleFont.setStyle(Font.BOLD);
    titleParagraph.setSpacingAfter(20);
    document.add(titleParagraph);

    if (null != eIdData && null != eIdData.getIdentity()) {
        if (null != eIdData.getPhoto()) {
            try {
                Image image = createImageFromPhoto(eIdData.getPhoto());
                document.add(image);
            } catch (Exception e) {
                LOG.error("Error getting photo: " + e.getMessage());
            }

            Identity identity = eIdData.getIdentity();

            // metadata
            setDocumentMetadata(document, identity.firstName, identity.name);
            writer.createXmpMetadata();

            // create a table with the data of the eID card
            PdfPTable table = new PdfPTable(2);
            table.getDefaultCell().setBorder(0);

            table.addCell("Name");
            table.addCell(identity.name);

            table.addCell("First name");
            String firstName = identity.firstName;
            if (null != identity.middleName) {
                firstName += " " + identity.middleName;
            }
            table.addCell(firstName);

            table.addCell("Nationality");
            table.addCell(identity.nationality);

            table.addCell("National Registration Number");
            table.addCell(identity.nationalNumber);

            table.addCell("Gender");
            table.addCell(identity.gender.toString());

            table.addCell("Date of birth");
            SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy");
            table.addCell(formatter.format(identity.dateOfBirth.getTime()));

            table.addCell("Place of birth");
            table.addCell(identity.placeOfBirth);

            if (null != eIdData.getAddress()) {
                Address address = eIdData.getAddress();
                table.addCell("Address");
                PdfPCell cell = new PdfPCell();
                cell.setBorder(0);
                cell.addElement(new Paragraph(address.streetAndNumber));
                cell.addElement(new Paragraph(address.zip + " " + address.municipality));
                table.addCell(cell);
            }

            document.add(table);

            // TODO: to be tested
            /*
            try {
                Image barcodeImage =
                    createBarcodeImage(identity.nationalNumber, identity.cardNumber);
                    
                barcodeImage.setAlignment(Element.ALIGN_CENTER);
                Paragraph barcodePara = new Paragraph();
                barcodePara.add(barcodeImage);
                    
                document.add(barcodeImage);
            } catch (Exception e) {
                LOG.error("Error adding barcode: " + e.getMessage());
            }
            */
        } else {
            document.add(new Paragraph("No eID identity data available."));
        }
    }
    document.close();
    return baos.toByteArray();
}

From source file:com.qcadoo.plugins.qcadooExport.internal.ExportToPDFController.java

License:Open Source License

@Monitorable(threshold = 500)
@ResponseBody//from w  w  w . jav a2  s.  c  om
@RequestMapping(value = { CONTROLLER_PATH }, method = RequestMethod.POST)
public Object generatePdf(@PathVariable(PLUGIN_IDENTIFIER_VARIABLE) final String pluginIdentifier,
        @PathVariable(VIEW_NAME_VARIABLE) final String viewName, @RequestBody final JSONObject body,
        final Locale locale) {
    try {
        changeMaxResults(body);
        ViewDefinitionState state = crudService.invokeEvent(pluginIdentifier, viewName, body, locale);
        GridComponent grid = (GridComponent) state.getComponentByReference("grid");
        Document document = new Document(PageSize.A4.rotate());
        String date = DateFormat.getDateInstance().format(new Date());
        File file = fileService.createExportFile("export_" + grid.getName() + "_" + date + ".pdf");
        FileOutputStream fileOutputStream = new FileOutputStream(file);
        PdfWriter writer = PdfWriter.getInstance(document, fileOutputStream);

        writer.setPageEvent(new PdfPageNumbering(footerResolver.resolveFooter(locale)));

        document.setMargins(40, 40, 60, 60);

        document.addTitle("export.pdf");
        pdfHelper.addMetaData(document);
        writer.createXmpMetadata();
        document.open();

        String title = translationService.translate(
                pluginIdentifier + "." + viewName + ".window.mainTab." + grid.getName() + ".header", locale);

        Date generationDate = new Date();

        pdfHelper.addDocumentHeader(document, "", title,
                translationService.translate("qcadooReport.commons.generatedBy.label", locale), generationDate);

        int columns = 0;
        List<String> exportToPDFTableHeader = new ArrayList<String>();
        for (String name : grid.getColumnNames().values()) {
            exportToPDFTableHeader.add(name);
            columns++;
        }
        PdfPTable table = pdfHelper.createTableWithHeader(columns, exportToPDFTableHeader, false);

        List<Map<String, String>> rows;
        if (grid.getSelectedEntitiesIds().isEmpty()) {
            rows = grid.getColumnValuesOfAllRecords();
        } else {
            rows = grid.getColumnValuesOfSelectedRecords();
        }

        for (Map<String, String> row : rows) {
            for (String value : row.values()) {
                table.addCell(new Phrase(value, FontUtils.getDejavuRegular7Dark()));
            }
        }
        document.add(table);
        document.close();

        state.redirectTo(fileService.getUrl(file.getAbsolutePath()) + "?clean", true, false);
        return crudService.renderView(state);
    } catch (JSONException e) {
        throw new IllegalStateException(e.getMessage(), e);
    } catch (FileNotFoundException e) {
        throw new IllegalStateException(e.getMessage(), e);
    } catch (DocumentException e) {
        throw new IllegalStateException(e.getMessage(), e);
    }
}

From source file:com.qcadoo.report.api.pdf.PdfDocumentService.java

License:Open Source License

private void generate(final Entity entity, final Locale locale, final String filename, final Rectangle pageSize)
        throws IOException, DocumentException {
    Document document = new Document(pageSize);
    try {/*from w  ww.j  a v  a2  s  .  co  m*/
        FileOutputStream fileOutputStream = new FileOutputStream(
                fileService.createReportFile(filename + "." + ReportService.ReportType.PDF.getExtension()));
        PdfWriter writer = PdfWriter.getInstance(document, fileOutputStream);
        writer.setPageEvent(new PdfPageNumbering(footerResolver.resolveFooter(locale)));
        document.setMargins(40, 40, 60, 60);
        buildPdfMetadata(document, locale);
        writer.createXmpMetadata();
        document.open();
        buildPdfContent(document, entity, locale);
        document.close();
    } catch (DocumentException e) {
        LOG.error("Problem with generating document - " + e.getMessage());
        document.close();
        throw e;
    }
}

From source file:com.qcadoo.report.api.pdf.PdfDocumentWithWriterService.java

License:Open Source License

private void generate(final Entity entity, final Locale locale, final String filename, final Rectangle pageSize)
        throws IOException, DocumentException {
    Document document = new Document(pageSize);
    try {/* w w  w  . j ava2  s  .  c om*/
        FileOutputStream fileOutputStream = new FileOutputStream(
                fileService.createReportFile(filename + "." + ReportService.ReportType.PDF.getExtension()));
        PdfWriter writer = PdfWriter.getInstance(document, fileOutputStream);
        writer.setPageEvent(new PdfPageNumbering(footerResolver.resolveFooter(locale)));
        document.setMargins(40, 40, 60, 60);
        buildPdfMetadata(document, locale);
        writer.createXmpMetadata();
        document.open();
        buildPdfContent(writer, document, entity, locale);
        document.close();
    } catch (DocumentException e) {
        LOG.error("Problem with generating document - " + e.getMessage());
        document.close();
        throw e;
    }
}

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

License:Apache License

/***************************************************************************
 * Creates a PDF, which is streams to the OutputStream out.
 * /*w w w.j  a  v  a 2  s. co m*/
 * @param out {@link OutputStream}
 * @param pagesizemode {@link PdfPageSize}
 * 
 * 
 * @throws IOException Signals that an I/O exception has occurred.
 * @throws FileNotFoundException the file not found exception
 * @throws ImageManagerException the image manager exception
 * @throws PDFManagerException the PDF manager exception
 * @throws ImageInterpreterException the image interpreter exception
 * @throws URISyntaxException
 ****************************************************************************/
public void createPDF(OutputStream out, PdfPageSize pagesizemode, Watermark myWatermark)
        throws ImageManagerException, FileNotFoundException, IOException, PDFManagerException,
        ImageInterpreterException, URISyntaxException {

    Document pdfdoc = null;
    PdfWriter writer = null;

    Rectangle pagesize = null; // pagesize of the first page
    PdfPageLabels pagelabels = null; // object to store all page labels

    try {
        if ((imageURLs == null) || (imageURLs.isEmpty())) {
            throw new PDFManagerException("No URLs for images available, HashMap is null or empty");
        }

        // set the page sizes & pdf document
        pdfdoc = setPDFPageSizeForFirstPage(pagesizemode, pagesize);

        // writer for creating the PDF
        writer = createPDFWriter(out, pdfdoc);

        // set metadata for PDF as author and title
        // ------------------------------------------------------------------------------------
        if (this.title != null) {
            pdfdoc.addTitle(this.title);
        }
        if (this.author != null) {
            pdfdoc.addAuthor(this.author);
        }
        if (this.keyword != null) {
            pdfdoc.addKeywords(this.keyword);
        }
        if (this.subject != null) {
            pdfdoc.addSubject(this.subject);
        }
        // add title page to PDF
        if (pdftitlepage != null) {
            // create a title page
            pdftitlepage.render(pdfdoc);
        }

        // iterate over all files, they must be ordered by the key
        // the key contains the page number (as integer), the String
        // contains the Page name
        // ----------------------------------------------------------------------

        pagelabels = addAllPages(pagesizemode, writer, pdfdoc, myWatermark);

        // add page labels
        if (pagelabels != null) {
            writer.setPageLabels(pagelabels);
        }

        // create the required xmp metadata
        // for pdfa
        if (pdfa) {
            writer.createXmpMetadata();
        }
    } catch (ImageManagerException e) {
        if (pdfdoc != null) {
            pdfdoc.close();
        }
        if (writer != null) {
            writer.close();
        }
        throw e;
    } catch (PDFManagerException e) {
        if (pdfdoc != null) {
            pdfdoc.close();
        }
        if (writer != null) {
            writer.close();
        }
        throw e;
    } catch (ImageInterpreterException e) {
        if (pdfdoc != null) {
            pdfdoc.close();
        }
        if (writer != null) {
            writer.close();
        }
        throw e;
    } catch (IOException e) {
        if (pdfdoc != null) {
            pdfdoc.close();
        }
        if (writer != null) {
            writer.close();
        }
        throw e;
    }
    // close documents and writer
    try {
        if (pdfdoc != null && pdfdoc.isOpen()) {
            pdfdoc.close();
        }
        if (writer != null) {
            writer.close();
        }
    } catch (IllegalStateException e) {
        LOGGER.warn("Caught IllegalStateException when closing pdf document.");
    } catch (NullPointerException e) {
        throw new PDFManagerException("Nullpointer occured while closing pdfwriter");
    }
    LOGGER.debug("PDF document and writer closed");
}

From source file:net.sf.sze.service.impl.converter.PdfConverterImpl.java

License:GNU General Public License

/**
 * Orders the pages from an DIN-A4-document on a DIN-A3-document.
 * @param reader reader for DIN-A4-document
 * @param pdfFileA3 file in which the A3-document will be saved.
 * @param pages page-numbers in the order they will placed the paper in the
 * order left, right-side must be a multiple of 4. 0 is interpreted as an
 * empty-page.//  w w  w  . jav a2  s.c  o  m
 * @throws DocumentException problems in iText.
 * @throws IOException io-problems.
 */
private void createA3Subdocument(PdfReader reader, File pdfFileA3, int... pages)
        throws DocumentException, IOException {
    if (pages.length % 4 != 0) {
        throw new IllegalArgumentException("The number of pages must be a " + "multiple of 4.");
    }

    // we retrieve the size of the first page
    final Rectangle psize = reader.getPageSize(1);
    final float width = psize.getWidth();
    final float leftMargin = 0f;
    final float topMargin = 0f;

    // step 1: creation of a document-object
    final Document document = new Document(PageSize.A3.rotate());
    // step 2: we create a writer that listens to the document
    final PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(pdfFileA3));
    writer.setPDFXConformance(PdfWriter.PDFA1B);
    // step 3: we open the document
    document.open();
    addPdfAInfosToDictonary(writer);

    // step 4: we add content
    final PdfContentByte cb = writer.getDirectContent();
    final PdfTemplate[] pdfPages = new PdfTemplate[pages.length];
    for (int i = 0; i < pdfPages.length; i++) {
        final int pageNr = pages[i];
        final PdfTemplate page;
        if (pageNr == EMPTY_PAGE) {
            page = writer.getImportedPage(getEmptyPDFPage(psize), 1);
        } else {
            page = writer.getImportedPage(reader, pageNr);
        }

        if (i % 2 == 0) {
            document.newPage();
            cb.addTemplate(page, 1f, 0f, 0f, 1f, leftMargin, topMargin);
        } else {
            cb.addTemplate(page, 1f, 0f, 0f, 1f, width + leftMargin, topMargin);
        }

    }

    writer.createXmpMetadata();
    // step 5: we close the document
    document.close();
}

From source file:org.eclipse.osee.framework.ui.skynet.util.TableWriterAdaptor.java

License:Open Source License

public Document openDocument() {
    document.addTitle(title);//from w ww. ja v a  2 s  .co m
    document.addSubject("This report is automatically generated.");
    document.addKeywords("Metadata, iText");
    document.addCreationDate();
    if (writer instanceof PdfWriter) {
        PdfWriter pdfWriter = (PdfWriter) writer;
        pdfWriter.createXmpMetadata();
    }
    document.open();
    return document;
}

From source file:questions.encryption.HelloWorldFullyEncrypted.java

public static void main(String[] args) {
    // step 1//from  w  ww  .  j a  va2 s.co  m
    Document document = new Document();
    try {
        // step 2
        PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(RESULT));
        writer.setEncryption("hello".getBytes(), "world".getBytes(), 0, PdfWriter.ENCRYPTION_AES_128);
        writer.createXmpMetadata();
        // step 3
        document.open();
        // step 4
        document.add(new Paragraph("Hello World"));
        writer.addAnnotation(PdfAnnotation.createFileAttachment(writer, new Rectangle(100f, 650f, 150f, 700f),
                "This is some text", "some text".getBytes(), null, "some.txt"));
    } catch (DocumentException de) {
        System.err.println(de.getMessage());
    } catch (IOException ioe) {
        System.err.println(ioe.getMessage());
    }
    // step 5
    document.close();
}

From source file:questions.encryption.HelloWorldMetadataNotEncrypted.java

public static void main(String[] args) {
    // step 1/*  ww  w  . j a v  a 2s  . c  om*/
    Document document = new Document();
    try {
        // step 2
        PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(RESULT));
        writer.setEncryption("hello".getBytes(), "world".getBytes(), 0,
                PdfWriter.ENCRYPTION_AES_128 | PdfWriter.DO_NOT_ENCRYPT_METADATA);
        writer.createXmpMetadata();
        writer.setPdfVersion(PdfWriter.VERSION_1_5);
        // step 3
        document.open();
        // step 4
        document.add(new Paragraph("Hello World"));
        writer.addAnnotation(PdfAnnotation.createFileAttachment(writer, new Rectangle(100f, 650f, 150f, 700f),
                "This is some text", "some text".getBytes(), null, "some.txt"));
    } catch (DocumentException de) {
        System.err.println(de.getMessage());
    } catch (IOException ioe) {
        System.err.println(ioe.getMessage());
    }
    // step 5
    document.close();
}

From source file:questions.metadata.ReplaceXMP.java

@SuppressWarnings("unchecked")
public static void createOriginal() {
    // step 1:/*  w  w w  . ja  va2 s  .c  o m*/
    Document document = new Document();
    try {
        document.addAuthor("Bruno Lowagie");
        document.addKeywords("Hello World, XMP, Metadata");
        // step 2:
        PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(ORIGINAL));
        // step 3:
        writer.createXmpMetadata();
        document.open();
        // step 4:
        document.add(new Paragraph("Hello World"));
    } catch (DocumentException de) {
        System.err.println(de.getMessage());
    } catch (IOException ioe) {
        System.err.println(ioe.getMessage());
    }
    // step 5:
    document.close();
}