Search in sources :

Example 1 with DocumentException

use of com.lowagie.text.DocumentException in project Openfire by igniterealtime.

the class GraphServlet method writePDFContent.

private void writePDFContent(HttpServletRequest request, HttpServletResponse response, JFreeChart[] charts, Statistic[] stats, long starttime, long endtime, int width, int height) throws IOException {
    try {
        Document document = new Document(PageSize.A4, 50, 50, 50, 50);
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        PdfWriter writer = PdfWriter.getInstance(document, baos);
        writer.setPageEvent(new PDFEventListener(request));
        document.open();
        int index = 0;
        int chapIndex = 0;
        for (Statistic stat : stats) {
            String serverName = XMPPServer.getInstance().getServerInfo().getXMPPDomain();
            String dateName = JiveGlobals.formatDate(new Date(starttime)) + " - " + JiveGlobals.formatDate(new Date(endtime));
            Paragraph paragraph = new Paragraph(serverName, FontFactory.getFont(FontFactory.HELVETICA, 18, Font.BOLD));
            document.add(paragraph);
            paragraph = new Paragraph(dateName, FontFactory.getFont(FontFactory.HELVETICA, 14, Font.PLAIN));
            document.add(paragraph);
            document.add(Chunk.NEWLINE);
            document.add(Chunk.NEWLINE);
            Paragraph chapterTitle = new Paragraph(++chapIndex + ". " + stat.getName(), FontFactory.getFont(FontFactory.HELVETICA, 16, Font.BOLD));
            document.add(chapterTitle);
            // total hack: no idea what tags people are going to use in the description
            // possibly recommend that we only use a <p> tag?
            String[] paragraphs = stat.getDescription().split("<p>");
            for (String s : paragraphs) {
                Paragraph p = new Paragraph(s);
                document.add(p);
            }
            document.add(Chunk.NEWLINE);
            PdfContentByte contentByte = writer.getDirectContent();
            PdfTemplate template = contentByte.createTemplate(width, height);
            Graphics2D graphs2D = template.createGraphics(width, height, new DefaultFontMapper());
            Rectangle2D rectangle2D = new Rectangle2D.Double(0, 0, width, height);
            charts[index++].draw(graphs2D, rectangle2D);
            graphs2D.dispose();
            float x = (document.getPageSize().width() / 2) - (width / 2);
            contentByte.addTemplate(template, x, writer.getVerticalPosition(true) - height);
            document.newPage();
        }
        document.close();
        // setting some response headers
        response.setHeader("Expires", "0");
        response.setHeader("Cache-Control", "must-revalidate, post-check=0, pre-check=0");
        response.setHeader("Pragma", "public");
        // setting the content type
        response.setContentType("application/pdf");
        // the contentlength is needed for MSIE!!!
        response.setContentLength(baos.size());
        // write ByteArrayOutputStream to the ServletOutputStream
        ServletOutputStream out = response.getOutputStream();
        baos.writeTo(out);
        out.flush();
    } catch (DocumentException e) {
        Log.error("error creating PDF document: " + e.getMessage());
    }
}
Also used : PdfWriter(com.lowagie.text.pdf.PdfWriter) ServletOutputStream(javax.servlet.ServletOutputStream) Rectangle2D(java.awt.geom.Rectangle2D) DefaultFontMapper(com.lowagie.text.pdf.DefaultFontMapper) ByteArrayOutputStream(java.io.ByteArrayOutputStream) Document(com.lowagie.text.Document) PdfTemplate(com.lowagie.text.pdf.PdfTemplate) Date(java.util.Date) Paragraph(com.lowagie.text.Paragraph) Graphics2D(java.awt.Graphics2D) Statistic(org.jivesoftware.openfire.stats.Statistic) DocumentException(com.lowagie.text.DocumentException) PdfContentByte(com.lowagie.text.pdf.PdfContentByte)

Example 2 with DocumentException

use of com.lowagie.text.DocumentException in project Openfire by igniterealtime.

