Example usage for com.lowagie.text Document addCreationDate

List of usage examples for com.lowagie.text Document addCreationDate

Introduction

In this page you can find the example usage for com.lowagie.text Document addCreationDate.

Prototype


public boolean addCreationDate() 

Source Link

Document

Adds the current date and time to a Document.

Usage

From source file:org.displaytag.export.PdfView.java

License:Artistic License

/**
 * @see org.displaytag.export.BinaryExportView#doExport(OutputStream)
 *///from  ww w  .ja va2s  .  c o  m
public void doExport(OutputStream out) throws JspException {
    try {
        // Initialize the table with the appropriate number of columns
        initTable();

        // Initialize the Document and register it with PdfWriter listener and the OutputStream
        Document document = new Document(PageSize.A4.rotate(), 60, 60, 40, 40);
        document.addCreationDate();
        HeaderFooter footer = new HeaderFooter(new Phrase(TagConstants.EMPTY_STRING, smallFont), true);
        footer.setBorder(Rectangle.NO_BORDER);
        footer.setAlignment(Element.ALIGN_CENTER);

        PdfWriter.getInstance(document, out);

        // Fill the virtual PDF table with the necessary data
        generatePDFTable();
        document.open();
        document.setFooter(footer);
        document.add(this.tablePDF);
        document.close();

    } catch (Exception e) {
        throw new PdfGenerationException(e);
    }
}

From source file:org.egov.infra.web.displaytag.export.EGovPdfView.java

License:Open Source License

@Override
public void doExport(final OutputStream out) throws JspException {

    try {//from w  w  w.  j  a  v a2 s  . c om
        // Initialize the table with the appropriate number of columns
        initTable();

        // Initialize the Document and register it with PdfWriter listener and the OutputStream
        final Document document = new Document(PageSize.A4.rotate(), 60, 60, 40, 40);
        document.addCreationDate();
        final HeaderFooter footer = new HeaderFooter(new Phrase(TagConstants.TAGNAME_CAPTION, this.smallFont),
                true);
        footer.setBorder(Rectangle.NO_BORDER);
        footer.setAlignment(Element.ALIGN_CENTER);

        // PdfWriter.getInstance(document, out);
        PdfWriter.getInstance(document, out).setPageEvent(new PageNumber());
        // Fill the virtual PDF table with the necessary data
        generatePDFTable();
        document.open();

        // Table table = new Table(this.model.getNumberOfColumns());
        // ItextTableWriter writer = new ItextTableWriter(tablePDF, document);
        // writer.writeTable(this.model, "-1");
        // document.setFooter(footer);
        // document.setHeader(footer);
        document.add(this.tableCaption);
        document.add(this.tablePDF);
        document.close();

    } catch (final Exception e) {

        throw new PdfGenerationException(e);
    }

}

From source file:org.gbif.ipt.task.Eml2Rtf.java

License:Apache License

/**
 * Construct RTF document, mainly out of information extracted from Resource's EML object. Currently, the decision
 * has been made to always do this in English.
 * //from   ww w .j  a  va 2  s.  c o  m
 * @param doc Document
 * @param resource Resource
 * @throws DocumentException if problem occurs during add
 */
public void writeEmlIntoRtf(Document doc, Resource resource, String lng) throws DocumentException {
    // initialising resourceBundle.
    Locale loc = new Locale(lng);
    resourceBundle = ResourceBundle.getBundle("ApplicationResources", loc);
    // this.action = action;
    Eml eml = resource.getEml();
    // configure page
    doc.setMargins(72, 72, 72, 72);
    System.out.println(DataDir.CONFIG_DIR);
    // write metadata
    doc.addAuthor(resource.getCreator().getName());
    doc.addCreationDate();
    doc.addTitle((eml.getTitle() == null) ? resource.getShortname() : eml.getTitle());
    // add the keywords to the document
    StringBuilder keys = new StringBuilder();
    for (KeywordSet kw : eml.getKeywords()) {
        if (keys.length() == 0) {
            keys.append(kw.getKeywordsString(", "));
        } else {
            keys.append(", " + kw.getKeywordsString(", "));
        }
    }
    String keysValue = keys.toString();
    doc.addKeywords(keysValue);
    // write proper doc
    doc.open();
    // title
    addPara(doc, eml.getTitle(), fontHeader, 0, Element.ALIGN_CENTER);
    doc.add(Chunk.NEWLINE);
    // Authors, affiliations and corresponging authors
    addAuthors(doc, eml);
    // Other various sections..
    addDates(doc);
    //addCitations(doc);
    // Section called "Resource Citation" above "Abstract"
    addResourceCitation(doc, eml);
    setResAbs(eml);
    setPalKey(keysValue);
    setDisAgr(eml);
    //addAbstract(doc, eml);
    addRes(doc);
    //addKeywords(doc, keysValue);
    addPalcla(doc);
    addAbs(doc);
    addKeyWord(doc);
    addGeneralDescription(doc, eml);
    addProjectData(doc, eml);
    //addResourceLink(doc, resource);
    addTaxonomicCoverages(doc, eml, loc);
    addSpatialCoverage(doc, eml);
    addTemporalCoverages(doc, eml, loc);
    addNaturalCollections(doc, eml);
    addMethods(doc, eml);
    addResul(doc);
    addDatasetDescriptions(doc, resource);
    //addMetadataDescriptions(doc, eml);
    addDiscu(doc);
    addAgrad(doc);
    addReferences(doc, eml);
    doc.close();
}

