Search in sources :

Example 21 with DocumentException

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

the class PdfSurveyServices method buildSurveyResponseFromPdf.

/**
 */
public static Map<String, Object> buildSurveyResponseFromPdf(DispatchContext dctx, Map<String, ? extends Object> context) {
    String surveyResponseId = null;
    Locale locale = (Locale) context.get("locale");
    try {
        Delegator delegator = dctx.getDelegator();
        String partyId = (String) context.get("partyId");
        String surveyId = (String) context.get("surveyId");
        surveyResponseId = (String) context.get("surveyResponseId");
        if (UtilValidate.isNotEmpty(surveyResponseId)) {
            GenericValue surveyResponse = EntityQuery.use(delegator).from("SurveyResponse").where("surveyResponseId", surveyResponseId).queryOne();
            if (surveyResponse != null) {
                surveyId = surveyResponse.getString("surveyId");
            }
        } else {
            surveyResponseId = delegator.getNextSeqId("SurveyResponse");
            GenericValue surveyResponse = delegator.makeValue("SurveyResponse", UtilMisc.toMap("surveyResponseId", surveyResponseId, "surveyId", surveyId, "partyId", partyId));
            surveyResponse.set("responseDate", UtilDateTime.nowTimestamp());
            surveyResponse.set("lastModifiedDate", UtilDateTime.nowTimestamp());
            surveyResponse.create();
        }
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        ByteBuffer byteBuffer = getInputByteBuffer(context, delegator);
        PdfReader r = new PdfReader(byteBuffer.array());
        PdfStamper s = new PdfStamper(r, os);
        AcroFields fs = s.getAcroFields();
        Map<String, Object> hm = UtilGenerics.checkMap(fs.getFields());
        s.setFormFlattening(true);
        for (String fieldName : hm.keySet()) {
            // AcroFields.Item item = fs.getFieldItem(fieldName);
            String value = fs.getField(fieldName);
            GenericValue surveyQuestionAndAppl = EntityQuery.use(delegator).from("SurveyQuestionAndAppl").where("surveyId", surveyId, "externalFieldRef", fieldName).queryFirst();
            if (surveyQuestionAndAppl == null) {
                Debug.logInfo("No question found for surveyId:" + surveyId + " and externalFieldRef:" + fieldName, module);
                continue;
            }
            String surveyQuestionId = (String) surveyQuestionAndAppl.get("surveyQuestionId");
            String surveyQuestionTypeId = (String) surveyQuestionAndAppl.get("surveyQuestionTypeId");
            GenericValue surveyResponseAnswer = delegator.makeValue("SurveyResponseAnswer", UtilMisc.toMap("surveyResponseId", surveyResponseId, "surveyQuestionId", surveyQuestionId));
            if (surveyQuestionTypeId == null || "TEXT_SHORT".equals(surveyQuestionTypeId)) {
                surveyResponseAnswer.set("textResponse", value);
            }
            delegator.create(surveyResponseAnswer);
        }
        s.close();
    } catch (GeneralException | DocumentException | IOException e) {
        Debug.logError(e, "Error generating PDF: " + e.toString(), module);
        return ServiceUtil.returnError(UtilProperties.getMessage(resource, "ContentPDFGeneratingError", UtilMisc.toMap("errorString", e.toString()), locale));
    }
    Map<String, Object> results = ServiceUtil.returnSuccess();
    results.put("surveyResponseId", surveyResponseId);
    return results;
}
Also used : Locale(java.util.Locale) GenericValue(org.apache.ofbiz.entity.GenericValue) GeneralException(org.apache.ofbiz.base.util.GeneralException) ByteArrayOutputStream(java.io.ByteArrayOutputStream) PdfReader(com.lowagie.text.pdf.PdfReader) IOException(java.io.IOException) ByteBuffer(java.nio.ByteBuffer) Delegator(org.apache.ofbiz.entity.Delegator) PdfStamper(com.lowagie.text.pdf.PdfStamper) DocumentException(com.lowagie.text.DocumentException) AcroFields(com.lowagie.text.pdf.AcroFields) PdfObject(com.lowagie.text.pdf.PdfObject)

Example 22 with DocumentException

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

the class PdfSurveyServices method buildPdfFromSurveyResponse.

/**
 */