the class ConversationUtils method buildPDFContent.

private ByteArrayOutputStream buildPDFContent(Conversation conversation, Map<String, Font> colorMap) {
    Font roomEvent = FontFactory.getFont(FontFactory.HELVETICA, 12f, Font.ITALIC, new Color(0xFF, 0x00, 0xFF));
    try {
        Document document = new Document(PageSize.A4, 50, 50, 50, 50);
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        PdfWriter writer = PdfWriter.getInstance(document, baos);
        writer.setPageEvent(new PDFEventListener());
        document.open();
        Paragraph p = new Paragraph(LocaleUtils.getLocalizedString("archive.search.pdf.title", MonitoringConstants.NAME), FontFactory.getFont(FontFactory.HELVETICA, 18, Font.BOLD));
        document.add(p);
        document.add(Chunk.NEWLINE);
        ConversationInfo coninfo = new ConversationUtils().getConversationInfo(conversation.getConversationID(), false);
        String participantsDetail;
        if (coninfo.getAllParticipants() == null) {
            participantsDetail = coninfo.getParticipant1() + ", " + coninfo.getParticipant2();
        } else {
            participantsDetail = String.valueOf(coninfo.getAllParticipants().length);
        }
        Paragraph chapterTitle = new Paragraph(LocaleUtils.getLocalizedString("archive.search.pdf.participants", MonitoringConstants.NAME) + " " + participantsDetail, FontFactory.getFont(FontFactory.HELVETICA, 12, Font.BOLD));
        document.add(chapterTitle);
        Paragraph startDate = new Paragraph(LocaleUtils.getLocalizedString("archive.search.pdf.startdate", MonitoringConstants.NAME) + " " + coninfo.getDate(), FontFactory.getFont(FontFactory.HELVETICA, 12, Font.BOLD));
        document.add(startDate);
        Paragraph duration = new Paragraph(LocaleUtils.getLocalizedString("archive.search.pdf.duration", MonitoringConstants.NAME) + " " + coninfo.getDuration(), FontFactory.getFont(FontFactory.HELVETICA, 12, Font.BOLD));
        document.add(duration);
        Paragraph messageCount = new Paragraph(LocaleUtils.getLocalizedString("archive.search.pdf.messagecount", MonitoringConstants.NAME) + " " + conversation.getMessageCount(), FontFactory.getFont(FontFactory.HELVETICA, 12, Font.BOLD));
        document.add(messageCount);
        document.add(Chunk.NEWLINE);
        Paragraph messageParagraph;
        for (ArchivedMessage message : conversation.getMessages()) {
            String time = JiveGlobals.formatTime(message.getSentDate());
            String from = message.getFromJID().getNode();
            if (conversation.getRoom() != null) {
                from = message.getToJID().getResource();
            }
            String body = message.getBody();
            String prefix;
            if (!message.isRoomEvent()) {
                prefix = "[" + time + "] " + from + ":  ";
                Font font = colorMap.get(message.getFromJID().toString());
                if (font == null) {
                    font = colorMap.get(message.getFromJID().toBareJID());
                }
                if (font == null) {
                    font = FontFactory.getFont(FontFactory.HELVETICA, 12f, Font.BOLD, Color.BLACK);
                }
                messageParagraph = new Paragraph(new Chunk(prefix, font));
            } else {
                prefix = "[" + time + "] ";
                messageParagraph = new Paragraph(new Chunk(prefix, roomEvent));
            }
            messageParagraph.add(body);
            messageParagraph.add(" ");
            document.add(messageParagraph);
        }
        document.close();
        return baos;
    } catch (DocumentException e) {
        Log.error("error creating PDF document: " + e.getMessage(), e);
        return null;
    }
}
Also used : PdfWriter(com.lowagie.text.pdf.PdfWriter) Color(java.awt.Color) ByteArrayOutputStream(java.io.ByteArrayOutputStream) Document(com.lowagie.text.Document) Chunk(com.lowagie.text.Chunk) Font(com.lowagie.text.Font) Paragraph(com.lowagie.text.Paragraph) DocumentException(com.lowagie.text.DocumentException)