From source file:org.goodoldai.jeff.report.pdf.PDFReportBuilder.java

License:Open Source License

/**
 * This method inserts the header into the PDF report. The header consists 
 * of general data collected from the explanation (date and time created, 
 * owner, title, language and country). If any of this data is missing, it is not
 * inserted into the report. Since the report format is PDF, the provided 
 * stream should be an instance of com.lowagie.text.Document.
 * /* w  w  w .ja  v  a 2 s. co  m*/
 * @param explanation explanation from which the header data is to be
 * collected
 * @param stream output stream that the header is supposed to be inserted
 * into
 * 
 * @throws org.goodoldai.jeff.explanation.ExplanationException if any of the arguments are
 * null or if the entered output stream type is not com.lowagie.text.Document
 */
protected void insertHeader(Explanation explanation, Object stream) {
    if (explanation == null) {
        throw new ExplanationException("The argument 'explanation' is mandatory, so it can not be null");
    }

    if (stream == null) {
        throw new ExplanationException("The argument 'stream' is mandatory, so it can not be null");
    }

    if (!(stream instanceof Document)) {
        throw new ExplanationException("The entered stream must be a com.lowagie.text.Document instance");
    }

    Document doc = (Document) stream;

    String owner = explanation.getOwner();
    String title = explanation.getTitle();

    doc.addCreator("JEFF (Java Explanation Facility Framework)");
    doc.addAuthor(owner + " [OWNER]");
    doc.addCreationDate();

    if (title != null) {
        try {
            Phrase p = new Phrase(title, new Font(Font.HELVETICA, 16));
            Paragraph pa = new Paragraph(p);
            pa.setSpacingBefore(10);
            pa.setSpacingAfter(30);
            pa.setAlignment(Element.ALIGN_CENTER);
            doc.add(pa);
        } catch (DocumentException ex) {
            throw new ExplanationException(ex.getMessage());
        }
    }

}

From source file:org.gtdfree.addons.PDFExportAddOn.java

License:Open Source License

