Search in sources :

Example 11 with DocumentException

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

the class FormPrintEngineIText method fillPageFields.

/**
 * This will fill in the page with data,
 * m_currentPageData contains the details of the current page being printed
 * @throws FormPrintException Thrown if there is any form processing problems
 */
protected void fillPageFields() throws FormPrintException {
    log.debug("fillPageFields: Page=" + getCurrentPage());
    try {
        PdfContentByte cb = m_writer.getDirectContent();
        PageDetailsExtended page = (PageDetailsExtended) getCurrentPageData();
        // Loop through each field to be inserted
        for (Iterator i = page.fieldList.iterator(); i.hasNext(); ) {
            String fieldname = (String) i.next();
            // Get the properties for displaying this field
            FieldProperties props = (FieldProperties) page.fieldProperties.get(fieldname);
            // Get the data to display
            FormPrintEngine.DomValue data = new FormPrintEngine.DomValue(fieldname, props.sampleData);
            // Caluclate Clipping Region
            float x1 = Math.min(props.x1, props.x2);
            float x2 = Math.max(props.x1, props.x2);
            float y1 = Math.min(props.y1, props.y2);
            float y2 = Math.max(props.y1, props.y2);
            float w = Math.abs(props.x1 - props.x2) + 1;
            float h = Math.abs(props.y1 - props.y2) + 1;
            if (log.isDebugEnabled())
                log.debug("Print Field " + fieldname + "=" + data.getObject() + " @ [(" + x1 + "," + y1 + ")->(" + x2 + "," + y2 + ")]");
            // Default the font if not specified
            String font = BaseFont.HELVETICA;
            if (props.fontFace != null)
                font = props.fontFace;
            // Handle Barcodes diffently withing iText, don't just use fonts
            if (font.startsWith("Barcode")) {
                String bcClassName = "com.lowagie.text.pdf." + font;
                Object bcode = null;
                String dataStr = data.getValue();
                if (dataStr != null) {
                    log.debug("Barcode Data String = " + dataStr);
                    // Try and create the correct Barcode Object
                    try {
                        Class bcClass = Class.forName(bcClassName);
                        bcode = bcClass.newInstance();
                    } catch (Exception e) {
                        String err = "Can't Create Barcode Object for barcode type '" + font + "' on field " + fieldname;
                        log.error(err, e);
                    }
                    // Only continue if the barcode object was created
                    if (bcode != null) {
                        // Generate and Print barcode, based on common interface
                        if (bcode instanceof Barcode) {
                            Barcode b = (Barcode) bcode;
                            // Set some default output a barcode
                            b.setCode(dataStr);
                            if (props.fontSize <= 0) {
                                // Hide text if font size is 0, and make the barcode height the size of the box
                                b.setBarHeight(h);
                                b.setFont(null);
                            } else {
                                // size of text under barcode
                                b.setSize(props.fontSize);
                                // Adjust Bar Height to allow for font size
                                b.setBarHeight(h - props.fontSize - 5);
                            }
                            // Wide Bars
                            b.setN(2);
                            // Set custom parameters
                            setBarcodeParams(fieldname, bcode, props.style);
                            // Print out barcode
                            Image image = ((Barcode) bcode).createImageWithBarcode(cb, null, null);
                            printImage(image, cb, x1, y1, x2, y2, props.align, props.fitMethod, props.rotate);
                        } else // Print PDF417 barcode, not based on common interface
                        if (bcode instanceof BarcodePDF417) {
                            BarcodePDF417 b = (BarcodePDF417) bcode;
                            // Set some default output a barcode
                            b.setText(dataStr);
                            b.setErrorLevel(5);
                            // Set custom parameters
                            setBarcodeParams(fieldname, bcode, props.style);
                            log.debug("PDF417 Settings\n" + "BitColumns=" + b.getBitColumns() + "\n" + "CodeColumns=" + b.getCodeColumns() + "\n" + "CodeRows=" + b.getCodeRows() + "\n" + "ErrorLevel=" + b.getErrorLevel() + "\n" + "YHeight=" + b.getYHeight() + "\n" + "AspectRatio=" + b.getAspectRatio() + "\n" + "Options=" + b.getOptions() + "\n" + "LenCodewords=" + b.getLenCodewords());
                            // Print out barcode
                            // image = b.getImage();
                            printImage(b.getImage(), cb, x1, y1, x2, y2, props.align, props.fitMethod, props.rotate);
                        } else {
                            // Error, unknown barcode
                            String err = "Error, No print handler for barcode object " + bcode.getClass().getName();
                            log.error(err);
                        // throw new EngineProcessingException(err);
                        }
                    }
                } else
                    log.debug("SKIPPED BARCODE : No data for " + fieldname);
            // Handle Images differently within iText, native support for JFreeChart
            } else if ("image".equalsIgnoreCase(font)) {
                try {
                    java.awt.Image image = data.getDomImage();
                    // Add an image to the page
                    if (image != null) {
                        if (fieldname.startsWith("watermark")) {
                            // Add an image-based watermark to the under content layer
                            PdfContentByte contentUnder = m_writer.getDirectContentUnder();
                            if (props.opacity != 1f) {
                                PdfGState gs = new PdfGState();
                                gs.setFillOpacity(props.opacity);
                                contentUnder.setGState(gs);
                            }
                            printImage(image, contentUnder, x1, y1, x2, y2, props.align, props.fitMethod, props.rotate);
                        } else {
                            // Add an image to main page layer
                            printImage(image, cb, x1, y1, x2, y2, props.align, props.fitMethod, props.rotate);
                        }
                    }
                } catch (IOException e) {
                    // Add Error on page.
                    Phrase text = new Phrase("Image Error", FontFactory.getFont(FontFactory.HELVETICA_BOLDOBLIQUE, 8f, 0, ColorHelper.getColor("red")));
                    ColumnText ct = new ColumnText(cb);
                    ct.setSimpleColumn(text, x1, y1, x2, y2, 8f, Element.ALIGN_LEFT);
                }
            } else if (fieldname.startsWith("watermark")) {
                // Add a text-based watermark
                String text = data.getValue();
                PdfContentByte contentUnder = m_writer.getDirectContentUnder();
                if (props.opacity != 1f) {
                    PdfGState gs = new PdfGState();
                    gs.setFillOpacity(props.opacity);
                    contentUnder.setGState(gs);
                }
                // The text aligns (left, center, right) on the pivot point.
                // Default to align left.
                float pivotX = x1;
                float pivotY = y1;
                if (Element.ALIGN_CENTER == props.align) {
                    pivotX = (x1 / 2) + (x2 / 2);
                    pivotY = y1;
                } else if (Element.ALIGN_RIGHT == props.align) {
                    pivotX = x2;
                    pivotY = y1;
                }
                Phrase watermark = new Phrase(text, FontFactory.getFont(props.fontFace, props.fontSize, decodeFontStyle(props.style), ColorHelper.getColor(defaultWatermarkColor)));
                ColumnText.showTextAligned(contentUnder, props.align, watermark, pivotX, pivotY, props.rotate);
            } else {
                // Handle printing of basic Text
                float lineHeight = props.fontSize;
                String str = data.getValue();
                if (str != null) {
                    // Add a bounded column to add text to.
                    Phrase text = new Phrase(str, FontFactory.getFont(props.fontFace, props.fontSize, decodeFontStyle(props.style), ColorHelper.getColor(props.color)));
                    ColumnText ct = new ColumnText(cb);
                    if (props.fitMethod == FIT_METHOD_CLIP)
                        // set up column with height/width restrictions
                        ct.setSimpleColumn(text, x1, y1, x2, y2, lineHeight, props.align);
                    else
                        // set up column without (i.e. large) height/width restrictions
                        ct.setSimpleColumn(text, x1, y1, 1000, 0, lineHeight, props.align);
                    ct.go();
                }
            }
            // Draw outline boxes arround fields
            if (isTemplateMode()) {
                cb.setLineWidth(0.5f);
                cb.setLineDash(4f, 2f);
                cb.setColorStroke(new Color(0xA0, 0xA0, 0xA0));
                cb.moveTo(x1, y1);
                cb.lineTo(x1, y2);
                cb.lineTo(x2, y2);
                cb.lineTo(x2, y1);
                cb.lineTo(x1, y1);
                cb.stroke();
            }
        }
    // end for-loop
    } catch (DocumentException e) {
        String err = "Error printing data - " + e.getMessage();
        log.error(err, e);
        throw new EngineProcessingException(err);
    // } catch (IOException e) {
    // String err = "Error printing data - " + e.getMessage();
    // log.error(err ,e);
    // throw new EngineProcessingException(err);
    }
}
Also used : BarcodePDF417(com.lowagie.text.pdf.BarcodePDF417) Color(java.awt.Color) IOException(java.io.IOException) Phrase(com.lowagie.text.Phrase) Image(com.lowagie.text.Image) BadElementException(com.lowagie.text.BadElementException) EngineProcessingException(org.jaffa.modules.printing.services.exceptions.EngineProcessingException) IOException(java.io.IOException) DocumentException(com.lowagie.text.DocumentException) FileNotFoundException(java.io.FileNotFoundException) FormPrintException(org.jaffa.modules.printing.services.exceptions.FormPrintException) EngineProcessingException(org.jaffa.modules.printing.services.exceptions.EngineProcessingException) ColumnText(com.lowagie.text.pdf.ColumnText) Barcode(com.lowagie.text.pdf.Barcode) DocumentException(com.lowagie.text.DocumentException) Iterator(java.util.Iterator) PdfContentByte(com.lowagie.text.pdf.PdfContentByte) PdfGState(com.lowagie.text.pdf.PdfGState)