Example 3 with DocumentException

use of com.lowagie.text.DocumentException in project jgnash by ccavanaugh.

the class FontRegistry method registerFont.

private void registerFont(final String path) {
    try {
        if (path.toLowerCase(Locale.ROOT).endsWith(".ttf") || path.toLowerCase(Locale.ROOT).endsWith(".otf") || path.toLowerCase(Locale.ROOT).indexOf(".ttc,") > 0) {
            Object[] allNames = BaseFont.getAllFontNames(path, BaseFont.WINANSI, null);
            //full name
            String[][] names = (String[][]) allNames[2];
            for (String[] name : names) {
                registeredFontMap.put(name[3].toLowerCase(Locale.ROOT), path);
            }
        } else if (path.toLowerCase(Locale.ROOT).endsWith(".ttc")) {
            String[] names = BaseFont.enumerateTTCNames(path);
            for (int i = 0; i < names.length; i++) {
                registerFont(path + "," + i);
            }
        } else if (path.toLowerCase(Locale.ROOT).endsWith(".afm") || path.toLowerCase(Locale.ROOT).endsWith(".pfm")) {
            BaseFont bf = BaseFont.createFont(path, BaseFont.CP1252, false);
            String fullName = bf.getFullFontName()[0][3].toLowerCase(Locale.ROOT);
            registeredFontMap.put(fullName, path);
        }
    } catch (final DocumentException | IOException e) {
        throw new RuntimeException(e);
    }
}
Also used : DocumentException(com.lowagie.text.DocumentException) BaseFont(com.lowagie.text.pdf.BaseFont) IOException(java.io.IOException)

Example 4 with DocumentException

use of com.lowagie.text.DocumentException in project janrufmonitor by tbrandt77.

the class PDFFilter method doExport.