@Override
public void export(GTDModel model, ActionsCollection collection, OutputStream out,
        ExportAddOn.ExportOrder order, FileFilter ff, boolean compact) throws Exception {

    fontSelector = new FontSelector();
    fontSelectorB = new FontSelector();
    fontSelectorB2 = new FontSelector();
    fontSelectorB4 = new FontSelector();

    baseFont = fontModel.getBaseFont();//  w  w w.  java2 s .c o m

    for (BaseFont bf : fontModel.getFonts()) {
        fontSelector.addFont(new Font(bf, baseFontSize));
        fontSelectorB.addFont(new Font(bf, baseFontSize, Font.BOLD));
        fontSelectorB2.addFont(new Font(bf, baseFontSize + 2, Font.BOLD));
        fontSelectorB4.addFont(new Font(bf, baseFontSize + 4, Font.BOLD));
    }

    boolean emptyH2 = false;
    boolean emptyH3 = false;

    PdfPTable actionTable = null;

    Document doc = new Document();

    if (sizeSet) {
        doc.setPageSize(pageSize);
    }
    if (marginSet) {
        doc.setMargins(marginLeft, marginRight, marginTop, marginBottom);
    }

    //System.out.println("PDF size "+doc.getPageSize().toString());
    //System.out.println("PDF m "+marginLeft+" "+marginRight+" "+marginTop+" "+marginBottom);

    @SuppressWarnings("unused")
    PdfWriter pw = PdfWriter.getInstance(doc, out);

    doc.addCreationDate();
    doc.addTitle("GTD-Free PDF");
    doc.addSubject("GTD-Free data exported as PDF");

    HeaderFooter footer = new HeaderFooter(newParagraph(), true);
    footer.setAlignment(HeaderFooter.ALIGN_CENTER);
    footer.setBorder(HeaderFooter.TOP);
    doc.setFooter(footer);

    doc.open();

    Phrase ch = newTitle("GTD-Free Data");
    Paragraph p = new Paragraph(ch);
    p.setAlignment(Paragraph.ALIGN_CENTER);

    PdfPTable t = new PdfPTable(1);
    t.setWidthPercentage(100f);
    PdfPCell c = newCell(p);
    c.setBorder(Table.BOTTOM);
    c.setBorderWidth(2.5f);
    c.setHorizontalAlignment(PdfPCell.ALIGN_CENTER);
    c.setPadding(5f);
    t.addCell(c);
    doc.add(t);

    Iterator<Object> it = collection.iterator(order);

    while (it.hasNext()) {
        Object o = it.next();

        if (o == ActionsCollection.ACTIONS_WITHOUT_PROJECT) {

            if (order == ExportAddOn.ExportOrder.FoldersProjectsActions) {

                doc.add(newSubSection(ActionsCollection.ACTIONS_WITHOUT_PROJECT));

                emptyH2 = false;
                emptyH3 = true;
            } else {

                doc.add(newSection(ActionsCollection.ACTIONS_WITHOUT_PROJECT));

                emptyH2 = true;
                emptyH3 = false;
            }

            continue;
        }

        if (o instanceof Folder) {

            Folder f = (Folder) o;

            if (actionTable != null) {
                doc.add(actionTable);
                actionTable = null;
            }

            if (f.isProject()) {

                if (order == ExportAddOn.ExportOrder.ProjectsActions
                        || order == ExportAddOn.ExportOrder.ProjectsFoldersActions) {

                    if (emptyH2 || emptyH3) {
                        p = newParagraph(NONE_DOT);
                        doc.add(p);
                    }

                    doc.add(newSection(f.getName()));

                    if (compact) {
                        if (f.getDescription() != null && f.getDescription().length() > 0) {
                            p = newParagraph(f.getDescription());
                            p.setIndentationLeft(10f);
                            p.setIndentationRight(10f);
                            doc.add(p);
                        }
                    } else {
                        t = new PdfPTable(2);
                        t.setKeepTogether(true);
                        t.setSpacingBefore(5f);
                        t.setWidthPercentage(66f);
                        t.setWidths(new float[] { 0.33f, 0.66f });

                        c = newCell("ID");
                        t.addCell(c);
                        c = newCell(newStrongParagraph(String.valueOf(f.getId())));
                        t.addCell(c);
                        c = newCell("Type");
                        t.addCell(c);
                        c = newCell(newStrongParagraph("Project"));
                        t.addCell(c);
                        c = newCell("Open");
                        t.addCell(c);
                        c = newCell(newStrongParagraph(String.valueOf(f.getOpenCount())));
                        t.addCell(c);
                        c = newCell("All");
                        t.addCell(c);
                        c = newCell(newStrongParagraph(String.valueOf(f.size())));
                        t.addCell(c);
                        c = newCell("Description");
                        t.addCell(c);
                        c = newDescriptionCell(f.getDescription());
                        t.addCell(c);

                        doc.add(t);
                    }

                    emptyH2 = true;
                    emptyH3 = false;

                } else {

                    if (emptyH3) {
                        p = newParagraph(NONE_DOT);
                        doc.add(p);
                    }

                    doc.add(newSubSection("Project:" + " " + f.getName()));

                    emptyH2 = false;
                    emptyH3 = true;
                }

                continue;

            }
            if (order == ExportAddOn.ExportOrder.FoldersActions
                    || order == ExportAddOn.ExportOrder.FoldersProjectsActions) {

                if (emptyH2 || emptyH3) {
                    p = newParagraph(NONE_DOT);
                    doc.add(p);
                }

                doc.add(newSection(f.getName()));

                if (compact) {
                    if (f.getDescription() != null && f.getDescription().length() > 0) {
                        p = newParagraph(f.getDescription());
                        p.setIndentationLeft(10f);
                        p.setIndentationRight(10f);
                        doc.add(p);
                    }
                } else {

                    t = new PdfPTable(2);
                    t.setKeepTogether(true);
                    t.setSpacingBefore(5f);
                    t.setWidthPercentage(66f);
                    t.setWidths(new float[] { 0.33f, 0.66f });

                    c = newCell("ID");
                    t.addCell(c);
                    c = newCell(newStrongParagraph(String.valueOf(f.getId())));
                    t.addCell(c);

                    String type = "";
                    if (f.isAction()) {
                        type = "Action list";
                    } else if (f.isInBucket()) {
                        type = "In-Bucket";
                    } else if (f.isQueue()) {
                        type = "Next action queue";
                    } else if (f.isReference()) {
                        type = "Reference list";
                    } else if (f.isSomeday()) {
                        type = "Someday/Maybe list";
                    } else if (f.isBuildIn()) {
                        type = "Default list";
                    }

                    c = newCell("Type");
                    t.addCell(c);
                    c = newCell(newStrongParagraph(type));
                    t.addCell(c);
                    c = newCell("Open");
                    t.addCell(c);
                    c = newCell(newStrongParagraph(String.valueOf(f.getOpenCount())));
                    t.addCell(c);
                    c = newCell("All");
                    t.addCell(c);
                    c = newCell(newStrongParagraph(String.valueOf(f.size())));
                    t.addCell(c);
                    c = newCell("Description");
                    t.addCell(c);
                    c = newDescriptionCell(f.getDescription());
                    t.addCell(c);

                    doc.add(t);
                }

                emptyH2 = true;
                emptyH3 = false;

            } else {

                if (emptyH3) {
                    p = newParagraph(NONE_DOT);
                    doc.add(p);
                }

                doc.add(newSubSection("List:" + " " + f.getName()));

                emptyH2 = false;
                emptyH3 = true;

            }

            continue;

        }

        if (o instanceof Action) {
            emptyH2 = false;
            emptyH3 = false;

            Action a = (Action) o;

            if (compact) {

                if (actionTable == null) {
                    actionTable = new PdfPTable(5);
                    actionTable.setWidthPercentage(100f);
                    actionTable.setHeaderRows(1);
                    actionTable.setSpacingBefore(5f);
                    c = newHeaderCell("ID");
                    actionTable.addCell(c);
                    c = newHeaderCell("Pri.");
                    actionTable.addCell(c);
                    c = newHeaderCell("Description");
                    actionTable.addCell(c);
                    c = newHeaderCell("Reminder");
                    actionTable.addCell(c);
                    c = newHeaderCell(CHECK_RESOLVED);
                    actionTable.addCell(c);

                    float width = doc.getPageSize().getWidth() - doc.getPageSize().getBorderWidthLeft()
                            - doc.getPageSize().getBorderWidthRight();
                    int i = model.getLastActionID();
                    float step = baseFontSize - 1;
                    int steps = (int) Math.floor(Math.log10(i)) + 1;
                    // ID column
                    float col1 = 8 + steps * step;
                    // Priority column
                    float col2 = 4 + 3 * (baseFontSize + 4);
                    // Reminder column
                    float col4 = 10 + step * 11;
                    // Resolved column
                    float col5 = 8 + baseFontSize;
                    // Description column
                    float col3 = width - col1 - col2 - col4 - col5;
                    actionTable.setWidths(new float[] { col1, col2, col3, col4, col5 });

                }

                addSingleActionRow(a, actionTable);

            } else {
                addSingleActionTable(model, doc, a);
            }
        }

    }

    if (actionTable != null) {
        doc.add(actionTable);
        actionTable = null;
    }
    if (emptyH2 || emptyH3) {

        p = newParagraph(NONE_DOT);
        doc.add(p);
    }

    //w.writeCharacters("Exported: "+ApplicationHelper.toISODateTimeString(new Date()));

    doc.close();
}

