Example usage for org.apache.poi.xssf.usermodel XSSFDrawing createPicture

List of usage examples for org.apache.poi.xssf.usermodel XSSFDrawing createPicture

Introduction

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

Prototype

@Override
    public XSSFPicture createPicture(ClientAnchor anchor, int pictureIndex) 

Source Link

Usage

From source file:com.netsteadfast.greenstep.util.SimpleUtils.java

License:Apache License

public static void setCellPicture(XSSFWorkbook wb, XSSFSheet sh, byte[] iconBytes, int row, int col)
        throws Exception {
    int myPictureId = wb.addPicture(iconBytes, XSSFWorkbook.PICTURE_TYPE_PNG);

    XSSFDrawing drawing = sh.createDrawingPatriarch();
    XSSFClientAnchor myAnchor = new XSSFClientAnchor();

    myAnchor.setCol1(col);/*ww w. j a v  a2 s.  c  om*/
    myAnchor.setRow1(row);

    XSSFPicture myPicture = drawing.createPicture(myAnchor, myPictureId);
    myPicture.resize();
}

From source file:com.vodafone.poms.ii.helpers.ExportManager.java

private static int addImageToShape(XSSFSheet sh, XSSFClientAnchor imgAnchor, int imgId) {
    XSSFDrawing pat = sh.createDrawingPatriarch();
    XSSFPicture pic = pat.createPicture(imgAnchor, imgId);

    CTPicture cPic = pic.getCTPicture();
    int shapeId = (int) cPic.getNvPicPr().getCNvPr().getId();
    cPic.getNvPicPr().getCNvPr().setHidden(true);
    CTOfficeArtExtensionList extLst = cPic.getNvPicPr().getCNvPicPr().addNewExtLst();
    // https://msdn.microsoft.com/en-us/library/dd911027(v=office.12).aspx
    CTOfficeArtExtension ext = extLst.addNewExt();
    ext.setUri("{63B3BB69-23CF-44E3-9099-C40C66FF867C}");
    XmlCursor cur = ext.newCursor();/*from ww w.ja va2 s .  c  om*/
    cur.toEndToken();
    cur.beginElement(new QName(drawNS, "compatExt", "a14"));
    cur.insertAttributeWithValue("spid", "_x0000_s" + shapeId);

    return shapeId;
}

From source file:nc.noumea.mairie.appock.util.StockSpreadsheetExporter.java

License:Open Source License

private static void addImage(XSSFWorkbook workbook, XSSFSheet worksheet, File file, int rowNum)
        throws IOException {
    //add picture data to this workbook.
    InputStream is = new FileInputStream(file);
    byte[] bytes = IOUtils.toByteArray(is);
    int pictureIdx = workbook.addPicture(bytes, Workbook.PICTURE_TYPE_PNG);
    is.close();//from   www  .j a v  a 2  s  .  com

    XSSFDrawing drawing = worksheet.createDrawingPatriarch();

    //add a picture shape
    XSSFClientAnchor anchor = workbook.getCreationHelper().createClientAnchor();
    anchor.setAnchorType(ClientAnchor.AnchorType.MOVE_DONT_RESIZE);
    //set top-left corner of the picture,
    //subsequent call of Picture#resize() will operate relative to it
    anchor.setCol1(0);
    anchor.setRow1(rowNum);

    Picture pict = drawing.createPicture(anchor, pictureIdx);
    //auto-size picture relative to its top-left corner
    pict.resize();

    //get the picture width
    int pictWidthPx = pict.getImageDimension().width;
    int pictHeightPt = pict.getImageDimension().height;

    //get the cell width
    float cellWidthPx = worksheet.getColumnWidthInPixels(0);
    float cellHeightPx = ConvertImageUnits.heightUnits2Pixel(worksheet.getRow(rowNum).getHeight());

    //calculate the center position
    int centerPosPx = Math.round(cellWidthPx / 2f - (float) pictWidthPx / 2f);
    int centerPosPy = Math.round(cellHeightPx / 2f - (float) pictHeightPt / 2f + 10);

    //set the new upper left anchor position
    anchor.setCol1(0);
    //set the remaining pixels up to the center position as Dx in unit EMU
    anchor.setDx1(centerPosPx * Units.EMU_PER_PIXEL);
    anchor.setDy1(centerPosPy * Units.EMU_PER_PIXEL);

    //resize the pictutre to original size again
    //this will determine the new bottom rigth anchor position
    pict.resize();

}

From source file:org.apache.ofbiz.pricat.AbstractPricatParser.java

License:Apache License

