Example usage for org.apache.poi.ss.usermodel Drawing createPicture

List of usage examples for org.apache.poi.ss.usermodel Drawing createPicture

Introduction

In this page you can find the example usage for org.apache.poi.ss.usermodel Drawing createPicture.

Prototype

Picture createPicture(ClientAnchor anchor, int pictureIndex);

Source Link

Document

Creates a picture.

Usage

From source file:com.miraisolutions.xlconnect.Workbook.java

License:Open Source License

public void addImage(File imageFile, String name, boolean originalSize)
        throws FileNotFoundException, IOException {
    Name cname = getName(name);//w ww  .ja v a 2  s.  c  o  m

    // Get sheet where name is defined in
    Sheet sheet = workbook.getSheet(cname.getSheetName());

    AreaReference aref = new AreaReference(cname.getRefersToFormula());
    // Get name corners (top left, bottom right)
    CellReference topLeft = aref.getFirstCell();
    CellReference bottomRight = aref.getLastCell();

    // Determine image type
    int imageType;
    String filename = imageFile.getName().toLowerCase();
    if (filename.endsWith("jpg") || filename.endsWith("jpeg")) {
        imageType = org.apache.poi.ss.usermodel.Workbook.PICTURE_TYPE_JPEG;
    } else if (filename.endsWith("png")) {
        imageType = org.apache.poi.ss.usermodel.Workbook.PICTURE_TYPE_PNG;
    } else if (filename.endsWith("wmf")) {
        imageType = org.apache.poi.ss.usermodel.Workbook.PICTURE_TYPE_WMF;
    } else if (filename.endsWith("emf")) {
        imageType = org.apache.poi.ss.usermodel.Workbook.PICTURE_TYPE_EMF;
    } else if (filename.endsWith("bmp") || filename.endsWith("dib")) {
        imageType = org.apache.poi.ss.usermodel.Workbook.PICTURE_TYPE_DIB;
    } else if (filename.endsWith("pict") || filename.endsWith("pct") || filename.endsWith("pic")) {
        imageType = org.apache.poi.ss.usermodel.Workbook.PICTURE_TYPE_PICT;
    } else
        throw new IllegalArgumentException(
                "Image type \"" + filename.substring(filename.lastIndexOf('.') + 1) + "\" not supported!");

    InputStream is = new FileInputStream(imageFile);
    byte[] bytes = IOUtils.toByteArray(is);
    int imageIndex = workbook.addPicture(bytes, imageType);
    is.close();

    Drawing drawing;
    if (isHSSF()) {
        drawing = ((HSSFSheet) sheet).getDrawingPatriarch();
        if (drawing == null) {
            drawing = sheet.createDrawingPatriarch();
        }
    } else if (isXSSF()) {
        drawing = ((XSSFSheet) sheet).createDrawingPatriarch();
    } else {
        drawing = sheet.createDrawingPatriarch();
    }

    CreationHelper helper = workbook.getCreationHelper();
    ClientAnchor anchor = helper.createClientAnchor();
    anchor.setRow1(topLeft.getRow());
    anchor.setCol1(topLeft.getCol());
    // +1 since we want to include the
    anchor.setRow2(bottomRight.getRow() + 1);
    anchor.setCol2(bottomRight.getCol() + 1);
    anchor.setAnchorType(ClientAnchor.DONT_MOVE_AND_RESIZE);

    Picture picture = drawing.createPicture(anchor, imageIndex);
    if (originalSize)
        picture.resize();
}

From source file:com.qihang.winter.poi.excel.export.base.ExcelExportBase.java

License:Apache License

/**
 * Cell/* w ww . j  a  v a2 s  .  co m*/
 * 
 * @param patriarch
 * @param entity
 * @param row
 * @param i
 * @param imagePath
 * @param obj
 * @throws Exception
 */
