Search in sources :

Example 1 with Image

use of com.lowagie.text.Image 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 2 with Image

use of com.lowagie.text.Image in project mdw-designer by CenturyLinkCloud.

the class ExportHelper method printGraphPdf.

private void printGraphPdf(DocWriter writer, CanvasCommon canvas, Graph process, Rectangle pageSize, String type, String filename, Chapter chapter, int chapterNumber) throws Exception {
    Dimension graphsize = process.getGraphSize();
    // we create a fontMapper and read all the fonts in the font directory
    DefaultFontMapper mapper = new DefaultFontMapper();
    FontFactory.registerDirectories();
    mapper.insertDirectory("c:\\winnt\\fonts");
    // we create a template and a Graphics2D object that corresponds with it
    int w;
    int h;
    float scale;
    if ((float) graphsize.width < pageSize.getWidth() * 0.8 && (float) graphsize.height < pageSize.getHeight() * 0.8 || type.equals(HTML)) {
        w = graphsize.width + 36;
        h = graphsize.height + 36;
        scale = -1f;
    } else {
        scale = pageSize.getWidth() * 0.8f / (float) graphsize.width;
        if (scale > pageSize.getHeight() * 0.8f / (float) graphsize.height)
            scale = pageSize.getHeight() * 0.8f / (float) graphsize.height;
        w = (int) (graphsize.width * scale) + 36;
        h = (int) (graphsize.height * scale) + 36;
    }
    Image img;
    int zoomSave = process.zoom;
    process.zoom = 100;
    Color bgsave = canvas.getBackground();
    boolean edsave = canvas.editable;
    canvas.editable = false;
    canvas.setBackground(Color.white);
    if (type.equals(PDF)) {
        PdfContentByte cb = ((PdfWriter) writer).getDirectContent();
        PdfTemplate tp = cb.createTemplate(w, h);
        Graphics2D g2 = tp.createGraphics(w, h, mapper);
        if (scale > 0)
            g2.scale(scale, scale);
        tp.setWidth(w);
        tp.setHeight(h);
        canvas.paintComponent(g2);
        g2.dispose();
        img = new ImgTemplate(tp);
    } else {
        String imgfilename = filename + "." + process.getName() + "_ch" + chapterNumber + ".jpg";
        printImage(imgfilename, -1f, canvas, graphsize);
        img = Image.getInstance(imgfilename);
        if (scale > 0)
            img.scalePercent(scale * 100);
    }
    process.zoom = zoomSave;
    canvas.setBackground(bgsave);
    canvas.editable = edsave;
    if (img != null)
        chapter.add(img);
}
Also used : PdfWriter(com.lowagie.text.pdf.PdfWriter) ImgTemplate(com.lowagie.text.ImgTemplate) Color(java.awt.Color) DefaultFontMapper(com.lowagie.text.pdf.DefaultFontMapper) Dimension(java.awt.Dimension) BufferedImage(java.awt.image.BufferedImage) Image(com.lowagie.text.Image) PdfTemplate(com.lowagie.text.pdf.PdfTemplate) Graphics2D(java.awt.Graphics2D) PdfContentByte(com.lowagie.text.pdf.PdfContentByte)

Example 3 with Image

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

the class FormPrintEngineIText method printImage.

/**
 * Print a java image
 */
private void printImage(java.awt.Image image, PdfContentByte cb, float x1, float y1, float x2, float y2, int alignment, int fitMethod, float rotate) throws BadElementException, IOException, DocumentException {
    if (image != null) {
        // Convert to an iText Image
        Image img = Image.getInstance(image, null);
        printImage(img, cb, x1, y1, x2, y2, alignment, fitMethod, rotate);
    }
}
Also used : Image(com.lowagie.text.Image)

Example 4 with Image

use of com.lowagie.text.Image 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 5 with Image

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

the class PdfExportDemo method createSvgImage.

private Image createSvgImage(PdfContentByte contentByte, float maxPointWidth, float maxPointHeight) throws IOException {
    Image image = drawUnscaledSvg(contentByte);
    image.scaleToFit(maxPointWidth, maxPointHeight);
    return image;
}
Also used : Image(com.lowagie.text.Image)

Aggregations

Image (com.lowagie.text.Image)9 Color (java.awt.Color)5 IOException (java.io.IOException)5 DocumentException (com.lowagie.text.DocumentException)4 BadElementException (com.lowagie.text.BadElementException)3 Document (com.lowagie.text.Document)3 Phrase (com.lowagie.text.Phrase)3 PdfContentByte (com.lowagie.text.pdf.PdfContentByte)3 PdfPCell (com.lowagie.text.pdf.PdfPCell)3 PdfPTable (com.lowagie.text.pdf.PdfPTable)3 FileOutputStream (java.io.FileOutputStream)3 ImgTemplate (com.lowagie.text.ImgTemplate)2 Paragraph (com.lowagie.text.Paragraph)2 Rectangle (com.lowagie.text.Rectangle)2 DefaultFontMapper (com.lowagie.text.pdf.DefaultFontMapper)2 PdfTemplate (com.lowagie.text.pdf.PdfTemplate)2 PdfWriter (com.lowagie.text.pdf.PdfWriter)2 ITableCellRenderer (de.janrufmonitor.ui.jface.application.rendering.ITableCellRenderer)2 Graphics2D (java.awt.Graphics2D)2 BufferedImage (java.awt.image.BufferedImage)2