public boolean doExport() {
    Document document = new Document(PageSize.A4.rotate(), 20, 20, 20, 20);
    document.addCreationDate();
    document.addCreator("jAnrufmonitor");
    try {
        PdfWriter.getInstance(document, new FileOutputStream(this.m_filename));
        document.open();
        // get renderers
        List renderer = new ArrayList();
        String renderer_config = this.getRuntime().getConfigManagerFactory().getConfigManager().getProperty("ui.jface.application.journal.Journal", "renderer");
        if (renderer_config != null && renderer_config.length() > 0) {
            StringTokenizer s = new StringTokenizer(renderer_config, ",");
            while (s.hasMoreTokens()) {
                renderer.add(RendererRegistry.getInstance().getRenderer(s.nextToken()));
            }
        }
        // get column width
        float totalWidth = 0;
        String[] cWidth = new String[renderer.size()];
        for (int i = 0, j = renderer.size(); i < j; i++) {
            cWidth[i] = getRuntime().getConfigManagerFactory().getConfigManager().getProperty("ui.jface.application.journal.Journal", "col_size_" + ((ITableCellRenderer) renderer.get(i)).getID());
            if (cWidth[i] != null && cWidth[i].length() > 0) {
                totalWidth += Float.parseFloat(cWidth[i]);
            }
            if (cWidth[i] != null && cWidth[i].length() == 0) {
                cWidth[i] = "0";
            }
        }
        float[] widths = new float[renderer.size()];
        for (int i = 0, j = renderer.size(); i < j; i++) {
            widths[i] = Float.parseFloat(cWidth[i]) / totalWidth;
        }
        PdfPTable table = new PdfPTable(widths);
        table.setHeaderRows(1);
        table.setWidthPercentage(100f);
        ITableCellRenderer t = null;
        PdfPCell cell = null;
        for (int i = 0, j = renderer.size(); i < j; i++) {
            t = (ITableCellRenderer) renderer.get(i);
            if (t == null) {
                this.m_logger.severe("No renderer found for ID: " + (String) renderer.get(i));
                this.m_logger.severe("Export to PDF format canceled...");
                return false;
            }
            cell = new PdfPCell(new Paragraph(t.getHeader()));
            cell.setBackgroundColor(new Color(0xC0, 0xC0, 0xC0));
            table.addCell(cell);
        }
        ICall c = null;
        String cellContent = null;
        for (int i = 0, j = this.m_callList.size(); i < j; i++) {
            c = this.m_callList.get(i);
            for (int k = 0, m = renderer.size(); k < m; k++) {
                t = (ITableCellRenderer) renderer.get(k);
                t.updateData(c);
                cellContent = t.renderAsText();
                if (cellContent != null && cellContent.length() > 0) {
                    table.addCell(cellContent);
                } else {
                    cellContent = t.renderAsImageID();
                    if (cellContent != null && cellContent.length() > 0) {
                        try {
                            if (cellContent.startsWith("db://")) {
                                InputStream in = ImageHandler.getInstance().getImageStream(c.getCaller());
                                if (in != null) {
                                    ByteArrayOutputStream out = new ByteArrayOutputStream();
                                    Stream.copy(in, out, true);
                                    in.close();
                                    out.close();
                                    Image pdfImage = Image.getInstance(out.toByteArray());
                                    // pdfImage.scaleAbsolute(90.0f, 45.0f);
                                    table.addCell(pdfImage);
                                } else {
                                    table.addCell(" ");
                                }
                            } else if (new File(cellContent).exists()) {
                                Image pdfImage = Image.getInstance(cellContent);
                                table.addCell(pdfImage);
                            } else {
                                Image pdfImage = Image.getInstance(SWTImageManager.getInstance(PIMRuntime.getInstance()).getImagePath(cellContent));
                                table.addCell(pdfImage);
                            }
                        } catch (IOException e) {
                            this.m_logger.severe(e.getMessage());
                            table.addCell(" ");
                        }
                    } else
                        table.addCell(" ");
                }
            }
        }
        document.add(table);
    } catch (DocumentException de) {
        this.m_logger.severe(de.getMessage());
        return false;
    } catch (IOException ioe) {
        this.m_logger.severe(ioe.getMessage());
        return false;
    } finally {
        document.close();
    }
    return true;
}
Also used : ITableCellRenderer(de.janrufmonitor.ui.jface.application.rendering.ITableCellRenderer) PdfPCell(com.lowagie.text.pdf.PdfPCell) ICall(de.janrufmonitor.framework.ICall) InputStream(java.io.InputStream) Color(java.awt.Color) ArrayList(java.util.ArrayList) ByteArrayOutputStream(java.io.ByteArrayOutputStream) IOException(java.io.IOException) Document(com.lowagie.text.Document) Image(com.lowagie.text.Image) Paragraph(com.lowagie.text.Paragraph) StringTokenizer(java.util.StringTokenizer) PdfPTable(com.lowagie.text.pdf.PdfPTable) FileOutputStream(java.io.FileOutputStream) DocumentException(com.lowagie.text.DocumentException) ICallList(de.janrufmonitor.framework.ICallList) ArrayList(java.util.ArrayList) List(java.util.List) File(java.io.File)

Example 5 with DocumentException

use of com.lowagie.text.DocumentException in project ofbiz-framework by apache.

the class CompDocServices method renderCompDocPdf.