From source file:org.jboss.as.quickstarts.ejbinwar.ejb.GreeterEJB.java

License:Apache License

public ByteArrayOutputStream generatePDFDocumentBytes(String selectedTariff) throws DocumentException {
    java.util.Set<String> users = getRestUsers(selectedTariff);

    Document doc = new Document();

    ByteArrayOutputStream baosPDF = new ByteArrayOutputStream();
    PdfWriter docWriter = null;//from w w w  . j  av a2s  .c  om

    try {
        docWriter = PdfWriter.getInstance(doc, baosPDF);

        doc.addAuthor(this.getClass().getName());
        doc.addCreationDate();
        doc.addProducer();
        doc.addCreator(this.getClass().getName());
        doc.addTitle(selectedTariff + " clients");
        doc.addKeywords("pdf, itext, Java, ecare, http");

        doc.setPageSize(PageSize.LETTER);

        HeaderFooter footer = new HeaderFooter(new Phrase("E-Care report"), false);

        doc.setFooter(footer);

        doc.open();

        doc.add(new Paragraph(selectedTariff + " clients"));
        doc.add(new Paragraph("\n"));
        doc.add(new Paragraph("\n"));

        PdfPTable table = new PdfPTable(4); // 3 columns.

        PdfPCell cell1 = new PdfPCell(new Paragraph("Name"));
        PdfPCell cell2 = new PdfPCell(new Paragraph("Surname"));
        PdfPCell cell3 = new PdfPCell(new Paragraph("Address"));
        PdfPCell cell4 = new PdfPCell(new Paragraph("Email"));

        table.addCell(cell1);
        table.addCell(cell2);
        table.addCell(cell3);
        table.addCell(cell4);

        for (Iterator<String> it = users.iterator(); it.hasNext();) {
            String user = it.next();

            table.addCell(new PdfPCell(new Paragraph(user.split(" ")[0])));
            table.addCell(new PdfPCell(new Paragraph(user.split(" ")[1])));
            table.addCell(new PdfPCell(new Paragraph(user.split(" ")[2])));
            table.addCell(new PdfPCell(new Paragraph(user.split(" ")[3])));
        }

        doc.add(table);

    } catch (DocumentException dex) {
        baosPDF.reset();
        throw dex;
    } finally {
        if (doc != null) {
            doc.close();
        }
        if (docWriter != null) {
            docWriter.close();
        }
    }

    if (baosPDF.size() < 1) {
        throw new DocumentException("document has " + baosPDF.size() + " bytes");
    }
    return baosPDF;

}