public void createImageCell(Drawing patriarch,
        com.qihang.winter.poi.excel.entity.params.ExcelExportEntity entity, Row row, int i, String imagePath,
        Object obj) throws Exception {
    row.setHeight((short) (50 * entity.getHeight()));
    row.createCell(i);
    ClientAnchor anchor;
    if (type.equals(com.qihang.winter.poi.excel.entity.enmus.ExcelType.HSSF)) {
        anchor = new HSSFClientAnchor(0, 0, 0, 0, (short) i, row.getRowNum(), (short) (i + 1),
                row.getRowNum() + 1);
    } else {
        anchor = new XSSFClientAnchor(0, 0, 0, 0, (short) i, row.getRowNum(), (short) (i + 1),
                row.getRowNum() + 1);
    }

    if (StringUtils.isEmpty(imagePath)) {
        return;
    }
    if (entity.getExportImageType() == 1) {
        ByteArrayOutputStream byteArrayOut = new ByteArrayOutputStream();
        BufferedImage bufferImg;
        try {
            String path = PoiPublicUtil.getWebRootPath(imagePath);
            path = path.replace("WEB-INF/classes/", "");
            path = path.replace("file:/", "");
            bufferImg = ImageIO.read(new File(path));
            ImageIO.write(bufferImg, imagePath.substring(imagePath.indexOf(".") + 1, imagePath.length()),
                    byteArrayOut);
            byte[] value = byteArrayOut.toByteArray();
            patriarch.createPicture(anchor,
                    row.getSheet().getWorkbook().addPicture(value, getImageType(value)));
        } catch (IOException e) {
            LOGGER.error(e.getMessage(), e);
        }
    } else {
        byte[] value = (byte[]) (entity.getMethods() != null ? getFieldBySomeMethod(entity.getMethods(), obj)
                : entity.getMethod().invoke(obj, new Object[] {}));
        if (value != null) {
            patriarch.createPicture(anchor,
                    row.getSheet().getWorkbook().addPicture(value, getImageType(value)));
        }
    }

}

From source file:com.upbest.utils.AddDimensionedImage.java

License:Apache License

/**
 * Add an image to a worksheet./*from w  w w .  ja  v  a2 s  . c o  m*/
 *
 * @param colNumber A primitive int that contains the index number of a
 *                  column on the worksheet; POI column indices are zero
 *                  based. Together with the rowNumber parameter's value,
 *                  this parameter identifies a cell on the worksheet. The
 *                  images top left hand corner will be aligned with the
 *                  top left hand corner of this cell.
 * @param rowNumber A primitive int that contains the index number of a row
 *                  on the worksheet; POI row indices are zero based.
 *                  Together with the rowNumber parameter's value, this
 *                  parameter identifies a cell on the worksheet. The
 *                  images top left hand corner will be aligned with the
 *                  top left hand corner of this cell.
 * @param sheet A reference to the sheet that contains the cell identified
 *              by the two parameters above.
 * @param drawing An instance of the DrawingPatriarch class. This is now
 *                passed into the method where it was, previously, recovered
 *                from the sheet in order to allow multiple pictures be
 *                inserted. If the patriarch was not 'cached in this manner
 *                each time it was created any previously positioned images
 *                would be simply over-written.
 * @param imageFile An instance of the URL class that encapsulates the name
 *                  of and path to the image that is to be 'inserted into'
 *                  the sheet.
 * @param reqImageWidthMM A primitive double that contains the required
 *                        width of the image in millimetres.
 * @param reqImageHeightMM A primitive double that contains the required
 *                         height of the image in millimetres.
 * @param resizeBehaviour A primitive int whose value will determine how
 *                        the code should react if the image is larger than
 *                        the cell referenced by the colNumber and
 *                        rowNumber parameters. Four constants are provided
 *                        to determine what should happen;
 *                          AddDimensionedImage.EXPAND_ROW
 *                          AddDimensionedImage.EXPAND_COLUMN
 *                          AddDimensionedImage.EXPAND_ROW_AND_COLUMN
 *                          AddDimensionedImage.OVERLAY_ROW_AND_COLUMN
 * @throws java.io.FileNotFoundException If the file containing the image
 *                                       cannot be located.
 * @throws java.io.IOException If a problem occurs whilst reading the file
 *                             of image data.
 * @throws java.lang.IllegalArgumentException If an invalid value is passed
 *                                            to the resizeBehaviour
 *                                            parameter or if the extension
 *                                            of the image file indicates that
 *                                            it is of a type that cannot
 *                                            currently be added to the worksheet.
 */