Example 12 with DocumentException

use of com.lowagie.text.DocumentException in project charts by vaadin.

the class PdfExportDemo method writePdf.

/**
 * Writes a PDF file with some static example content plus embeds the chart
 * SVG.
 *
 * @param pdffilename
 *            PDF's filename
 * @param svg
 *            SVG as a String
 * @return PDF File
 */
public File writePdf(String pdffilename, String svg) {
    svgStr = svg;
    document = new Document();
    document.addTitle("PDF Sample");
    document.addCreator("Vaadin");
    initFonts();
    File file = null;
    try {
        file = writeToFile(pdffilename, document);
        document.open();
        writePdfContent();
        document.close();
    } catch (DocumentException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return file;
}
Also used : DocumentException(com.lowagie.text.DocumentException) IOException(java.io.IOException) SVGDocument(org.w3c.dom.svg.SVGDocument) Document(com.lowagie.text.Document) File(java.io.File)

Example 13 with DocumentException

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

the class ITextWriter method writeGeometry.

// for now, the preferences for a geometry is a dummy.
public void writeGeometry(Geometry geom, FileOutputStream fos, PageFormat pageFormat, PublishPreferences preferences) throws Exception {
    if (geom == null || fos == null || pageFormat == null || preferences == null) {
        throw new IllegalArgumentException("One or more null params while publishing Geometry.");
    }
    try {
        createDocument(pageFormat);
        createDocWriter(fos);
        // Add metadata before you open the document...
        String name = geom.getName().trim();
        String userName = "Unknown";
        if (geom.getVersion() != null) {
            userName = geom.getVersion().getOwner().getName();
        }
        document.addTitle(name + "[owned by " + userName + "]");
        document.addCreator("Virtual Cell");
        document.addCreationDate();
        // writeWatermark(document, pageFormat);
        writeHeaderFooter("Geometry: " + name);
        document.open();
        // 
        Section introSection = null;
        int chapterNum = 1;
        Chapter geomChapter = new Chapter("Geometry", chapterNum++);
        introSection = geomChapter.addSection("General Info", geomChapter.numberDepth() + 1);
        writeMetadata(introSection, name, geom.getDescription(), userName, "Geometry");
        // title?
        Section geomSection = geomChapter.addSection("Geometry", geomChapter.numberDepth() + 1);
        writeGeom(geomSection, geom, null);
        document.add(geomChapter);
        document.close();
    } catch (DocumentException e) {
        System.err.println("Unable to publish BioModel.");
        e.printStackTrace();
        throw e;
    }
}
Also used : DocumentException(com.lowagie.text.DocumentException) Chapter(com.lowagie.text.Chapter) Section(com.lowagie.text.Section)

Example 14 with DocumentException

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

the class ITextWriter method writeMathDescAsImages.

// container can be a chapter or a section of a chapter.
// MathDescription.description ignored.
// currently not used.
protected void writeMathDescAsImages(Section container, MathDescription mathDesc) throws DocumentException {
    if (mathDesc == null) {
        return;
    }
    Section mathDescSection = container.addSection("Math Description: " + mathDesc.getName(), container.depth() + 1);
    Section mathDescSubSection = null;
    Expression[] expArray = null;
    BufferedImage dummy = new BufferedImage(500, 50, BufferedImage.TYPE_3BYTE_BGR);
    int scale = 1;
    int viewableWidth = (int) (document.getPageSize().width() - document.leftMargin() - document.rightMargin());
    // add Constants
    Enumeration<Constant> constantsList = mathDesc.getConstants();
    while (constantsList.hasMoreElements()) {
        Constant constant = constantsList.nextElement();
        Expression exp = constant.getExpression();
        try {
            expArray = new Expression[] { Expression.assign(new Expression(constant.getName()), exp.flatten()) };
        } catch (ExpressionException ee) {
            System.err.println("Unable to process constant " + constant.getName() + " for publishing");
            ee.printStackTrace();
            continue;
        }
        try {
            Dimension dim = ExpressionCanvas.getExpressionImageSize(expArray, (Graphics2D) dummy.getGraphics());
            BufferedImage bufferedImage = new BufferedImage((int) dim.getWidth() * scale, (int) dim.getHeight() * scale, BufferedImage.TYPE_3BYTE_BGR);
            ExpressionCanvas.getExpressionAsImage(expArray, bufferedImage, scale);
            com.lowagie.text.Image expImage = com.lowagie.text.Image.getInstance(bufferedImage, null);
            expImage.setAlignment(com.lowagie.text.Image.ALIGN_LEFT);
            if (mathDescSubSection == null) {
                mathDescSubSection = mathDescSection.addSection("Constants", mathDescSection.depth() + 1);
            }
            if (viewableWidth < Math.floor(expImage.scaledWidth())) {
                expImage.scaleToFit(viewableWidth, expImage.plainHeight());
                System.out.println("Constant After scaling: " + expImage.scaledWidth());
            }
            mathDescSubSection.add(expImage);
        } catch (Exception e) {
            System.err.println("Unable to add structure mapping image to report.");
            e.printStackTrace();
        }
    }
    mathDescSubSection = null;
    // add functions
    Enumeration<Function> functionsList = mathDesc.getFunctions();
    while (functionsList.hasMoreElements()) {
        Function function = functionsList.nextElement();
        Expression exp = function.getExpression();
        try {
            expArray = new Expression[] { Expression.assign(new Expression(function.getName()), exp.flatten()) };
        } catch (ExpressionException ee) {
            System.err.println("Unable to process function " + function.getName() + " for publishing");
            ee.printStackTrace();
            continue;
        }
        try {
            Dimension dim = ExpressionCanvas.getExpressionImageSize(expArray, (Graphics2D) dummy.getGraphics());
            BufferedImage bufferedImage = new BufferedImage((int) dim.getWidth() * scale, (int) dim.getHeight() * scale, BufferedImage.TYPE_3BYTE_BGR);
            ExpressionCanvas.getExpressionAsImage(expArray, bufferedImage, scale);
            com.lowagie.text.Image expImage = com.lowagie.text.Image.getInstance(bufferedImage, null);
            expImage.setAlignment(com.lowagie.text.Image.ALIGN_LEFT);
            if (mathDescSubSection == null) {
                mathDescSubSection = mathDescSection.addSection("Functions", mathDescSection.depth() + 1);
            }
            if (viewableWidth < Math.floor(expImage.scaledWidth())) {
                expImage.scaleToFit(viewableWidth, expImage.height());
                System.out.println("Function After scaling: " + expImage.scaledWidth());
            }
            mathDescSubSection.add(expImage);
        } catch (Exception e) {
            System.err.println("Unable to add structure mapping image to report.");
            e.printStackTrace();
        }
    }
    writeSubDomainsEquationsAsImages(mathDescSection, mathDesc);
}
Also used : Constant(cbit.vcell.math.Constant) Dimension(java.awt.Dimension) Section(com.lowagie.text.Section) BufferedImage(java.awt.image.BufferedImage) ExpressionException(cbit.vcell.parser.ExpressionException) DocumentException(com.lowagie.text.DocumentException) ExpressionException(cbit.vcell.parser.ExpressionException) Function(cbit.vcell.math.Function) Expression(cbit.vcell.parser.Expression) SimulationContext(cbit.vcell.mapping.SimulationContext) GeometryContext(cbit.vcell.mapping.GeometryContext) ReactionContext(cbit.vcell.mapping.ReactionContext)

Example 15 with DocumentException

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

the class ITextWriter method getReactionArrowImageCell.

private Cell getReactionArrowImageCell(boolean bReversible) throws DocumentException {
    // Create image for arrow(s)
    int imageWidth = 150;
    int imageHeight = 50;
    BufferedImage bufferedImage = new BufferedImage(imageWidth, imageHeight, BufferedImage.TYPE_3BYTE_BGR);
    Graphics2D g = (Graphics2D) bufferedImage.getGraphics();
    g.setClip(0, 0, imageWidth, imageHeight);
    g.setColor(Color.white);
    g.fillRect(0, 0, imageWidth, imageHeight);
    g.setColor(Color.black);
    int fontSize = 12;
    g.setFont(new java.awt.Font("SansSerif", Font.BOLD, fontSize));
    // Draw the arrows on canvas/image
    if (bReversible) {
        // Forward  *AND* Reverse (bi-directional) arrow
        java.awt.Polygon arrow = new java.awt.Polygon(new int[] { 20, 40, 40, 110, 110, 130, 110, 110, 40, 40 }, new int[] { 25, 14, 22, 22, 14, 25, 36, 28, 28, 36 }, 10);
        g.fill(arrow);
    } else {
        // Only Forward Arrow
        java.awt.Polygon arrow = new java.awt.Polygon(new int[] { 20, 110, 110, 130, 110, 110, 20 }, new int[] { 22, 22, 14, 25, 36, 28, 28 }, 7);
        g.fill(arrow);
    }
    Cell imageCell = null;
    try {
        com.lowagie.text.Image rpImage = com.lowagie.text.Image.getInstance(bufferedImage, null);
        rpImage.setAlignment(com.lowagie.text.Image.MIDDLE);
        imageCell = new Cell();
        imageCell.add(rpImage);
    } catch (Exception e) {
        System.err.println("Unable to add structure mapping image to report.");
        e.printStackTrace();
    }
    return imageCell;
}
Also used : BufferedImage(java.awt.image.BufferedImage) DocumentException(com.lowagie.text.DocumentException) ExpressionException(cbit.vcell.parser.ExpressionException) Graphics2D(java.awt.Graphics2D) SimulationContext(cbit.vcell.mapping.SimulationContext) GeometryContext(cbit.vcell.mapping.GeometryContext) ReactionContext(cbit.vcell.mapping.ReactionContext) Cell(com.lowagie.text.Cell)

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