public void writeCommentsToFile(XSSFWorkbook workbook, XSSFSheet sheet) {
    report.println();//from w  w w .j a v  a2s. co m
    report.print(UtilProperties.getMessage(resource, "WriteCommentsBackToExcel", locale),
            InterfaceReport.FORMAT_NOTE);
    FileOutputStream fos = null;
    XSSFCreationHelper factory = workbook.getCreationHelper();
    XSSFFont boldFont = workbook.createFont();
    boldFont.setFontName("Arial");
    boldFont.setBold(true);
    boldFont.setCharSet(134);
    boldFont.setFontHeightInPoints((short) 9);
    XSSFFont plainFont = workbook.createFont();
    plainFont.setFontName("Arial");
    plainFont.setCharSet(134);
    plainFont.setFontHeightInPoints((short) 9);

    XSSFSheet errorSheet = null;
    if (errorMessages.keySet().size() > 0) {
        String errorSheetName = UtilDateTime.nowDateString("yyyy-MM-dd HHmm") + " Errors";
        errorSheetName = WorkbookUtil.createSafeSheetName(errorSheetName);
        errorSheet = workbook.createSheet(errorSheetName);
        workbook.setSheetOrder(errorSheetName, 0);
        workbook.setActiveSheet(workbook.getSheetIndex(errorSheetName));
        XSSFDrawing drawingPatriarch = errorSheet.getDrawingPatriarch();
        if (drawingPatriarch == null) {
            drawingPatriarch = errorSheet.createDrawingPatriarch();
        }
        for (int i = 0; i <= getHeaderRowNo(); i++) {
            XSSFRow newRow = errorSheet.createRow(i);
            XSSFRow row = sheet.getRow(i);
            newRow.setHeight(row.getHeight());
            copyRow(row, newRow, factory, drawingPatriarch);
        }

        // copy merged regions
        for (int i = 0; i < sheet.getNumMergedRegions(); i++) {
            CellRangeAddress mergedRegion = sheet.getMergedRegion(i);
            if (mergedRegion.getFirstRow() < getHeaderRowNo()) {
                errorSheet.addMergedRegion(mergedRegion);
            }
        }

        // copy images
        List<XSSFPictureData> pics = workbook.getAllPictures();
        List<XSSFShape> shapes = sheet.getDrawingPatriarch().getShapes();
        for (int i = 0; i < shapes.size(); i++) {
            XSSFShape shape = shapes.get(i);
            XSSFAnchor anchor = shape.getAnchor();
            if (shape instanceof XSSFPicture && anchor instanceof XSSFClientAnchor) {
                XSSFPicture pic = (XSSFPicture) shape;
                XSSFClientAnchor clientAnchor = (XSSFClientAnchor) anchor;
                if (clientAnchor.getRow1() < getHeaderRowNo()) {
                    for (int j = 0; j < pics.size(); j++) {
                        XSSFPictureData picture = pics.get(j);
                        if (picture.getPackagePart().getPartName()
                                .equals(pic.getPictureData().getPackagePart().getPartName())) {
                            drawingPatriarch.createPicture(clientAnchor, j);
                        }
                    }
                }
            }
        }
    }

    try {
        // set comments in the original sheet
        XSSFDrawing patriarch = sheet.getDrawingPatriarch();
        for (CellReference cell : errorMessages.keySet()) {
            if (cell != null && errorMessages.get(cell) != null) {
                XSSFComment comment = sheet.getCellComment(new CellAddress(cell.getRow(), cell.getCol()));
                boolean isNewComment = false;
                if (comment == null) {
                    XSSFClientAnchor anchor = factory.createClientAnchor();
                    anchor.setDx1(100);
                    anchor.setDx2(100);
                    anchor.setDy1(100);
                    anchor.setDy2(100);
                    anchor.setCol1(cell.getCol());
                    anchor.setCol2(cell.getCol() + 4);
                    anchor.setRow1(cell.getRow());
                    anchor.setRow2(cell.getRow() + 4);
                    anchor.setAnchorType(AnchorType.DONT_MOVE_AND_RESIZE);

                    comment = patriarch.createCellComment(anchor);
                    isNewComment = true;
                }
                XSSFRichTextString rts = factory.createRichTextString("OFBiz PriCat:\n");
                rts.applyFont(boldFont);
                rts.append(errorMessages.get(cell), plainFont);
                comment.setString(rts);
                comment.setAuthor("Apache OFBiz PriCat");
                if (isNewComment) {
                    sheet.getRow(cell.getRow()).getCell(cell.getCol()).setCellComment(comment);
                    OFBizPricatUtil.formatCommentShape(sheet, cell);
                }
            }
        }

        // set comments in the new error sheet
        XSSFDrawing errorPatriarch = errorSheet.getDrawingPatriarch();
        int newRowNum = getHeaderRowNo() + 1;
        Map<Integer, Integer> rowMapping = new HashMap<Integer, Integer>();
        for (CellReference cell : errorMessages.keySet()) {
            if (cell != null && errorMessages.get(cell) != null) {
                XSSFRow row = sheet.getRow(cell.getRow());
                Integer rowNum = Integer.valueOf(row.getRowNum());
                int errorRow = newRowNum;
                if (rowMapping.containsKey(rowNum)) {
                    errorRow = rowMapping.get(rowNum).intValue();
                } else {
                    XSSFRow newRow = errorSheet.getRow(errorRow);
                    if (newRow == null) {
                        newRow = errorSheet.createRow(errorRow);
                    }
                    rowMapping.put(rowNum, Integer.valueOf(errorRow));
                    newRow.setHeight(row.getHeight());
                    copyRow(row, newRow, factory, errorPatriarch);
                    newRowNum++;
                }
            }
        }

        // write to file
        if (sequenceNum > 0L) {
            File commentedExcel = FileUtil.getFile(tempFilesFolder + userLoginId + "/" + sequenceNum + ".xlsx");
            fos = new FileOutputStream(commentedExcel);
            workbook.write(fos);
        } else {
            fos = new FileOutputStream(pricatFile);
            workbook.write(fos);
        }
        fos.flush();
        fos.close();
        workbook.close();
    } catch (FileNotFoundException e) {
        report.println(e);
        Debug.logError(e, module);
    } catch (IOException e) {
        report.println(e);
        Debug.logError(e, module);
    } finally {
        if (fos != null) {
            try {
                fos.close();
            } catch (IOException e) {
                Debug.logError(e, module);
            }
        }
        if (workbook != null) {
            try {
                workbook.close();
            } catch (IOException e) {
                Debug.logError(e, module);
            }
        }
    }
    report.println(UtilProperties.getMessage(resource, "ok", locale), InterfaceReport.FORMAT_OK);
    report.println();
}