public void addImageToSheet(int colNumber, int rowNumber, Sheet sheet, Drawing drawing, URL imageFile,
        double reqImageWidthMM, double reqImageHeightMM, int resizeBehaviour)
        throws IOException, IllegalArgumentException {
    ClientAnchor anchor = null;
    ClientAnchorDetail rowClientAnchorDetail = null;
    ClientAnchorDetail colClientAnchorDetail = null;
    int imageType = 0;

    // Validate the resizeBehaviour parameter.
    if ((resizeBehaviour != AddDimensionedImage.EXPAND_COLUMN)
            && (resizeBehaviour != AddDimensionedImage.EXPAND_ROW)
            && (resizeBehaviour != AddDimensionedImage.EXPAND_ROW_AND_COLUMN)
            && (resizeBehaviour != AddDimensionedImage.OVERLAY_ROW_AND_COLUMN)) {
        throw new IllegalArgumentException("Invalid value passed to the "
                + "resizeBehaviour parameter of AddDimensionedImage.addImageToSheet()");
    }

    // Call methods to calculate how the image and sheet should be
    // manipulated to accomodate the image; columns and then rows.
    colClientAnchorDetail = this.fitImageToColumns(sheet, colNumber, reqImageWidthMM, resizeBehaviour);
    rowClientAnchorDetail = this.fitImageToRows(sheet, rowNumber, reqImageHeightMM, resizeBehaviour);

    // Having determined if and how to resize the rows, columns and/or the
    // image, create the ClientAnchor object to position the image on
    // the worksheet. Note how the two ClientAnchorDetail records are
    // interrogated to recover the row/column co-ordinates and any insets.
    // The first two parameters are not used currently but could be if the
    // need arose to extend the functionality of this code by adding the
    // ability to specify that a clear 'border' be placed around the image.
    anchor = sheet.getWorkbook().getCreationHelper().createClientAnchor();

    anchor.setDx1(0);
    anchor.setDy1(0);
    anchor.setDx2(colClientAnchorDetail.getInset());
    anchor.setDy2(rowClientAnchorDetail.getInset());
    anchor.setCol1(colClientAnchorDetail.getFromIndex());
    anchor.setRow1(rowClientAnchorDetail.getFromIndex());
    anchor.setCol2(colClientAnchorDetail.getToIndex());
    anchor.setRow2(rowClientAnchorDetail.getToIndex());

    // For now, set the anchor type to do not move or resize the
    // image as the size of the row/column is adjusted. This could easilly
    // become another parameter passed to the method. Please read the note
    // above regarding the behaviour of image resizing.
    anchor.setAnchorType(ClientAnchor.MOVE_AND_RESIZE);

    // Now, add the picture to the workbook. Note that unlike the similar
    // method in the HSSF Examples section, the image type is checked. First,
    // the image files location is identified by interrogating the URL passed
    // to the method, the images type is identified before it is added to the
    // sheet.
    String sURL = imageFile.toString().toLowerCase();
    if (sURL.endsWith(".png")) {
        imageType = Workbook.PICTURE_TYPE_PNG;
    } else if (sURL.endsWith("jpg") || sURL.endsWith(".jpeg")) {
        imageType = Workbook.PICTURE_TYPE_JPEG;
    } else {
        throw new IllegalArgumentException("Invalid Image file : " + sURL);
    }
    int index = sheet.getWorkbook().addPicture(IOUtils.toByteArray(imageFile.openStream()), imageType);
    drawing.createPicture(anchor, index);
}