public static Map<String, Object> buildPdfFromSurveyResponse(DispatchContext dctx, Map<String, ? extends Object> rcontext) {
    Map<String, Object> context = UtilMisc.makeMapWritable(rcontext);
    Delegator delegator = dctx.getDelegator();
    Map<String, Object> results = ServiceUtil.returnSuccess();
    String surveyResponseId = (String) context.get("surveyResponseId");
    String contentId = (String) context.get("contentId");
    String surveyId = null;
    Document document = new Document();
    try {
        if (UtilValidate.isNotEmpty(surveyResponseId)) {
            GenericValue surveyResponse = EntityQuery.use(delegator).from("SurveyResponse").where("surveyResponseId", surveyResponseId).queryOne();
            if (surveyResponse != null) {
                surveyId = surveyResponse.getString("surveyId");
            }
        }
        if (UtilValidate.isNotEmpty(surveyId) && UtilValidate.isEmpty(contentId)) {
            GenericValue survey = EntityQuery.use(delegator).from("Survey").where("surveyId", surveyId).queryOne();
            if (survey != null) {
                String acroFormContentId = survey.getString("acroFormContentId");
                if (UtilValidate.isNotEmpty(acroFormContentId)) {
                    context.put("contentId", acroFormContentId);
                }
            }
        }
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        PdfWriter.getInstance(document, baos);
        List<GenericValue> responses = EntityQuery.use(delegator).from("SurveyResponseAnswer").where("surveyResponseId", surveyResponseId).queryList();
        for (GenericValue surveyResponseAnswer : responses) {
            String value = null;
            String surveyQuestionId = (String) surveyResponseAnswer.get("surveyQuestionId");
            GenericValue surveyQuestion = EntityQuery.use(delegator).from("SurveyQuestion").where("surveyQuestionId", surveyQuestionId).queryOne();
            String questionType = surveyQuestion.getString("surveyQuestionTypeId");
            // DEJ20060227 this isn't used, if needed in the future should get from SurveyQuestionAppl.externalFieldRef String fieldName = surveyQuestion.getString("description");
            if ("OPTION".equals(questionType)) {
                value = surveyResponseAnswer.getString("surveyOptionSeqId");
            } else if ("BOOLEAN".equals(questionType)) {
                value = surveyResponseAnswer.getString("booleanResponse");
            } else if ("NUMBER_LONG".equals(questionType) || "NUMBER_CURRENCY".equals(questionType) || "NUMBER_FLOAT".equals(questionType)) {
                Double num = surveyResponseAnswer.getDouble("numericResponse");
                if (num != null) {
                    value = num.toString();
                }
            } else if ("SEPERATOR_LINE".equals(questionType) || "SEPERATOR_TEXT".equals(questionType)) {
            // not really a question; ingore completely
            } else {
                value = surveyResponseAnswer.getString("textResponse");
            }
            Chunk chunk = new Chunk(surveyQuestion.getString("question") + ": " + value);
            Paragraph p = new Paragraph(chunk);
            document.add(p);
        }
        ByteBuffer outByteBuffer = ByteBuffer.wrap(baos.toByteArray());
        results.put("outByteBuffer", outByteBuffer);
    } catch (GenericEntityException | DocumentException e) {
        Debug.logError(e, module);
        results = ServiceUtil.returnError(e.getMessage());
    }
    return results;
}
Also used : GenericValue(org.apache.ofbiz.entity.GenericValue) ByteArrayOutputStream(java.io.ByteArrayOutputStream) Document(com.lowagie.text.Document) Chunk(com.lowagie.text.Chunk) ByteBuffer(java.nio.ByteBuffer) Paragraph(com.lowagie.text.Paragraph) Delegator(org.apache.ofbiz.entity.Delegator) GenericEntityException(org.apache.ofbiz.entity.GenericEntityException) DocumentException(com.lowagie.text.DocumentException) PdfObject(com.lowagie.text.pdf.PdfObject)

Example 23 with DocumentException

use of com.lowagie.text.DocumentException in project jaffa-framework by jaffa-projects.

the class PdfHelper method scalePdfPages.