From source file:org.jbpm.designer.web.server.TransformerServlet.java

License:Apache License

@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    req.setCharacterEncoding("UTF-8");
    String formattedSvgEncoded = req.getParameter("fsvg");
    String uuid = Utils.getUUID(req);
    String profileName = Utils.getDefaultProfileName(req.getParameter("profile"));
    String transformto = req.getParameter("transformto");
    String jpdl = req.getParameter("jpdl");
    String gpd = req.getParameter("gpd");
    String bpmn2in = req.getParameter("bpmn2");
    String jsonin = req.getParameter("json");
    String preprocessingData = req.getParameter("pp");
    String respaction = req.getParameter("respaction");
    String pp = req.getParameter("pp");
    String processid = req.getParameter("processid");
    String sourceEnc = req.getParameter("enc");
    String convertServiceTasks = req.getParameter("convertservicetasks");
    String htmlSourceEnc = req.getParameter("htmlenc");

    String formattedSvg = (formattedSvgEncoded == null ? ""
            : new String(Base64.decodeBase64(formattedSvgEncoded), "UTF-8"));

    String htmlSource = (htmlSourceEnc == null ? "" : new String(Base64.decodeBase64(htmlSourceEnc), "UTF-8"));

    if (sourceEnc != null && sourceEnc.equals("true")) {
        bpmn2in = new String(Base64.decodeBase64(bpmn2in), "UTF-8");
    }/*from   w w  w. j  a  va2s  .c om*/

    if (profile == null) {
        profile = _profileService.findProfile(req, profileName);
    }

    DroolsFactoryImpl.init();
    BpsimFactoryImpl.init();

    Repository repository = profile.getRepository();

    if (transformto != null && transformto.equals(TO_PDF)) {
        if (respaction != null && respaction.equals(RESPACTION_SHOWURL)) {

            try {
                ByteArrayOutputStream pdfBout = new ByteArrayOutputStream();
                Document pdfDoc = new Document(PageSize.A4);
                PdfWriter pdfWriter = PdfWriter.getInstance(pdfDoc, pdfBout);
                pdfDoc.open();
                pdfDoc.addCreationDate();

                PNGTranscoder t = new PNGTranscoder();
                t.addTranscodingHint(ImageTranscoder.KEY_MEDIA, "screen");

                float widthHint = getFloatParam(req, SVG_WIDTH_PARAM, DEFAULT_PDF_WIDTH);
                float heightHint = getFloatParam(req, SVG_HEIGHT_PARAM, DEFAULT_PDF_HEIGHT);
                String objStyle = "style=\"width:" + widthHint + "px;height:" + heightHint + "px;\"";
                t.addTranscodingHint(SVGAbstractTranscoder.KEY_WIDTH, widthHint);
                t.addTranscodingHint(SVGAbstractTranscoder.KEY_HEIGHT, heightHint);

                ByteArrayOutputStream imageBout = new ByteArrayOutputStream();
                TranscoderInput input = new TranscoderInput(new StringReader(formattedSvg));
                TranscoderOutput output = new TranscoderOutput(imageBout);
                t.transcode(input, output);

                Image processImage = Image.getInstance(imageBout.toByteArray());
                scalePDFImage(pdfDoc, processImage);
                pdfDoc.add(processImage);

                pdfDoc.close();

                resp.setCharacterEncoding("UTF-8");
                resp.setContentType("text/plain");

                resp.getWriter()
                        .write("<object type=\"application/pdf\" " + objStyle
                                + " data=\"data:application/pdf;base64,"
                                + Base64.encodeBase64String(pdfBout.toByteArray()) + "\"></object>");
            } catch (Exception e) {
                resp.sendError(500, e.getMessage());
            }
        } else {
            storeInRepository(uuid, formattedSvg, transformto, processid, repository);

            try {
                resp.setCharacterEncoding("UTF-8");
                resp.setContentType("application/pdf");
                if (processid != null) {
                    resp.setHeader("Content-Disposition", "attachment; filename=\"" + processid + ".pdf\"");
                } else {
                    resp.setHeader("Content-Disposition", "attachment; filename=\"" + uuid + ".pdf\"");
                }

                ByteArrayOutputStream bout = new ByteArrayOutputStream();
                Document pdfDoc = new Document(PageSize.A4);
                PdfWriter pdfWriter = PdfWriter.getInstance(pdfDoc, resp.getOutputStream());
                pdfDoc.open();
                pdfDoc.addCreationDate();

                PNGTranscoder t = new PNGTranscoder();
                t.addTranscodingHint(ImageTranscoder.KEY_MEDIA, "screen");
                TranscoderInput input = new TranscoderInput(new StringReader(formattedSvg));
                TranscoderOutput output = new TranscoderOutput(bout);
                t.transcode(input, output);

                Image processImage = Image.getInstance(bout.toByteArray());
                scalePDFImage(pdfDoc, processImage);
                pdfDoc.add(processImage);

                pdfDoc.close();
            } catch (Exception e) {
                resp.sendError(500, e.getMessage());
            }
        }
    } else if (transformto != null && transformto.equals(TO_PNG)) {
        try {
            if (respaction != null && respaction.equals(RESPACTION_SHOWURL)) {
                ByteArrayOutputStream bout = new ByteArrayOutputStream();
                PNGTranscoder t = new PNGTranscoder();
                t.addTranscodingHint(ImageTranscoder.KEY_MEDIA, "screen");
                TranscoderInput input = new TranscoderInput(new StringReader(formattedSvg));
                TranscoderOutput output = new TranscoderOutput(bout);
                t.transcode(input, output);
                resp.setCharacterEncoding("UTF-8");
                resp.setContentType("text/plain");
                if (req.getParameter(SVG_WIDTH_PARAM) != null && req.getParameter(SVG_HEIGHT_PARAM) != null) {
                    int widthHint = (int) getFloatParam(req, SVG_WIDTH_PARAM, DEFAULT_PDF_WIDTH);
                    int heightHint = (int) getFloatParam(req, SVG_HEIGHT_PARAM, DEFAULT_PDF_HEIGHT);
                    resp.getWriter()
                            .write("<img width=\"" + widthHint + "\" height=\"" + heightHint
                                    + "\" src=\"data:image/png;base64,"
                                    + Base64.encodeBase64String(bout.toByteArray()) + "\">");
                } else {
                    resp.getWriter().write("<img src=\"data:image/png;base64,"
                            + Base64.encodeBase64String(bout.toByteArray()) + "\">");
                }
            } else {
                storeInRepository(uuid, formattedSvg, transformto, processid, repository);
                resp.setContentType("image/png");
                if (processid != null) {
                    resp.setHeader("Content-Disposition", "attachment; filename=\"" + processid + ".png\"");
                } else {
                    resp.setHeader("Content-Disposition", "attachment; filename=\"" + uuid + ".png\"");
                }

                PNGTranscoder t = new PNGTranscoder();
                t.addTranscodingHint(ImageTranscoder.KEY_MEDIA, "screen");
                TranscoderInput input = new TranscoderInput(new StringReader(formattedSvg));
                TranscoderOutput output = new TranscoderOutput(resp.getOutputStream());
                t.transcode(input, output);
            }
        } catch (TranscoderException e) {
            resp.sendError(500, e.getMessage());
        }
    } else if (transformto != null && transformto.equals(TO_SVG)) {
        storeInRepository(uuid, formattedSvg, transformto, processid, repository);
    } else if (transformto != null && transformto.equals(BPMN2_TO_JSON)) {
        try {
            if (convertServiceTasks != null && convertServiceTasks.equals("true")) {
                bpmn2in = bpmn2in.replaceAll("drools:taskName=\".*?\"", "drools:taskName=\"ReadOnlyService\"");
                bpmn2in = bpmn2in.replaceAll("tns:taskName=\".*?\"", "tns:taskName=\"ReadOnlyService\"");
            }

            Definitions def = ((JbpmProfileImpl) profile).getDefinitions(bpmn2in);
            def.setTargetNamespace("http://www.omg.org/bpmn20");

            if (convertServiceTasks != null && convertServiceTasks.equals("true")) {
                // fix the data input associations for converted tasks
                List<RootElement> rootElements = def.getRootElements();
                for (RootElement root : rootElements) {
                    if (root instanceof Process) {
                        updateTaskDataInputs((Process) root, def);
                    }
                }
            }

            // get the xml from Definitions
            ResourceSet rSet = new ResourceSetImpl();
            rSet.getResourceFactoryRegistry().getExtensionToFactoryMap().put("bpmn2",
                    new JBPMBpmn2ResourceFactoryImpl());
            JBPMBpmn2ResourceImpl bpmn2resource = (JBPMBpmn2ResourceImpl) rSet
                    .createResource(URI.createURI("virtual.bpmn2"));
            bpmn2resource.getDefaultLoadOptions().put(JBPMBpmn2ResourceImpl.OPTION_ENCODING, "UTF-8");
            bpmn2resource.getDefaultLoadOptions().put(JBPMBpmn2ResourceImpl.OPTION_DEFER_IDREF_RESOLUTION,
                    true);
            bpmn2resource.getDefaultLoadOptions().put(JBPMBpmn2ResourceImpl.OPTION_DISABLE_NOTIFY, true);
            bpmn2resource.getDefaultLoadOptions().put(JBPMBpmn2ResourceImpl.OPTION_PROCESS_DANGLING_HREF,
                    JBPMBpmn2ResourceImpl.OPTION_PROCESS_DANGLING_HREF_RECORD);
            bpmn2resource.setEncoding("UTF-8");
            rSet.getResources().add(bpmn2resource);
            bpmn2resource.getContents().add(def);
            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
            bpmn2resource.save(outputStream, new HashMap<Object, Object>());
            String revisedXmlModel = outputStream.toString();
            String json = profile.createUnmarshaller().parseModel(revisedXmlModel, profile, pp);
            resp.setCharacterEncoding("UTF-8");
            resp.setContentType("application/json");
            resp.getWriter().print(json);
        } catch (Exception e) {
            e.printStackTrace();
            _logger.error(e.getMessage());
            resp.setContentType("application/json");
            resp.getWriter().print("{}");
        }
    } else if (transformto != null && transformto.equals(JSON_TO_BPMN2)) {
        try {
            DroolsFactoryImpl.init();
            BpsimFactoryImpl.init();
            if (preprocessingData == null) {
                preprocessingData = "";
            }
            String processXML = profile.createMarshaller().parseModel(jsonin, preprocessingData);
            resp.setContentType("application/xml");
            resp.getWriter().print(processXML);
        } catch (Exception e) {
            e.printStackTrace();
            _logger.error(e.getMessage());
            resp.setContentType("application/xml");
            resp.getWriter().print("");
        }
    } else if (transformto != null && transformto.equals(HTML_TO_PDF)) {
        try {
            resp.setContentType("application/pdf");
            if (processid != null) {
                resp.setHeader("Content-Disposition", "attachment; filename=\"" + processid + ".pdf\"");
            } else {
                resp.setHeader("Content-Disposition", "attachment; filename=\"" + uuid + ".pdf\"");
            }

            Document pdfDoc = new Document(PageSize.A4);
            PdfWriter pdfWriter = PdfWriter.getInstance(pdfDoc, resp.getOutputStream());
            pdfDoc.open();
            pdfDoc.addCreator("jBPM Designer");
            pdfDoc.addSubject("Business Process Documentation");
            pdfDoc.addCreationDate();
            pdfDoc.addTitle("Process Documentation");

            HTMLWorker htmlWorker = new HTMLWorker(pdfDoc);
            htmlWorker.parse(new StringReader(htmlSource));
            pdfDoc.close();
        } catch (DocumentException e) {
            resp.sendError(500, e.getMessage());
        }
    }
}