From source file:Compras.altaCompras.java

   private void b_muestraActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_b_muestraActionPerformed
    // TODO add your handling code here:
    javax.swing.JFileChooser jF1= new javax.swing.JFileChooser();
    jF1.setFileFilter(new ExtensionFileFilter("Excel document (*.xls)", new String[] { "xls" }));
    String ruta = null;//from  w w  w  .j ava2 s  .  co m
    if(jF1.showSaveDialog(null)==jF1.APPROVE_OPTION)
    {
        ruta = jF1.getSelectedFile().getAbsolutePath();
        File archivoXLS = new File(ruta+".xls");
        try
        {
            if(archivoXLS.exists())
            archivoXLS.delete();
            archivoXLS.createNewFile();
            Workbook libro = new HSSFWorkbook();
            FileOutputStream archivo = new FileOutputStream(archivoXLS);
            Sheet hoja = libro.createSheet("Muestras");
                
            org.apache.poi.ss.usermodel.Font font10 = libro.createFont();
            font10.setFontHeightInPoints((short)10);
            font10.setFontName("Arial");
            font10.setItalic(false);
            font10.setBold(false);
            font10.setColor(new HSSFColor.YELLOW().getIndex());
                
                
            CellStyle titulo = libro.createCellStyle();
            CellStyle contenido = libro.createCellStyle();
            CellStyle firma = libro.createCellStyle();
            CellStyle costado = libro.createCellStyle();
            CellStyle derecha = libro.createCellStyle();
            CellStyle derecha_borde = libro.createCellStyle();
                
            titulo.setFont(font10);
            titulo.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
            titulo.setFillBackgroundColor(new HSSFColor.GREEN().getIndex());
            titulo.setAlignment(CellStyle.ALIGN_CENTER);
                
            contenido.setBorderBottom(HSSFCellStyle.BORDER_THIN);
            contenido.setBorderTop(HSSFCellStyle.BORDER_THIN);
            contenido.setBorderRight(HSSFCellStyle.BORDER_THIN);
            contenido.setBorderLeft(HSSFCellStyle.BORDER_THIN);
                
            derecha_borde.setBorderBottom(HSSFCellStyle.BORDER_THIN);
            derecha_borde.setBorderTop(HSSFCellStyle.BORDER_THIN);
            derecha_borde.setBorderRight(HSSFCellStyle.BORDER_THIN);
            derecha_borde.setBorderLeft(HSSFCellStyle.BORDER_THIN);
            derecha_borde.setAlignment(CellStyle.ALIGN_RIGHT);
                
            derecha.setAlignment(CellStyle.ALIGN_RIGHT);
                
            firma.setBorderTop(HSSFCellStyle.BORDER_THIN);
            firma.setAlignment(CellStyle.ALIGN_CENTER);
                
            //costado.setBorderLeft(HSSFCellStyle.BORDER_THIN);
                
            hoja.setColumnWidth(0, 3000);
            hoja.setColumnWidth(2, 3000);
            hoja.setColumnWidth(3, 8000);
            hoja.setColumnWidth(4, 5000);
            try
            {
                InputStream is = new FileInputStream("imagenes/grande300115.jpg");
                byte[] bytes = IOUtils.toByteArray(is);
                int pictureIdx = libro.addPicture(bytes, Workbook.PICTURE_TYPE_JPEG);
                is.close();
                CreationHelper helper = libro.getCreationHelper();
                Drawing drawing = hoja.createDrawingPatriarch();
                ClientAnchor anchor = helper.createClientAnchor();
                anchor.setCol1(0);
                anchor.setRow1(0);
                Picture pict = drawing.createPicture(anchor, pictureIdx);
                pict.resize();
            }catch(Exception e){e.printStackTrace();}
            Row r7 = hoja.createRow(7);
            r7.createCell(0).setCellValue("ORDEN:");
            r7.createCell(1).setCellValue(String.valueOf(ord.getIdOrden()));
            r7.createCell(2).setCellValue("Hrs. Entrega:");
            r7.createCell(3).setCellValue("");
            hoja.addMergedRegion(new CellRangeAddress(7,7,4,7));
            r7.createCell(4).setCellValue("ORDEN PARA SURTIR MUESTRAS");
            r7.getCell(4).setCellStyle(derecha);
                
            Date fecha = new Date();
            DateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy");//YYYY-MM-DD HH:MM:SS
            String valor=dateFormat.format(fecha);
            Row r8 = hoja.createRow(8);
            r8.createCell(0).setCellValue("Supervisor:");
            hoja.addMergedRegion(new CellRangeAddress(8,8,1,3));
            r8.createCell(1).setCellValue("");
            r8.createCell(4).setCellValue("F. Elaboracin:");
            r8.createCell(5).setCellValue(valor);
                
            Row r9 = hoja.createRow(9);
            r9.createCell(0).setCellValue("Comprador:");
            hoja.addMergedRegion(new CellRangeAddress(9,9,1,3));
            r9.createCell(1).setCellValue("");
            r9.createCell(4).setCellValue("F. Entrega:");
            r9.createCell(5).setCellValue("");
                
            Row r10 = hoja.createRow(10);
            r10.createCell(0).setCellValue("Cantidad");
            r10.getCell(0).setCellStyle(titulo);
            hoja.addMergedRegion(new CellRangeAddress(10,10,1,7));
            r10.createCell(1).setCellValue("Descripcin");
            r10.getCell(1).setCellStyle(titulo);
                
            int ren=11;
            for(int r=0;r<(t_datos.getRowCount());r++)
            {
                if((boolean)t_titulos.getValueAt(r, 3)==true)
                {
                    Row fila = hoja.createRow(ren);
                    Cell celda = fila.createCell(0);
                    celda.setCellStyle(derecha_borde);
                    Cell celda1 = fila.createCell(1);
                    celda1.setCellStyle(contenido);
                    fila.createCell(2).setCellStyle(contenido);
                    fila.createCell(3).setCellStyle(contenido);
                    fila.createCell(4).setCellStyle(contenido);
                    fila.createCell(5).setCellStyle(contenido);
                    fila.createCell(6).setCellStyle(contenido);
                    fila.createCell(7).setCellStyle(contenido);
                    //Cell celda8 = fila.createCell(8);
                    //celda8.setCellStyle(costado);
                    try{
                        celda.setCellValue(t_datos.getValueAt(r, 14).toString());
                        hoja.addMergedRegion(new CellRangeAddress(ren,ren,1,7));
                        celda1.setCellValue(t_titulos.getValueAt(r, 2).toString());
                        //celda8.setCellValue("");
                    }catch(Exception e){
                        celda.setCellValue("");
                    }
                    ren++;
                }
            }
                
            Row rx = hoja.createRow(ren+5);
            hoja.addMergedRegion(new CellRangeAddress(ren+5,ren+5,0,2));
            rx.createCell(0).setCellValue("Recibe Muestras");
            rx.getCell(0).setCellStyle(firma);
            rx.createCell(1).setCellStyle(firma);
            rx.createCell(2).setCellStyle(firma);
            hoja.addMergedRegion(new CellRangeAddress(ren+5,ren+5,5,7));
            rx.createCell(5).setCellValue("Entrega Muestras");
            rx.getCell(5).setCellStyle(firma);
            rx.createCell(6).setCellStyle(firma);
            rx.createCell(7).setCellStyle(firma);
                
            libro.write(archivo);
            archivo.close();
            Desktop.getDesktop().open(archivoXLS);
        }catch(Exception e)
        {
            e.printStackTrace();
            JOptionPane.showMessageDialog(this, "No se pudo realizar el reporte si el archivo esta abierto");
        }
    }
}