public static Map<String, Object> renderCompDocPdf(DispatchContext dctx, Map<String, ? extends Object> context) {
    LocalDispatcher dispatcher = dctx.getDispatcher();
    Locale locale = (Locale) context.get("locale");
    String rootDir = (String) context.get("rootDir");
    String webSiteId = (String) context.get("webSiteId");
    String https = (String) context.get("https");
    Delegator delegator = dctx.getDelegator();
    String contentId = (String) context.get("contentId");
    String contentRevisionSeqId = (String) context.get("contentRevisionSeqId");
    try {
        List<EntityCondition> exprList = new LinkedList<EntityCondition>();
        exprList.add(EntityCondition.makeCondition("contentIdTo", EntityOperator.EQUALS, contentId));
        exprList.add(EntityCondition.makeCondition("contentAssocTypeId", EntityOperator.EQUALS, "COMPDOC_PART"));
        exprList.add(EntityCondition.makeCondition("rootRevisionContentId", EntityOperator.EQUALS, contentId));
        if (UtilValidate.isNotEmpty(contentRevisionSeqId)) {
            exprList.add(EntityCondition.makeCondition("contentRevisionSeqId", EntityOperator.LESS_THAN_EQUAL_TO, contentRevisionSeqId));
        }
        List<GenericValue> compDocParts = EntityQuery.use(delegator).select("rootRevisionContentId", "itemContentId", "maxRevisionSeqId", "contentId", "dataResourceId", "contentIdTo", "contentAssocTypeId", "fromDate", "sequenceNum").from("ContentAssocRevisionItemView").where(exprList).orderBy("sequenceNum").filterByDate().queryList();
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        Document document = new Document();
        document.setPageSize(PageSize.LETTER);
        PdfCopy writer = new PdfCopy(document, baos);
        document.open();
        for (GenericValue contentAssocRevisionItemView : compDocParts) {
            String thisDataResourceId = contentAssocRevisionItemView.getString("dataResourceId");
            GenericValue dataResource = EntityQuery.use(delegator).from("DataResource").where("dataResourceId", thisDataResourceId).queryOne();
            String inputMimeType = null;
            if (dataResource != null) {
                inputMimeType = dataResource.getString("mimeTypeId");
            }
            byte[] inputByteArray = null;
            PdfReader reader = null;
            if (inputMimeType != null && "application/pdf".equals(inputMimeType)) {
                ByteBuffer byteBuffer = DataResourceWorker.getContentAsByteBuffer(delegator, thisDataResourceId, https, webSiteId, locale, rootDir);
                inputByteArray = byteBuffer.array();
                reader = new PdfReader(inputByteArray);
            } else if (inputMimeType != null && "text/html".equals(inputMimeType)) {
                ByteBuffer byteBuffer = DataResourceWorker.getContentAsByteBuffer(delegator, thisDataResourceId, https, webSiteId, locale, rootDir);
                inputByteArray = byteBuffer.array();
                String s = new String(inputByteArray, "UTF-8");
                Debug.logInfo("text/html string:" + s, module);
                continue;
            } else if (inputMimeType != null && "application/vnd.ofbiz.survey.response".equals(inputMimeType)) {
                String surveyResponseId = dataResource.getString("relatedDetailId");
                String surveyId = null;
                String acroFormContentId = null;
                GenericValue surveyResponse = null;
                if (UtilValidate.isNotEmpty(surveyResponseId)) {
                    surveyResponse = EntityQuery.use(delegator).from("SurveyResponse").where("surveyResponseId", surveyResponseId).queryOne();
                    if (surveyResponse != null) {
                        surveyId = surveyResponse.getString("surveyId");
                    }
                }
                if (UtilValidate.isNotEmpty(surveyId)) {
                    GenericValue survey = EntityQuery.use(delegator).from("Survey").where("surveyId", surveyId).queryOne();
                    if (survey != null) {
                        acroFormContentId = survey.getString("acroFormContentId");
                        if (UtilValidate.isNotEmpty(acroFormContentId)) {
                        // TODO: is something supposed to be done here?
                        }
                    }
                }
                if (surveyResponse != null) {
                    if (UtilValidate.isEmpty(acroFormContentId)) {
                        // Create AcroForm PDF
                        Map<String, Object> survey2PdfResults = dispatcher.runSync("buildPdfFromSurveyResponse", UtilMisc.toMap("surveyResponseId", surveyId));
                        if (ServiceUtil.isError(survey2PdfResults)) {
                            return ServiceUtil.returnError(UtilProperties.getMessage(resource, "ContentSurveyErrorBuildingPDF", locale), null, null, survey2PdfResults);
                        }
                        ByteBuffer outByteBuffer = (ByteBuffer) survey2PdfResults.get("outByteBuffer");
                        inputByteArray = outByteBuffer.array();
                        reader = new PdfReader(inputByteArray);
                    } else {
                        // Fill in acroForm
                        Map<String, Object> survey2AcroFieldResults = dispatcher.runSync("setAcroFieldsFromSurveyResponse", UtilMisc.toMap("surveyResponseId", surveyResponseId));
                        if (ServiceUtil.isError(survey2AcroFieldResults)) {
                            return ServiceUtil.returnError(UtilProperties.getMessage(resource, "ContentSurveyErrorSettingAcroFields", locale), null, null, survey2AcroFieldResults);
                        }
                        ByteBuffer outByteBuffer = (ByteBuffer) survey2AcroFieldResults.get("outByteBuffer");
                        inputByteArray = outByteBuffer.array();
                        reader = new PdfReader(inputByteArray);
                    }
                }
            } else {
                return ServiceUtil.returnError(UtilProperties.getMessage(resource, "ContentMimeTypeNotSupported", locale));
            }
            if (reader != null) {
                int n = reader.getNumberOfPages();
                for (int i = 0; i < n; i++) {
                    PdfImportedPage pg = writer.getImportedPage(reader, i + 1);
                    writer.addPage(pg);
                }
            }
        }
        document.close();
        ByteBuffer outByteBuffer = ByteBuffer.wrap(baos.toByteArray());
        Map<String, Object> results = ServiceUtil.returnSuccess();
        results.put("outByteBuffer", outByteBuffer);
        return results;
    } catch (GenericEntityException e) {
        return ServiceUtil.returnError(e.toString());
    } catch (IOException | DocumentException | GeneralException e) {
        Debug.logError(e, "Error in CompDoc operation: ", module);
        return ServiceUtil.returnError(e.toString());
    }
}
Also used : Locale(java.util.Locale) GenericValue(org.apache.ofbiz.entity.GenericValue) LocalDispatcher(org.apache.ofbiz.service.LocalDispatcher) GeneralException(org.apache.ofbiz.base.util.GeneralException) EntityCondition(org.apache.ofbiz.entity.condition.EntityCondition) ByteArrayOutputStream(java.io.ByteArrayOutputStream) PdfReader(com.lowagie.text.pdf.PdfReader) IOException(java.io.IOException) Document(com.lowagie.text.Document) ByteBuffer(java.nio.ByteBuffer) LinkedList(java.util.LinkedList) PdfImportedPage(com.lowagie.text.pdf.PdfImportedPage) PdfCopy(com.lowagie.text.pdf.PdfCopy) Delegator(org.apache.ofbiz.entity.Delegator) GenericEntityException(org.apache.ofbiz.entity.GenericEntityException) DocumentException(com.lowagie.text.DocumentException)

Aggregations

DocumentException (com.lowagie.text.DocumentException)34 Document (com.lowagie.text.Document)19 IOException (java.io.IOException)15 ByteArrayOutputStream (java.io.ByteArrayOutputStream)13 Paragraph (com.lowagie.text.Paragraph)12 Color (java.awt.Color)9 PdfContentByte (com.lowagie.text.pdf.PdfContentByte)7 PdfReader (com.lowagie.text.pdf.PdfReader)7 ByteBuffer (java.nio.ByteBuffer)6 Delegator (org.apache.ofbiz.entity.Delegator)6 Chunk (com.lowagie.text.Chunk)5 Phrase (com.lowagie.text.Phrase)5 Section (com.lowagie.text.Section)5 PdfObject (com.lowagie.text.pdf.PdfObject)5 PdfWriter (com.lowagie.text.pdf.PdfWriter)5 GeneralException (org.apache.ofbiz.base.util.GeneralException)5 ExpressionException (cbit.vcell.parser.ExpressionException)4 AcroFields (com.lowagie.text.pdf.AcroFields)4 PdfStamper (com.lowagie.text.pdf.PdfStamper)4 File (java.io.File)4