/**
 * Scale the pages of the input pdfOutput document to the given pageSize.
 * @param pdfOutput The PDF document to rescale, in the form of a ByteArrayOutputStream.
 * @param pageSize The new page size to which to scale to PDF document, e.g. "A4".
 * @param noEnlarge If true, center pages instead of enlarging them.
 *        Use noEnlarge if the new page size is larger than the old one
 *        and the pages should be centered instead of enlarged.
 * @param preserveAspectRatio If true, the aspect ratio will be preserved.
 * @return The PDF document with its pages scaled to the input pageSize.
 */
public static byte[] scalePdfPages(byte[] pdfOutput, String pageSize, boolean noEnlarge, boolean preserveAspectRatio) throws FormPrintException {
    if (pageSize == null || pdfOutput == null) {
        return pdfOutput;
    }
    // Get the dimensions of the given pageSize in PostScript points.
    // A PostScript point is a 72th of an inch.
    float dimX;
    float dimY;
    Rectangle rectangle;
    try {
        rectangle = PageSize.getRectangle(pageSize);
    } catch (Exception ex) {
        FormPrintException e = new PdfProcessingException("scalePdfPages  - Invalid page size = " + pageSize + "  ");
        log.error(" scalePdfPages  - Invalid page size: " + pageSize + ".  " + ex.getMessage() + ". ");
        throw e;
    }
    if (rectangle != null) {
        dimX = rectangle.getWidth();
        dimY = rectangle.getHeight();
    } else {
        FormPrintException e = new PdfProcessingException("scalePdfPages  - Invalid page size: " + pageSize);
        log.error(" scalePdfPages  - Invalid page size: " + pageSize);
        throw e;
    }
    // Create portrait and landscape rectangles for the given page size.
    Rectangle portraitPageSize;
    Rectangle landscapePageSize;
    if (dimY > dimX) {
        portraitPageSize = new Rectangle(dimX, dimY);
        landscapePageSize = new Rectangle(dimY, dimX);
    } else {
        portraitPageSize = new Rectangle(dimY, dimX);
        landscapePageSize = new Rectangle(dimX, dimY);
    }
    // Remove the document rotation before resizing the document.
    byte[] output = removeRotation(pdfOutput);
    PdfReader currentReader = null;
    try {
        currentReader = new PdfReader(output);
    } catch (IOException ex) {
        FormPrintException e = new PdfProcessingException("scalePdfPages  - Failed to create a PDF Reader");
        log.error(" scalePdfPages  - Failed to create a PDF Reader ");
        throw e;
    }
    OutputStream baos = new ByteArrayOutputStream();
    Rectangle newSize = new Rectangle(dimX, dimY);
    Document document = new Document(newSize, 0, 0, 0, 0);
    PdfWriter writer = null;
    try {
        writer = PdfWriter.getInstance(document, baos);
    } catch (DocumentException ex) {
        FormPrintException e = new PdfProcessingException("scalePdfPages  - Failed to create a PDF Writer");
        log.error(" scalePdfPages  - Failed to create a PDF Writer ");
        throw e;
    }
    document.open();
    PdfContentByte cb = writer.getDirectContent();
    PdfImportedPage page;
    float offsetX, offsetY;
    for (int i = 1; i <= currentReader.getNumberOfPages(); i++) {
        Rectangle currentSize = currentReader.getPageSizeWithRotation(i);
        if (currentReader.getPageRotation(i) != 0) {
            FormPrintException e = new PdfProcessingException("Page Rotation, " + currentReader.getPageRotation(i) + ", must be removed to re-scale the form.");
            log.error(" Page Rotation, " + currentReader.getPageRotation(i) + ", must be removed to re-scale the form. ");
            throw e;
        }
        // Reset the page size for each page because there may be a mix of sizes in the document.
        float currentWidth = currentSize.getWidth();
        float currentHeight = currentSize.getHeight();
        if (currentWidth > currentHeight) {
            newSize = landscapePageSize;
        } else {
            newSize = portraitPageSize;
        }
        document.setPageSize(newSize);
        document.newPage();
        float factorX = newSize.getWidth() / currentSize.getWidth();
        float factorY = newSize.getHeight() / currentSize.getHeight();
        // and the pages should be centered instead of enlarged.
        if (noEnlarge) {
            if (factorX > 1) {
                factorX = 1;
            }
            if (factorY > 1) {
                factorY = 1;
            }
        }
        if (preserveAspectRatio) {
            factorX = Math.min(factorX, factorY);
            factorY = factorX;
        }
        offsetX = (newSize.getWidth() - (currentSize.getWidth() * factorX)) / 2f;
        offsetY = (newSize.getHeight() - (currentSize.getHeight() * factorY)) / 2f;
        page = writer.getImportedPage(currentReader, i);
        cb.addTemplate(page, factorX, 0, 0, factorY, offsetX, offsetY);
    }
    document.close();
    return ((ByteArrayOutputStream) baos).toByteArray();
}
Also used : PdfProcessingException(org.jaffa.modules.printing.services.exceptions.PdfProcessingException) PdfWriter(com.lowagie.text.pdf.PdfWriter) OutputStream(java.io.OutputStream) ByteArrayOutputStream(java.io.ByteArrayOutputStream) Rectangle(com.lowagie.text.Rectangle) PdfReader(com.lowagie.text.pdf.PdfReader) IOException(java.io.IOException) ByteArrayOutputStream(java.io.ByteArrayOutputStream) Document(com.lowagie.text.Document) IOException(java.io.IOException) DocumentException(com.lowagie.text.DocumentException) PdfProcessingException(org.jaffa.modules.printing.services.exceptions.PdfProcessingException) FormPrintException(org.jaffa.modules.printing.services.exceptions.FormPrintException) PdfImportedPage(com.lowagie.text.pdf.PdfImportedPage) DocumentException(com.lowagie.text.DocumentException) FormPrintException(org.jaffa.modules.printing.services.exceptions.FormPrintException) PdfContentByte(com.lowagie.text.pdf.PdfContentByte)