From source file:controller.VisitasController.java

public void exportExcel() {

    FileChooser fileChooser = new FileChooser();
    fileChooser.setTitle("Open Resource File");
    fileChooser.setInitialDirectory(new File(System.getProperty("user.home")));
    fileChooser.getExtensionFilters().add(new FileChooser.ExtensionFilter("XLS", "*.xls"));
    File f = fileChooser.showSaveDialog(null);

    try {// w w  w  .  ja  v a  2  s .  c  o  m
        String filename = f.getAbsolutePath();
        HSSFWorkbook workbook = new HSSFWorkbook();
        HSSFSheet sheet = workbook.createSheet("FirstSheet");
        int bool = 1;

        InputStream inputStream = getClass().getResourceAsStream("/images/excel-logo.jpg");

        byte[] imageBytes = IOUtils.toByteArray(inputStream);

        int pictureureIdx = workbook.addPicture(imageBytes, Workbook.PICTURE_TYPE_JPEG);

        inputStream.close();

        CreationHelper helper = workbook.getCreationHelper();

        Drawing drawing = sheet.createDrawingPatriarch();

        ClientAnchor anchor = helper.createClientAnchor();

        anchor.setCol1(1);
        anchor.setRow1(0);

        Picture pict = drawing.createPicture(anchor, pictureureIdx);

        HSSFRow rowhead = sheet.createRow(8);

        rowhead.createCell(0);
        rowhead.createCell(1).setCellValue("Cedula");
        rowhead.createCell(2).setCellValue("Cliente");
        rowhead.createCell(3).setCellValue("Contrato");
        rowhead.createCell(4).setCellValue("Plan");
        rowhead.createCell(5).setCellValue("Fecha");
        rowhead.createCell(6).setCellValue("Hora");
        rowhead.createCell(7).setCellValue("Invitados");
        makeRowBold(workbook, rowhead);

        for (int i = 0; i < table.getItems().size(); i++) {
            HSSFRow row = sheet.createRow(i + 9);
            Asistencia a = (Asistencia) table.getItems().get(i);
            row.createCell(1).setCellValue(a.getCedula());
            row.createCell(2).setCellValue(a.getNombre());
            row.createCell(3).setCellValue(a.getContrato());
            row.createCell(4).setCellValue(a.getPlan());
            row.createCell(5).setCellValue(a.getFecha());
            row.createCell(6).setCellValue(a.getHora());
            row.createCell(7).setCellValue(Integer.parseInt(a.getInvitados()));
            centerRow(workbook, row);
        }
        autoSizeColumns(workbook);
        pict.resize();
        FileOutputStream fileOut = new FileOutputStream(filename);
        workbook.write(fileOut);
        fileOut.close();

    } catch (Exception ex) {
        ex.printStackTrace();
    }

}