From source file:org.jbpm.designer.web.server.TransformerServlet.java

License:Apache License

protected void storeInRepository(String uuid, String svg, String transformto, String processid,
        Repository repository) {/*from w w w . j a  va2  s.c o  m*/
    String assetFullName = "";
    try {
        if (processid != null) {
            Asset<byte[]> processAsset = repository.loadAsset(uuid);
            String assetExt = "";
            String assetFileExt = "";
            if (transformto.equals(TO_PDF)) {
                assetExt = "-pdf";
                assetFileExt = ".pdf";
            }
            if (transformto.equals(TO_PNG)) {
                assetExt = "-image";
                assetFileExt = ".png";
            }
            if (transformto.equals(TO_SVG)) {
                assetExt = "-svg";
                assetFileExt = ".svg";
            }

            if (processid.startsWith(".")) {
                processid = processid.substring(1, processid.length());
            }
            assetFullName = processid + assetExt + assetFileExt;

            repository.deleteAssetFromPath(
                    processAsset.getAssetLocation().replaceAll("\\s", "%20") + "/" + assetFullName);

            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();

            if (transformto.equals(TO_PDF)) {

                ByteArrayOutputStream bout = new ByteArrayOutputStream();
                Document pdfDoc = new Document(PageSize.A4);
                PdfWriter pdfWriter = PdfWriter.getInstance(pdfDoc, outputStream);
                pdfDoc.open();
                pdfDoc.addCreationDate();

                PNGTranscoder t = new PNGTranscoder();
                t.addTranscodingHint(ImageTranscoder.KEY_MEDIA, "screen");
                TranscoderInput input = new TranscoderInput(new StringReader(svg));
                TranscoderOutput output = new TranscoderOutput(bout);
                t.transcode(input, output);

                Image processImage = Image.getInstance(bout.toByteArray());
                scalePDFImage(pdfDoc, processImage);
                pdfDoc.add(processImage);

                pdfDoc.close();
            } else if (transformto.equals(TO_PNG)) {
                PNGTranscoder t = new PNGTranscoder();
                t.addTranscodingHint(ImageTranscoder.KEY_MEDIA, "screen");
                TranscoderInput input = new TranscoderInput(new StringReader(svg));
                TranscoderOutput output = new TranscoderOutput(outputStream);
                try {
                    t.transcode(input, output);
                } catch (Exception e) {
                    // issue with batik here..do not make a big deal
                    _logger.debug(e.getMessage());
                }
            } else if (transformto.equals(TO_SVG)) {
                OutputStreamWriter outStreamWriter = new OutputStreamWriter(outputStream);
                outStreamWriter.write(svg);
                outStreamWriter.close();
            }
            AssetBuilder builder = AssetBuilderFactory.getAssetBuilder(Asset.AssetType.Byte);

            builder.name(processid + assetExt).type(assetFileExt.substring(1))
                    .location(processAsset.getAssetLocation().replaceAll("\\s", "%20"))
                    .version(processAsset.getVersion()).content(outputStream.toByteArray());

            Asset<byte[]> resourceAsset = builder.getAsset();

            repository.createAsset(resourceAsset);
        }
    } catch (Exception e) {
        // just log that error happened
        if (e.getMessage() != null) {
            _logger.error(e.getMessage());
        } else {
            _logger.error(e.getClass().toString() + " " + assetFullName);
        }
        e.printStackTrace();
    }
}