Example 24 with DocumentException

use of com.lowagie.text.DocumentException in project jaffa-framework by jaffa-projects.

the class FormPrintEngineIText method startDocument.

/**
 * Any work to start off printing the document
 * @throws FormPrintException Thrown if there is any form processing problems
 */
protected void startDocument() throws FormPrintException {
    log.debug("startDocument:");
    Rectangle r = m_templateReader.getPageSize(getCurrentTemplatePage());
    log.debug("Page Size      : t=" + r.getTop() + ",l=" + r.getLeft() + ",b=" + r.getBottom() + ",r=" + r.getRight() + ", rot=" + r.getRotation());
    r = m_templateReader.getPageSizeWithRotation(getCurrentTemplatePage());
    log.debug("Page Size w/Rot: t=" + r.getTop() + ",l=" + r.getLeft() + ",b=" + r.getBottom() + ",r=" + r.getRight() + ", rot=" + r.getRotation());
    m_generatedDoc = new Document(m_templateReader.getPageSizeWithRotation(getCurrentTemplatePage()));
    // m_generatedDoc = new Document(m_templateReader.getPageSize(getCurrentTemplatePage()));
    m_output = new ByteArrayOutputStream();
    try {
        m_writer = PdfWriter.getInstance(m_generatedDoc, m_output);
    } catch (DocumentException e) {
        log.error("Error Creating Writer - " + e.getMessage(), e);
        throw new EngineProcessingException("Error Creating Writer - " + e.getMessage());
    }
    if (getDocumentProperties() != null) {
        Properties dp = (Properties) getDocumentProperties().clone();
        if (dp.getProperty(DOCUMENT_PROPERTY_TITLE) != null) {
            m_generatedDoc.addTitle(dp.getProperty(DOCUMENT_PROPERTY_TITLE));
            dp.remove(DOCUMENT_PROPERTY_TITLE);
        }
        if (dp.getProperty(DOCUMENT_PROPERTY_SUBJECT) != null) {
            m_generatedDoc.addSubject(dp.getProperty(DOCUMENT_PROPERTY_SUBJECT));
            dp.remove(DOCUMENT_PROPERTY_SUBJECT);
        }
        if (dp.getProperty(DOCUMENT_PROPERTY_KEYWORDS) != null) {
            m_generatedDoc.addKeywords(dp.getProperty(DOCUMENT_PROPERTY_KEYWORDS));
            dp.remove(DOCUMENT_PROPERTY_KEYWORDS);
        }
        if (dp.getProperty(DOCUMENT_PROPERTY_CREATOR) != null) {
            m_generatedDoc.addCreator(dp.getProperty(DOCUMENT_PROPERTY_CREATOR, "Jaffa Print Engine"));
            dp.remove(DOCUMENT_PROPERTY_CREATOR);
        }
        if (dp.getProperty(DOCUMENT_PROPERTY_AUTHOR) != null) {
            m_generatedDoc.addAuthor(dp.getProperty(DOCUMENT_PROPERTY_AUTHOR));
            dp.remove(DOCUMENT_PROPERTY_AUTHOR);
        }
        // loop through other properties and set them as header parameters
        for (Enumeration en = dp.elements(); en.hasMoreElements(); ) {
            Map.Entry e = (Map.Entry) en.nextElement();
            if (e.getKey() != null && e.getValue() != null)
                m_generatedDoc.addHeader(e.getKey().toString(), e.getValue().toString());
        }
    }
    m_generatedDoc.addCreationDate();
    m_generatedDoc.open();
}
Also used : Enumeration(java.util.Enumeration) DocumentException(com.lowagie.text.DocumentException) Rectangle(com.lowagie.text.Rectangle) ByteArrayOutputStream(java.io.ByteArrayOutputStream) Document(com.lowagie.text.Document) Properties(java.util.Properties) HashMap(java.util.HashMap) Map(java.util.Map) EngineProcessingException(org.jaffa.modules.printing.services.exceptions.EngineProcessingException)