From source file:org.azkfw.document.tools.DirectoryTreeDocument.java

License:Apache License

private void onFindFile(final DirectoryParserEvent event) {
    DirectoryParserFileInfo info = event.getInfo();
    String prefix = info.getPrefix();
    File file = info.getFile();//w  w  w  . j a v a  2s  .  c  o m

    XSSFRow row = sheet.createRow(offsetRow + countFile);
    int col = 0;
    for (int i = 0; i < prefix.length(); i++) {
        Character c = prefix.charAt(i);

        XSSFCell cell = row.createCell(offsetCol + col);
        cell.setCellValue(c.toString());
        col++;
    }

    XSSFDrawing patriarch = sheet.createDrawingPatriarch();
    XSSFClientAnchor anchor = new XSSFClientAnchor(0, 0, 18, 18, (short) (offsetCol + col),
            (offsetRow + countFile), (short) (offsetCol + col + 1), (offsetRow + countFile + 1));
    anchor.setAnchorType(XSSFClientAnchor.MOVE_DONT_RESIZE);
    if (file.isFile()) {
        patriarch.createPicture(anchor,
                sheet.getWorkbook().addPicture(imgFile.toByteArray(), HSSFWorkbook.PICTURE_TYPE_PNG));
    } else {
        patriarch.createPicture(anchor,
                sheet.getWorkbook().addPicture(imgDirectory.toByteArray(), HSSFWorkbook.PICTURE_TYPE_PNG));
    }

    XSSFCell cell = row.createCell(offsetCol + col + 1);
    cell.setCellValue(file.getName());

    maxCol = Math.max(maxCol, col + 1);

    countFile++;
}

From source file:org.cgiar.ccafs.ap.summaries.projects.xlsx.BaseXLS.java

License:Open Source License

/**
 * @throws IOException//from  w  w w  .  j a  v  a 2s .c  om
 */
public void createLogo(Workbook workbook, Sheet sheet) throws IOException {
    // FileInputStream obtains input bytes from the image file
    InputStream inputStream =

            new FileInputStream(
                    new File(config.getResourcePath(), "templates" + File.separator + "logo-ccafs.png"));
    // Get the contents of an InputStream as a byte[].
    byte[] bytes = IOUtils.toByteArray(inputStream);
    // Adds a picture to the workbook
    int pictureIdx = workbook.addPicture(bytes, Workbook.PICTURE_TYPE_PNG);
    // close the input stream
    inputStream.close();

    // Creates the top-level drawing patriarch.
    XSSFDrawing drawing = (XSSFDrawing) sheet.createDrawingPatriarch();

    // Set top-left corner for the image
    XSSFClientAnchor anchor = new XSSFClientAnchor();
    anchor.setAnchorType(2);
    anchor.setCol1(LOGO_POSITION_COLUMN);
    anchor.setRow1(LOGO_POSITION_ROW);

    // Creates a picture
    XSSFPicture pict = drawing.createPicture(anchor, pictureIdx);

    // Reset the image to the original size
    pict.resize();

}