From source file:de.iteratec.iteraplan.businesslogic.exchange.elasticExcel.export.template.AbstractIntroSheetGenerator.java

License:Open Source License

private void insertIteraplanLogo(int colIndex, int rowIndex) {
    CreationHelper helper = getWorkbook().getCreationHelper();

    byte[] bytes;
    try {/*from w  w  w .j a  v a  2s.c  o m*/
        InputStream is = logoImage.getInputStream();
        bytes = IOUtils.toByteArray(is);
    } catch (IOException e) {
        LOGGER.error("Could not read the excel template!", e);
        throw new IteraplanTechnicalException(IteraplanErrorMessages.INVALID_EXCEL_TEMPLATE);
    }
    int pictureIdx = getWorkbook().addPicture(bytes, Workbook.PICTURE_TYPE_PNG);

    Sheet sheet = getIntroductionSheet();
    Drawing drawing = sheet.createDrawingPatriarch();
    ClientAnchor anchor = helper.createClientAnchor();
    //set top-left corner of the picture
    anchor.setCol1(colIndex);
    anchor.setRow1(rowIndex);
    Picture pict = drawing.createPicture(anchor, pictureIdx);

    pict.resize();
}

From source file:demo.poi.AddDimensionedImage.java

License:Apache License

/**
 * Add an image to a worksheet./*  ww  w.j  a v a  2  s .c o m*/
 *
 * @param colNumber
 *            A primitive int that contains the index number of a column on
 *            the worksheet; POI column indices are zero based. Together
 *            with the rowNumber parameter's value, this parameter
 *            identifies a cell on the worksheet. The images top left hand
 *            corner will be aligned with the top left hand corner of this
 *            cell.
 * @param rowNumber
 *            A primitive int that contains the index number of a row on the
 *            worksheet; POI row indices are zero based. Together with the
 *            rowNumber parameter's value, this parameter identifies a cell
 *            on the worksheet. The images top left hand corner will be
 *            aligned with the top left hand corner of this cell.
 * @param sheet
 *            A reference to the sheet that contains the cell identified by
 *            the two parameters above.
 * @param drawing
 *            An instance of the DrawingPatriarch class. This is now passed
 *            into the method where it was, previously, recovered from the
 *            sheet in order to allow multiple pictures be inserted. If the
 *            patriarch was not 'cached in this manner each time it was
 *            created any previously positioned images would be simply
 *            over-written.
 * @param imageFile
 *            An instance of the URL class that encapsulates the name of and
 *            path to the image that is to be 'inserted into' the sheet.
 * @param reqImageWidthMM
 *            A primitive double that contains the required width of the
 *            image in millimetres.
 * @param reqImageHeightMM
 *            A primitive double that contains the required height of the
 *            image in millimetres.
 * @param resizeBehaviour
 *            A primitive int whose value will determine how the code should
 *            react if the image is larger than the cell referenced by the
 *            colNumber and rowNumber parameters. Four constants are
 *            provided to determine what should happen;
 *            AddDimensionedImage.EXPAND_ROW
 *            AddDimensionedImage.EXPAND_COLUMN
 *            AddDimensionedImage.EXPAND_ROW_AND_COLUMN
 *            AddDimensionedImage.OVERLAY_ROW_AND_COLUMN
 * @throws java.io.FileNotFoundException
 *             If the file containing the image cannot be located.
 * @throws java.io.IOException
 *             If a problem occurs whilst reading the file of image data.
 * @throws java.lang.IllegalArgumentException
 *             If an invalid value is passed to the resizeBehaviour
 *             parameter or if the extension of the image file indicates
 *             that it is of a type that cannot currently be added to the
 *             worksheet.
 */