Example 25 with DocumentException

use of com.lowagie.text.DocumentException in project vcell by virtualcell.

the class ITextWriter method writeStructure.

protected void writeStructure(Model model, Structure struct, Table structTable) throws DocumentException {
    // If this structure has any reactions in it, add its name as a hyperlink to the reactions' list.
    if (hasReactions(model, struct)) {
        Paragraph linkParagraph = new Paragraph();
        Font linkFont;
        try {
            BaseFont fontBaseFont = BaseFont.createFont(BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.NOT_EMBEDDED);
            linkFont = new Font(fontBaseFont, DEF_FONT_SIZE, Font.NORMAL, new java.awt.Color(0, 0, 255));
        } catch (Exception e) {
            linkFont = getFont();
            e.printStackTrace();
        }
        linkParagraph.add(new Chunk(struct.getName(), linkFont).setLocalGoto(struct.getName()));
        Cell structLinkCell = new Cell(linkParagraph);
        structLinkCell.setBorderWidth(1);
        structLinkCell.setHorizontalAlignment(Element.ALIGN_LEFT);
        structTable.addCell(structLinkCell);
    } else {
        structTable.addCell(createCell(struct.getName(), getFont()));
    }
    StructureTopology structTopology = model.getStructureTopology();
    if (struct instanceof Membrane) {
        structTable.addCell(createCell("Membrane", getFont()));
        Feature outsideFeature = structTopology.getOutsideFeature((Membrane) struct);
        Feature insideFeature = structTopology.getInsideFeature((Membrane) struct);
        structTable.addCell(createCell((insideFeature != null ? insideFeature.getName() : "N/A"), getFont()));
        structTable.addCell(createCell((outsideFeature != null ? outsideFeature.getName() : "N/A"), getFont()));
    } else {
        structTable.addCell(createCell("Feature", getFont()));
        String outsideStr = "N/A", insideStr = "N/A";
        Membrane enclosingMem = (Membrane) structTopology.getParentStructure(struct);
        if (enclosingMem != null) {
            outsideStr = enclosingMem.getName();
        }
        // To do:  retrieve the 'child' membrane here...
        structTable.addCell(createCell(insideStr, getFont()));
        structTable.addCell(createCell(outsideStr, getFont()));
    }
}
Also used : StructureTopology(cbit.vcell.model.Model.StructureTopology) Color(java.awt.Color) BaseFont(com.lowagie.text.pdf.BaseFont) Membrane(cbit.vcell.model.Membrane) Chunk(com.lowagie.text.Chunk) Cell(com.lowagie.text.Cell) Feature(cbit.vcell.model.Feature) BaseFont(com.lowagie.text.pdf.BaseFont) Font(com.lowagie.text.Font) DocumentException(com.lowagie.text.DocumentException) ExpressionException(cbit.vcell.parser.ExpressionException) Paragraph(com.lowagie.text.Paragraph)

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