From source file:org.jrimum.bopepo.pdf.PDFs.java

License:Apache License

/**
 * Junta varios arquivos pdf em um s./*ww  w  . j  a  va2s .c om*/
 * 
 * @param pdfFiles
 *            Coleo de array de bytes
 * @param info
 *            Usa somente as informaes
 *            (title,subject,keywords,author,creator)
 * 
 * @return Arquivo PDF em forma de byte
 * 
 * @since 0.2
 */
public static byte[] mergeFiles(Collection<byte[]> pdfFiles, PdfDocInfo info) {

    try {

        ByteArrayOutputStream byteOS = new ByteArrayOutputStream();

        Document document = new Document();

        PdfCopy copy = new PdfCopy(document, byteOS);

        document.open();

        for (byte[] f : pdfFiles) {

            PdfReader reader = new PdfReader(f);

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

                copy.addPage(copy.getImportedPage(reader, page));
            }

            reader.close();
        }

        document.addCreationDate();

        if (info != null) {

            document.addAuthor(info.author());
            document.addCreator(info.creator());
            document.addTitle(info.title());
            document.addSubject(info.subject());
            document.addKeywords(info.keywords());
        }

        copy.close();
        document.close();
        byteOS.close();

        return byteOS.toByteArray();

    } catch (Exception e) {
        return Exceptions.throwIllegalStateException(e);
    }
}