public void addImageToSheet(int colNumber, int rowNumber, Sheet sheet, Drawing drawing, URL imageFile,
        double reqImageWidthMM, double reqImageHeightMM, int resizeBehaviour)
        throws IOException, IllegalArgumentException {
    ClientAnchor anchor = null;
    ClientAnchorDetail rowClientAnchorDetail = null;
    ClientAnchorDetail colClientAnchorDetail = null;
    int imageType = 0;

    // Validate the resizeBehaviour parameter.
    if ((resizeBehaviour != AddDimensionedImage.EXPAND_COLUMN)
            && (resizeBehaviour != AddDimensionedImage.EXPAND_ROW)
            && (resizeBehaviour != AddDimensionedImage.EXPAND_ROW_AND_COLUMN)
            && (resizeBehaviour != AddDimensionedImage.OVERLAY_ROW_AND_COLUMN)) {
        throw new IllegalArgumentException("Invalid value passed to the "
                + "resizeBehaviour parameter of AddDimensionedImage.addImageToSheet()");
    }

    // Call methods to calculate how the image and sheet should be
    // manipulated to accomodate the image; columns and then rows.
    colClientAnchorDetail = this.fitImageToColumns(sheet, colNumber, reqImageWidthMM, resizeBehaviour);
    rowClientAnchorDetail = this.fitImageToRows(sheet, rowNumber, reqImageHeightMM, resizeBehaviour);

    // Having determined if and how to resize the rows, columns and/or the
    // image, create the ClientAnchor object to position the image on
    // the worksheet. Note how the two ClientAnchorDetail records are
    // interrogated to recover the row/column co-ordinates and any insets.
    // The first two parameters are not used currently but could be if the
    // need arose to extend the functionality of this code by adding the
    // ability to specify that a clear 'border' be placed around the image.
    anchor = sheet.getWorkbook().getCreationHelper().createClientAnchor();

    anchor.setDx1(0);
    anchor.setDy1(0);
    anchor.setDx2(colClientAnchorDetail.getInset());
    anchor.setDy2(rowClientAnchorDetail.getInset());
    anchor.setCol1(colClientAnchorDetail.getFromIndex());
    anchor.setRow1(rowClientAnchorDetail.getFromIndex());
    anchor.setCol2(colClientAnchorDetail.getToIndex());
    anchor.setRow2(rowClientAnchorDetail.getToIndex());

    // For now, set the anchor type to do not move or resize the
    // image as the size of the row/column is adjusted. This could easilly
    // become another parameter passed to the method. Please read the note
    // above regarding the behaviour of image resizing.
    anchor.setAnchorType(ClientAnchor.MOVE_AND_RESIZE);

    // Now, add the picture to the workbook. Note that unlike the similar
    // method in the HSSF Examples section, the image type is checked.
    // First,
    // the image files location is identified by interrogating the URL
    // passed
    // to the method, the images type is identified before it is added to
    // the
    // sheet.
    String sURL = imageFile.toString().toLowerCase();
    if (sURL.endsWith(".png")) {
        imageType = Workbook.PICTURE_TYPE_PNG;
    } else if (sURL.endsWith("jpg") || sURL.endsWith(".jpeg")) {
        imageType = Workbook.PICTURE_TYPE_JPEG;
    } else {
        throw new IllegalArgumentException("Invalid Image file : " + sURL);
    }
    int index = sheet.getWorkbook().addPicture(IOUtils.toByteArray(imageFile.openStream()), imageType);
    drawing.createPicture(anchor, index);
}

From source file:domain.Excel.java

public void graficar(short columna_inicial, Integer fila_inicial, short columna_final, Integer fila_final) {

        final BufferedImage buffer = grafica.createBufferedImage(600, 200);

        ByteArrayOutputStream img_bytes = new ByteArrayOutputStream();
        try {/*from  www .ja v a2 s .c  o m*/

            ImageIO.write(buffer, "png", img_bytes);
            img_bytes.flush();

        } catch (IOException ex) {
            Logger.getLogger(Excel.class.getName()).log(Level.SEVERE, null, ex);
        }

        HSSFClientAnchor anchor = new HSSFClientAnchor(0, 0, 0, 0, (short) columna_inicial, fila_inicial,
                (short) columna_final, fila_final);
        int index = wb.addPicture(img_bytes.toByteArray(), HSSFWorkbook.PICTURE_TYPE_PNG);
        Drawing patriarch = sheet.createDrawingPatriarch();
        patriarch.createPicture(anchor, index);
        /**/
        /*
         Drawing drawing = sheet.createDrawingPatriarch();
         XSSFClientAnchor anchor = new XSSFClientAnchor(0, 0, 0, 0, (short) 2, 6, (short) 9, 26);
         Chart chart = drawing.createChart(anchor);
         ChartLegend legend = chart.getOrCreateLegend();
         legend.setPosition(LegendPosition.RIGHT);
         chart.getOrCreateLegend();
            
         ScatterChartData data = chart.getChartDataFactory().createScatterChartData();
            
         ValueAxis bottomAxis = chart.getChartAxisFactory().createValueAxis(AxisPosition.BOTTOM);
         ValueAxis leftAxis = chart.getChartAxisFactory().createValueAxis(AxisPosition.LEFT);
         leftAxis.setCrosses(AxisCrosses.AUTO_ZERO);
            
         ChartDataSource<String> xs = DataSources.fromStringCellRange(sheet, new CellRangeAddress(6, fila_final, 0, 0));
         ChartDataSource<Number> ys1 = DataSources.fromNumericCellRange(sheet, new CellRangeAddress(6, fila_final, 1, 1));
         //ChartDataSource<Number> ys2 = DataSources.fromNumericCellRange(sheet, new CellRangeAddress(2, 2, 0, NUM_OF_COLUMNS - 1));
            
         data.addSerie(xs, ys1);
            
         //data.addSerie(xs, ys2);
         chart.plot(data, bottomAxis, leftAxis);
         */
    }

From source file:domain.Excel.java

private void cargarLogo1(Integer fila, Integer columna, Double resize) {
        InputStream inputStream;//from   w w  w  .  j  a v a  2s .  c  o  m
        try {

            inputStream = getClass().getResourceAsStream("/resources/logo tru-test.png");//Tru-Test.jpg");

            byte[] bytes = IOUtils.toByteArray(inputStream);
            int pictureIdx = wb.addPicture(bytes, wb.PICTURE_TYPE_PNG);
            inputStream.close();
            CreationHelper helper = wb.getCreationHelper();
            Drawing drawing = sheet.createDrawingPatriarch();
            ClientAnchor anchor = helper.createClientAnchor();
            //set top-left corner for the image
            anchor.setCol1(columna);
            anchor.setRow1(fila);
            Picture pict = drawing.createPicture(anchor, pictureIdx);
            //Reset the image to the original size
            pict.resize(resize);

        } catch (FileNotFoundException ex) {
            Logger.getLogger(Excel.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(Excel.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

From source file:domain.Excel.java

private void cargarLogo2(Integer fila, Integer columna, Double resize) {
        InputStream inputStream;/*w  w w.ja v  a  2 s  .  co  m*/
        try {

            inputStream = getClass().getResourceAsStream("/resources/LOGO.png");//Tru-Test.jpg");

            byte[] bytes = IOUtils.toByteArray(inputStream);
            int pictureIdx = wb.addPicture(bytes, wb.PICTURE_TYPE_PNG);
            inputStream.close();
            CreationHelper helper = wb.getCreationHelper();
            Drawing drawing = sheet.createDrawingPatriarch();
            ClientAnchor anchor = helper.createClientAnchor();
            //set top-left corner for the image
            anchor.setCol1(columna);
            anchor.setRow1(fila);
            Picture pict = drawing.createPicture(anchor, pictureIdx);
            //Reset the image to the original size
            pict.resize(resize);

        } catch (FileNotFoundException ex) {
            Logger.getLogger(Excel.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(Excel.class.getName()).log(Level.SEVERE, null, ex);
        }
    }