From source file:org.netxilia.server.rest.pdf.SheetPdfProvider.java

License:Open Source License

@Override
public void writeTo(SheetFullName sheetName, Class<?> clazz, Type type, Annotation[] ann, MediaType mediaType,
        MultivaluedMap<String, Object> headers, OutputStream out) throws IOException, WebApplicationException {

    if (sheetName == null) {
        return;/*from   w w w.j a  va  2s. c om*/
    }

    /**
     * This is the table, added as an Element to the PDF document. It contains all the data, needed to represent the
     * visible table into the PDF
     */
    Table tablePDF;

    /**
     * The default font used in the document.
     */
    Font smallFont = FontFactory.getFont(FontFactory.HELVETICA, 7, Font.NORMAL, new Color(0, 0, 0));
    ISheet summarySheet = null;
    ISheet sheet = null;
    try {
        sheet = workbookProcessor.getWorkbook(sheetName.getWorkbookId()).getSheet(sheetName.getSheetName());
        try {
            // get the corresponding summary sheet
            SheetFullName summarySheetName = SheetFullName.summarySheetName(sheetName,
                    userService.getCurrentUser());
            summarySheet = workbookProcessor.getWorkbook(summarySheetName.getWorkbookId())
                    .getSheet(summarySheetName.getSheetName());

        } catch (Exception e) {
            // no summary sheet - go without one
        }

        // Initialize the Document and register it with PdfWriter listener and the OutputStream
        Document document = new Document(PageSize.A4.rotate(), 60, 60, 40, 40);
        document.addCreationDate();
        HeaderFooter footer = new HeaderFooter(new Phrase("", smallFont), true);
        footer.setBorder(Rectangle.NO_BORDER);
        footer.setAlignment(Element.ALIGN_CENTER);

        PdfWriter.getInstance(document, out);

        // Fill the virtual PDF table with the necessary data
        // Initialize the table with the appropriate number of columns
        tablePDF = initTable(sheet);
        // take tha maximum numbers of columns
        int columnCount = sheet.getDimensions().getNonBlocking().getColumnCount();
        if (summarySheet != null) {
            columnCount = Math.max(columnCount, summarySheet.getDimensions().getNonBlocking().getColumnCount());
        }
        generateHeaders(sheet, tablePDF, smallFont, columnCount);

        tablePDF.endHeaders();
        generateRows(sheet, false, tablePDF, smallFont, columnCount);
        if (summarySheet != null) {
            generateRows(summarySheet, true, tablePDF, smallFont, columnCount);
        }

        document.open();
        document.setFooter(footer);
        document.add(tablePDF);
        document.close();

        out.flush();
        out.close();

    } catch (Exception e) {
        throw new IOException(e);
    }
}