Example usage for com.lowagie.text Rectangle getWidth

List of usage examples for com.lowagie.text Rectangle getWidth

Introduction

In this page you can find the example usage for com.lowagie.text Rectangle getWidth.

Prototype

public float getWidth() 

Source Link

Document

Returns the width of the rectangle.

Usage

From source file:com.krawler.spring.exportFuctionality.ExportRecord.java

License:Open Source License

public ByteArrayOutputStream exportCashFlow(JSONObject jobj, String logoPath, String comName,
        HttpServletRequest request) throws DocumentException, ServiceException, IOException {
    ByteArrayOutputStream baos = null;
    double total = 0;
    Document document = null;//from  w ww  .  j ava  2  s .  co  m
    PdfWriter writer = null;
    try {

        baos = new ByteArrayOutputStream();
        document = new Document(PageSize.A4, 15, 15, 15, 15);
        writer = PdfWriter.getInstance(document, baos);
        document.open();
        PdfPTable mainTable = new PdfPTable(1);
        mainTable.setWidthPercentage(100);

        PdfPTable tab1 = null;
        Rectangle page = document.getPageSize();

        int bmargin = 15; //border margin
        PdfContentByte cb = writer.getDirectContent();
        cb.rectangle(bmargin, bmargin, page.getWidth() - bmargin * 2, page.getHeight() - bmargin * 2);
        cb.setColorStroke(Color.WHITE);
        cb.stroke();

        PdfPTable table1 = new PdfPTable(2);
        table1.setWidthPercentage(100);
        table1.setWidths(new float[] { 30, 20 });

        PdfPCell blankCell = new PdfPCell();
        blankCell.setBorder(0);
        tab1 = addCompanyLogo(logoPath, comName);
        PdfPCell cell1 = new PdfPCell(tab1);
        cell1.setBorder(0);
        table1.addCell(cell1);
        table1.addCell(blankCell);
        table1.addCell(blankCell);
        table1.addCell(blankCell);

        PdfPCell cell2 = new PdfPCell(new Paragraph(comName, fontSmallRegular));
        cell2.setBorder(0);
        table1.addCell(cell2);
        table1.addCell(blankCell);
        table1.addCell(blankCell);
        table1.addCell(blankCell);

        PdfPCell headerCell = createCell(messageSource.getMessage("acc.dashboard.cashFlowStatement", null,
                RequestContextUtils.getLocale(request)), fontMediumBold, Element.ALIGN_LEFT, 0, 5);
        headerCell.setBorder(0);
        table1.addCell(headerCell);
        table1.addCell(blankCell);
        table1.addCell(blankCell);
        table1.addCell(blankCell);

        table1.addCell(blankCell);
        table1.addCell(blankCell);
        table1.addCell(blankCell);
        table1.addCell(blankCell);

        JSONArray ObjArr = jobj.getJSONArray("data");

        PdfPCell HeaderCell1 = createCell(
                messageSource.getMessage("acc.report.2", null, RequestContextUtils.getLocale(request)),
                fontSmallBold, Element.ALIGN_LEFT, 0, 5);
        HeaderCell1.setBorderWidthLeft(1);
        HeaderCell1.setBorderWidthBottom(1);
        HeaderCell1.setBorderWidthTop(1);
        HeaderCell1.setBorderWidthRight(1);
        PdfPCell HeaderCell2 = createCell(
                messageSource.getMessage("acc.ra.value", null, RequestContextUtils.getLocale(request)),
                fontSmallBold, Element.ALIGN_RIGHT, 0, 5);
        HeaderCell2.setBorderWidthBottom(1);
        HeaderCell2.setBorderWidthTop(1);
        HeaderCell2.setBorderWidthRight(1);

        table1.addCell(HeaderCell1);
        table1.addCell(HeaderCell2);
        PdfPCell objCell1 = null;
        PdfPCell objCell2 = null;
        int objArrLength = ObjArr.length();
        for (int i = 0; i < objArrLength; i++) {
            JSONObject leftObj = ObjArr.getJSONObject(i);
            if (leftObj.has("lfmt") && leftObj.getString("lfmt").equals("title"))
                objCell1 = createBalanceSheetCell(leftObj.getString("lname"), fontSmallBold,
                        Element.ALIGN_CENTER, 0, 5, 0);
            else
                objCell1 = createBalanceSheetCell(leftObj.getString("lname"), fontSmallRegular,
                        Element.ALIGN_LEFT, 0, 5, 0);
            objCell2 = createBalanceSheetCell(leftObj.getString("lvalue"), fontSmallRegular,
                    Element.ALIGN_RIGHT, 0, 0, 0);
            objCell1.setBorderWidthLeft(1);
            objCell2.setBorderWidthRight(1);
            objCell1.setBorderWidthRight(1);
            objCell1.setBorderWidthBottom(1);
            objCell2.setBorderWidthBottom(1);
            if (i != (objArrLength - 1)) {
                table1.addCell(objCell1);
                table1.addCell(objCell2);
            }
        }
        objCell1.setBorderWidthBottom(1);
        objCell2.setBorderWidthBottom(1);
        table1.addCell(objCell1);
        table1.addCell(objCell2);

        PdfPCell mainCell11 = new PdfPCell(table1);
        mainCell11.setBorder(0);
        mainCell11.setPadding(10);
        mainTable.addCell(mainCell11);

        document.add(mainTable);
    } catch (Exception ex) {
        return null;
    } finally {
        if (document != null) {
            document.close();
        }
        if (writer != null) {
            writer.close();
        }
        if (baos != null) {
            baos.close();
        }
    }
    return baos;
}

From source file:com.krawler.spring.exportFunctionality.exportDAOImpl.java

License:Open Source License

public ByteArrayOutputStream getPdfData(JSONArray gridmap, HttpServletRequest request, JSONObject obj)
        throws ServiceException {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    PdfWriter writer = null;/*from   ww w .  j  a  va2s . c  o  m*/
    Document document = null;
    try {
        String colHeader = "";
        String colHeaderFinal = "";
        String fieldListFinal = "";
        String fieldList = "";
        String width = "";
        String align = "";
        String xtype = "";
        String alignFinal = "";
        String xtypeFinal = "";
        String widthFinal = "";
        String colHeaderArrStr[] = null;
        String dataIndexArrStr[] = null;
        String widthArrStr[] = null;
        String alignArrStr[] = null;
        String xtypeArrStr[] = null;
        String htmlCode = "";
        String advStr = "";
        int strLength = 0;
        float totalWidth = 0;

        config = new com.krawler.utils.json.base.JSONObject(request.getParameter("config"));
        if (request.getParameter("searchJson") != null && !request.getParameter("searchJson").equals("")) {
            JSONObject json = new JSONObject(request.getParameter("searchJson"));
            JSONArray advSearch = json.getJSONArray("root");
            for (int i = 0; i < advSearch.length(); i++) {
                JSONObject key = advSearch.getJSONObject(i);
                String value = "";
                String name = key.getString("columnheader");
                name = URLDecoder.decode(name);
                name.trim();
                if (name.contains("*")) {
                    name = name.substring(0, name.indexOf("*") - 1);
                }
                if (name.contains("(") && name.charAt(name.indexOf("(") + 1) == '&') {
                    htmlCode = name.substring(name.indexOf("(") + 3, name.length() - 2);
                    char temp = (char) Integer.parseInt(htmlCode, 10);
                    htmlCode = Character.toString(temp);
                    if (htmlCode.equals("$")) {
                        String currencyid = sessionHandlerImpl.getCurrencyID(request);
                        String currency = currencyRender(key.getString("combosearch"), currencyid);
                        name = name.substring(0, name.indexOf("(") - 1);
                        name = name + "(" + htmlCode + ")";
                        value = currency;
                    } else {
                        name = name.substring(0, name.indexOf("(") - 1);
                        value = name + " " + htmlCode;
                    }
                } else {
                    value = key.getString("combosearch");
                }
                advStr += name + " : " + value + ",";
            }
            advStr = advStr.substring(0, advStr.length() - 1);
            config.remove("subtitles");
            config.put("subtitles", "Filtered By: " + advStr);
        }
        if (request.getParameter("frm") != null && !request.getParameter("frm").equals("")) {
            KWLDateFormat dateFormat = (KWLDateFormat) hibernateTemplate.load(KWLDateFormat.class,
                    sessionHandlerImplObj.getDateFormatID(request));
            String prefDate = dateFormat.getJavaForm();
            Date from = new Date(Long.parseLong(request.getParameter("frm")));
            Date to = new Date(Long.parseLong(request.getParameter("to")));
            config.remove("subtitles");
            String timeFormatId = sessionHandlerImplObj.getUserTimeFormat(request);
            String timeZoneDiff = sessionHandlerImplObj.getTimeZoneDifference(request);
            config.put("subtitles", "Filtered By: From : "
                    + authHandler.getPrefDateFormatter(timeFormatId, timeZoneDiff, prefDate).format(from)
                    + " To : "
                    + authHandler.getPrefDateFormatter(timeFormatId, timeZoneDiff, prefDate).format(to));
        }

        Rectangle rec = null;
        if (config.getBoolean("landscape")) {
            Rectangle recPage = new Rectangle(PageSize.A4.rotate());
            recPage.setBackgroundColor(new java.awt.Color(Integer.parseInt(config.getString("bgColor"), 16)));
            document = new Document(recPage, 15, 15, 30, 30);
            rec = document.getPageSize();
            totalWidth = rec.getWidth();
        } else {
            Rectangle recPage = new Rectangle(PageSize.A4);
            recPage.setBackgroundColor(new java.awt.Color(Integer.parseInt(config.getString("bgColor"), 16)));
            document = new Document(recPage, 15, 15, 30, 30);
            rec = document.getPageSize();
            totalWidth = rec.getWidth();
        }

        writer = PdfWriter.getInstance(document, baos);
        writer.setPageEvent(new EndPage());
        document.open();
        if (config.getBoolean("showLogo")) {
            addComponyLogo(document, request);
        }

        addTitleSubtitle(document);

        if (gridmap != null) {
            for (int i = 0; i < gridmap.length(); i++) {
                JSONObject temp = gridmap.getJSONObject(i);
                colHeader += URLDecoder.decode(temp.getString("title"), "utf-8");
                if (colHeader.indexOf("*") != -1) {
                    colHeader = colHeader.substring(0, colHeader.indexOf("*") - 1) + ",";
                } else {
                    colHeader += ",";
                }
                fieldList += temp.getString("header").replace("$$", "#") + ",";// handled case for custom report. Because dataindex field have "#" symbol and while exporting data URL will break if having # symbol. So replaced # with $$ at JS side and reverted this change at Java side
                if (!config.getBoolean("landscape")) {
                    int totalWidth1 = (int) ((totalWidth / gridmap.length()) - 5.00);
                    width += "" + totalWidth1 + ","; //resize according to page view[potrait]
                } else {
                    width += temp.getString("width") + ",";
                }
                if (temp.optString("align").equals("")) {
                    align += "none" + ",";
                } else {
                    align += temp.getString("align") + ",";
                }
                if (temp.optString("xtype").equals("")) {
                    xtype += "none" + ",";
                } else {
                    xtype += temp.getString("xtype") + ",";
                }
            }
            strLength = colHeader.length() - 1;
            colHeaderFinal = colHeader.substring(0, strLength);
            strLength = fieldList.length() - 1;
            fieldListFinal = fieldList.substring(0, strLength);
            strLength = width.length() - 1;
            widthFinal = width.substring(0, strLength);
            strLength = align.length() - 1;
            alignFinal = align.substring(0, strLength);
            strLength = xtype.length() - 1;
            xtypeFinal = xtype.substring(0, strLength);
            colHeaderArrStr = colHeaderFinal.split(",");
            dataIndexArrStr = fieldListFinal.split(",");
            widthArrStr = widthFinal.split(",");
            alignArrStr = alignFinal.split(",");
            xtypeArrStr = xtypeFinal.split(",");
        } else {
            fieldList = request.getParameter("header");
            colHeader = URLDecoder.decode(request.getParameter("title"));
            width = request.getParameter("width");
            align = request.getParameter("align");
            xtype = request.getParameter("xtype");
            colHeaderArrStr = colHeader.split(",");
            dataIndexArrStr = fieldList.split(",");
            widthArrStr = width.split(",");
            alignArrStr = align.split(",");
            xtypeArrStr = xtype.split(",");
        }

        JSONArray store = null;
        if (obj.isNull("coldata")) {
            store = obj.getJSONArray("data");
        } else {
            store = obj.getJSONArray("coldata");
        }
        addTable(0, colHeaderArrStr.length, 0, store.length(), store, dataIndexArrStr, colHeaderArrStr,
                widthArrStr, alignArrStr, xtypeArrStr, document);

    } catch (DocumentException ex) {
        errorMsg = ex.getMessage();
        throw ServiceException.FAILURE("exportDAOImpl.getPdfData", ex);
    } catch (JSONException e) {
        errorMsg = e.getMessage();
        throw ServiceException.FAILURE("exportDAOImpl.getPdfData", e);
    } catch (Exception e) {
        errorMsg = e.getMessage();
        throw ServiceException.FAILURE("exportDAOImpl.getPdfData", e);
    } finally {
        if (document != null) {
            document.close();
        }
        if (writer != null) {
            writer.close();
        }
    }
    return baos;
}

From source file:com.krawler.spring.exportFunctionality.exportDAOImpl.java

License:Open Source License

public ByteArrayOutputStream getPdfData(JSONArray gridmap, String configStr, String titleStr, String headerStr,
        String widthStr, String alignStr, String xtypeStr, JSONObject obj) throws ServiceException {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    PdfWriter writer = null;/*from   w  w  w  . j  a  v a2s.  c  o m*/
    Document document = null;
    try {
        String colHeader = "";
        String colHeaderFinal = "";
        String fieldListFinal = "";
        String fieldList = "";
        String width = "";
        String align = "";
        String xtype = "";
        String alignFinal = "";
        String xtypeFinal = "";
        String widthFinal = "";
        String colHeaderArrStr[] = null;
        String dataIndexArrStr[] = null;
        String widthArrStr[] = null;
        String alignArrStr[] = null;
        String xtypeArrStr[] = null;
        String htmlCode = "";
        String advStr = "";
        int strLength = 0;
        float totalWidth = 0;

        config = new com.krawler.utils.json.base.JSONObject(configStr);
        Rectangle rec = null;
        if (config.getBoolean("landscape")) {
            Rectangle recPage = new Rectangle(PageSize.A4.rotate());
            recPage.setBackgroundColor(new java.awt.Color(Integer.parseInt(config.getString("bgColor"), 16)));
            document = new Document(recPage, 15, 15, 30, 30);
            rec = document.getPageSize();
            totalWidth = rec.getWidth();
        } else {
            Rectangle recPage = new Rectangle(PageSize.A4);
            recPage.setBackgroundColor(new java.awt.Color(Integer.parseInt(config.getString("bgColor"), 16)));
            document = new Document(recPage, 15, 15, 30, 30);
            rec = document.getPageSize();
            totalWidth = rec.getWidth();
        }

        writer = PdfWriter.getInstance(document, baos);
        writer.setPageEvent(new EndPage());
        document.open();
        //            if (config.getBoolean("showLogo")) {
        //                addComponyLogo(document, request);
        //            }

        addTitleSubtitle(document);

        if (gridmap != null) {
            for (int i = 0; i < gridmap.length(); i++) {
                JSONObject temp = gridmap.getJSONObject(i);
                colHeader += URLDecoder.decode(temp.getString("title"), "utf-8");
                if (colHeader.indexOf("*") != -1) {
                    colHeader = colHeader.substring(0, colHeader.indexOf("*") - 1) + ",";
                } else {
                    colHeader += ",";
                }
                fieldList += temp.getString("header") + ",";
                if (!config.getBoolean("landscape")) {
                    int totalWidth1 = (int) ((totalWidth / gridmap.length()) - 5.00);
                    width += "" + totalWidth1 + ","; //resize according to page view[potrait]
                } else {
                    width += temp.getString("width") + ",";
                }
                if (temp.getString("align").equals("")) {
                    align += "none" + ",";
                } else {
                    align += temp.getString("align") + ",";
                }
                if (temp.getString("xtype").equals("")) {
                    xtype += "none" + ",";
                } else {
                    xtype += temp.getString("xtype") + ",";
                }
            }
            strLength = colHeader.length() - 1;
            colHeaderFinal = colHeader.substring(0, strLength);
            strLength = fieldList.length() - 1;
            fieldListFinal = fieldList.substring(0, strLength);
            strLength = width.length() - 1;
            widthFinal = width.substring(0, strLength);
            strLength = align.length() - 1;
            alignFinal = align.substring(0, strLength);
            xtypeFinal = xtype.substring(0, strLength);
            colHeaderArrStr = colHeaderFinal.split(",");
            dataIndexArrStr = fieldListFinal.split(",");
            widthArrStr = widthFinal.split(",");
            alignArrStr = alignFinal.split(",");
            xtypeArrStr = xtypeFinal.split(",");
        } else {
            fieldList = headerStr;
            colHeader = URLDecoder.decode(titleStr);
            width = widthStr;
            align = alignStr;
            xtype = xtypeStr;
            colHeaderArrStr = colHeader.split(",");
            dataIndexArrStr = fieldList.split(",");
            widthArrStr = width.split(",");
            alignArrStr = align.split(",");
            xtypeArrStr = xtype.split(",");
        }

        JSONArray store = null;
        if (obj.isNull("coldata")) {
            store = obj.getJSONArray("data");
        } else {
            store = obj.getJSONArray("coldata");
        }
        addTable(0, colHeaderArrStr.length, 0, store.length(), store, dataIndexArrStr, colHeaderArrStr,
                widthArrStr, alignArrStr, xtypeArrStr, document);

    } catch (DocumentException ex) {
        errorMsg = ex.getMessage();
        throw ServiceException.FAILURE("exportDAOImpl.getPdfData", ex);
    } catch (JSONException e) {
        errorMsg = e.getMessage();
        throw ServiceException.FAILURE("exportDAOImpl.getPdfData", e);
    } catch (Exception e) {
        errorMsg = e.getMessage();
        throw ServiceException.FAILURE("exportDAOImpl.getPdfData", e);
    } finally {
        if (document != null) {
            document.close();
        }
        if (writer != null) {
            writer.close();
        }
    }
    return baos;
}

From source file:com.krawler.spring.exportFunctionality.exportMPXDAOImpl.java

License:Open Source License

public ByteArrayOutputStream getPdfData(JSONObject grid, HttpServletRequest request, JSONObject obj)
        throws ServiceException {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    PdfWriter writer = null;/*from  ww  w. j  a va  2  s .c o m*/
    Document document = null;
    try {
        JSONArray gridmap = grid == null ? null : grid.getJSONArray("data");
        String colHeader = "";
        String colHeaderFinal = "";
        String fieldListFinal = "";
        String fieldList = "";
        String width = "";
        String align = "";
        String alignFinal = "";
        String widthFinal = "";
        String colHeaderArrStr[] = null;
        String dataIndexArrStr[] = null;
        String widthArrStr[] = null;
        String alignArrStr[] = null;
        int strLength = 0;
        float totalWidth = 0;

        config = new com.krawler.utils.json.base.JSONObject(request.getParameter("config"));
        document = null;
        Rectangle rec = null;
        if (config.getBoolean("landscape")) {
            Rectangle recPage = new Rectangle(PageSize.A4.rotate());
            recPage.setBackgroundColor(new java.awt.Color(Integer.parseInt(config.getString("bgColor"), 16)));
            document = new Document(recPage, 15, 15, 30, 30);
            rec = document.getPageSize();
            totalWidth = rec.getWidth();
        } else {
            Rectangle recPage = new Rectangle(PageSize.A4);
            recPage.setBackgroundColor(new java.awt.Color(Integer.parseInt(config.getString("bgColor"), 16)));
            document = new Document(recPage, 15, 15, 30, 30);
            rec = document.getPageSize();
            totalWidth = rec.getWidth();
        }

        writer = PdfWriter.getInstance(document, baos);
        writer.setPageEvent(new EndPage());
        document.open();
        if (config.getBoolean("showLogo")) {
            addComponyLogo(document, request);
        }

        addTitleSubtitle(document);

        if (gridmap != null) {
            int givenTotalWidth = 0;
            for (int i = 0; i < gridmap.length(); i++) {
                JSONObject temp = gridmap.getJSONObject(i);
                givenTotalWidth += Integer.parseInt(temp.getString("width"));
            }
            double widthRatio = 1;
            if (givenTotalWidth > (totalWidth - 40.00)) {
                widthRatio = (totalWidth - 40.00) / givenTotalWidth; // 40.00 is left + right + table margin [15+15+10] margins of documents
            }
            for (int i = 0; i < gridmap.length(); i++) {
                JSONObject temp = gridmap.getJSONObject(i);
                colHeader += StringUtil.serverHTMLStripper(temp.getString("title"));
                if (colHeader.indexOf("*") != -1) {
                    colHeader = colHeader.substring(0, colHeader.indexOf("*") - 1) + ",";
                } else {
                    colHeader += ",";
                }
                fieldList += temp.getString("header") + ",";
                if (!config.getBoolean("landscape")) {
                    int totalWidth1 = (int) ((totalWidth / gridmap.length()) - 5.00);
                    width += "" + totalWidth1 + ","; //resize according to page view[potrait]
                } else {
                    double adjustedWidth = (Integer.parseInt(temp.getString("width")) * widthRatio);
                    width += ((int) Math.floor(adjustedWidth)) + ",";
                }
                if (temp.getString("align").equals("")) {
                    align += "none" + ",";
                } else {
                    align += temp.getString("align") + ",";
                }
            }
            strLength = colHeader.length() - 1;
            colHeaderFinal = colHeader.substring(0, strLength);
            strLength = fieldList.length() - 1;
            fieldListFinal = fieldList.substring(0, strLength);
            strLength = width.length() - 1;
            widthFinal = width.substring(0, strLength);
            strLength = align.length() - 1;
            alignFinal = align.substring(0, strLength);
            colHeaderArrStr = colHeaderFinal.split(",");
            dataIndexArrStr = fieldListFinal.split(",");
            widthArrStr = widthFinal.split(",");
            alignArrStr = alignFinal.split(",");
        } else {
            fieldList = request.getParameter("header");
            colHeader = request.getParameter("title");
            width = request.getParameter("width");
            align = request.getParameter("align");
            colHeaderArrStr = colHeader.split(",");
            dataIndexArrStr = fieldList.split(",");
            widthArrStr = width.split(",");
            alignArrStr = align.split(",");
        }

        JSONArray store = obj.getJSONArray("data");

        if (grid != null && grid.has("groupdata")) {
            JSONObject groupingConfig = grid.getJSONObject("groupdata");
            addGroupableTable(groupingConfig, 0, colHeaderArrStr.length, 0, store.length(), store,
                    dataIndexArrStr, colHeaderArrStr, widthArrStr, alignArrStr, document, request);
        } else {
            addTable(0, colHeaderArrStr.length, 0, store.length(), store, dataIndexArrStr, colHeaderArrStr,
                    widthArrStr, alignArrStr, document, request);
        }

    } catch (Exception e) {
        throw ServiceException.FAILURE("exportMPXDAOImpl.getPdfData", e);
    } finally {
        if (document != null) {
            document.close();
        }
        if (writer != null) {
            writer.close();
        }
    }
    return baos;
}

From source file:com.matic.sudoku.io.export.PdfExporter.java

License:Open Source License

/**
 * Write board contents to PDF//from   w w w  .  j a v a2s.  co m
 * 
 * @param board The board to write
 * @param targetFile Target output PDF file to write to
 * @throws DocumentException If any PDF library error occurs
 * @throws IOException If any error occurs while writing the PDF file
 */
public void write(final Board board, final File targetFile) throws DocumentException, IOException {
    //FontFactory.defaultEmbedding = true;
    final Document document = new Document(PageSize.A4, DOCUMENT_MARGIN, DOCUMENT_MARGIN, DOCUMENT_MARGIN,
            DOCUMENT_MARGIN);
    final OutputStream outputStream = new FileOutputStream(targetFile);
    final PdfWriter pdfWriter = PdfWriter.getInstance(document, outputStream);

    document.open();

    final PdfContentByte contentByte = pdfWriter.getDirectContent();
    final Rectangle pageSize = document.getPageSize();

    final float pageHeight = pageSize.getHeight();
    final float pageWidth = pageSize.getWidth();

    contentByte.saveState();

    final Graphics2D g2d = contentByte.createGraphics(pageWidth, pageHeight);
    board.setSize((int) pageWidth, (int) pageWidth);
    board.handleResized();

    final int puzzleWidth = board.getPuzzleWidth();

    //Calculate x and y coordinates for centered game board
    final int originX = (int) (pageWidth / 2 - (puzzleWidth / 2));
    final int originY = (int) ((pageHeight / 2) - (puzzleWidth / 2));

    board.setDrawingOrigin(originX, originY);
    board.draw(g2d, true, false);

    contentByte.restoreState();

    g2d.dispose();
    document.close();
    outputStream.flush();
    outputStream.close();
}

From source file:com.matic.sudoku.io.export.PdfExporter.java

License:Open Source License

/**
 * Generate and export multiple boards to PDF
 * //from w w w  .j  av a  2  s.c om
 * @param exporterParameters PDF exporter parameters
 * @param generator Generator used for puzzle generation
 * @throws IOException If any PDF library error occurs
 * @throws DocumentException If any error occurs while writing the PDF file
 */
public void write(final ExporterParameters exporterParameters, final Generator generator,
        final int boardDimension) throws IOException, DocumentException {
    //How many PDF-pages are needed to fit all puzzles using the desired page formatting
    final int optimisticPageCount = exporterParameters.getPuzzleCount()
            / exporterParameters.getPuzzlesPerPage();
    final int pageCount = exporterParameters.getPuzzleCount() % exporterParameters.getPuzzlesPerPage() > 0
            ? optimisticPageCount + 1
            : optimisticPageCount;

    final Document document = new Document(PageSize.A4, DOCUMENT_MARGIN, DOCUMENT_MARGIN, DOCUMENT_MARGIN,
            DOCUMENT_MARGIN);
    final OutputStream outputStream = new FileOutputStream(exporterParameters.getOutputPath());
    final PdfWriter pdfWriter = PdfWriter.getInstance(document, outputStream);

    final String creator = Sudoku.getNameAndVersion();
    document.addSubject("Puzzles generated by " + creator);
    document.addCreator(creator);
    document.open();

    final Rectangle pageSize = document.getPageSize();
    final int pageHeight = (int) pageSize.getHeight();
    final int pageWidth = (int) pageSize.getWidth();

    //Get appropriate number of rows and columns needed to divide a page into
    final int horizontalDimension = exporterParameters.getPuzzlesPerPage() > 2 ? 2 : 1;
    final int verticalDimension = exporterParameters.getPuzzlesPerPage() > 1 ? 2 : 1;

    //Get available space for each board (with margins) on a page
    final int boardWidth = pageWidth / horizontalDimension;
    final int boardHeight = pageHeight / verticalDimension;

    final Board board = new Board(boardDimension, SymbolType.DIGITS);
    board.setSize(boardWidth, boardHeight);
    board.handleResized();

    //Get available height/width on a page for a puzzle itself
    final int puzzleWidth = board.getPuzzleWidth();
    int puzzlesPrinted = 0;

    final PdfContentByte contentByte = pdfWriter.getDirectContent();
    final Grading[] gradings = getGeneratedPuzzleGradings(exporterParameters.getGradings(),
            exporterParameters.getOrdering(), exporterParameters.getPuzzleCount());

    pageCounter: for (int page = 0; page < pageCount; ++page) {
        document.newPage();
        final Graphics2D g2d = contentByte.createGraphics(pageWidth, pageHeight);
        for (int y = 0, i = 0; i < verticalDimension; y += boardHeight, ++i) {
            for (int x = 0, j = 0; j < horizontalDimension; x += boardWidth, ++j) {
                //Check whether to generate a new puzzle or print empty boards 
                final ExportMode exportMode = exporterParameters.getExportMode();
                final Grading selectedGrading = exportMode == ExportMode.BLANK ? null
                        : gradings[puzzlesPrinted];
                if (exportMode == ExportMode.GENERATE_NEW) {
                    board.setPuzzle(generatePuzzle(generator, getSymmetry(exporterParameters.getSymmetries()),
                            selectedGrading));
                    board.recordGivens();
                }

                //Calculate puzzle drawing origins
                final int originX = x + (int) (boardWidth / 2 - (puzzleWidth / 2));
                final int originY = y + (int) (boardHeight / 2) - (puzzleWidth / 2);

                board.setSymbolType(getSymbolType(exporterParameters.getSymbolType()));
                board.setDrawingOrigin(originX, originY);
                board.draw(g2d, false, false);

                drawLegend(g2d,
                        getLegendString(exporterParameters.isShowNumbering(),
                                exporterParameters.isShowGrading(), puzzlesPrinted + 1, selectedGrading),
                        originX, originY, puzzleWidth);

                if (++puzzlesPrinted == exporterParameters.getPuzzleCount()) {
                    //We've printed all puzzles, break
                    g2d.dispose();
                    break pageCounter;
                }
            }
        }
        g2d.dispose();
    }
    document.close();
    outputStream.flush();
    outputStream.close();
}

From source file:com.umlet.control.io.GenPdf.java

License:Open Source License

public void createPdfToStream(OutputStream ostream, DiagramHandler handler) {
    try {/*from   w ww . ja  v  a 2s  .  com*/
        // We get the Rectangle of our DrawPanel
        java.awt.Rectangle bounds = handler.getDrawPanel().getContentBounds(Constants.PRINTPADDING);
        // and create an iText specific Rectangle from (0,0) to (width,height) in which we draw the diagram
        Rectangle drawSpace = new Rectangle((float) bounds.getWidth(), (float) bounds.getHeight());

        // Create document in which we write the pdf
        Document document = new Document(drawSpace);
        PdfWriter writer = PdfWriter.getInstance(document, ostream);
        document.open();

        PdfContentByte cb = writer.getDirectContent();
        Graphics2D graphics2d = cb.createGraphics(drawSpace.getWidth(), drawSpace.getHeight());

        // We shift the diagram to the upper left corner, so we shift it by (minX,minY) of the contextBounds
        Dimension trans = new Dimension((int) bounds.getMinX(), (int) bounds.getMinY());
        graphics2d.translate(-trans.getWidth(), -trans.getHeight());

        handler.getDrawPanel().paintEntitiesIntoGraphics2D(graphics2d);

        graphics2d.dispose();
        document.close();

    } catch (Exception e) {
        System.out.println("UMLet: Error: Exception in outputPdf: " + e);
    }
}

From source file:com.userweave.batch.CreatePDF.java

License:Open Source License

public static void main(String[] args) {
    if (args.length == 0) {
        args = new String[] { "one.pdf", "two.pdf", "out.pdf" };
    }//from  ww  w. j a  v  a 2 s .  com
    if (args.length == 3) {
        try {
            // the document we're watermarking
            PdfReader document = new PdfReader(args[0]);
            int num_pages = document.getNumberOfPages();

            // the watermark (or letterhead, etc.)
            PdfReader mark = new PdfReader(args[1]);
            Rectangle mark_page_size = mark.getPageSize(1);

            // the output document
            PdfStamper writer = new PdfStamper(document, new FileOutputStream(args[2]));

            // create a PdfTemplate from the first page of mark
            // (PdfImportedPage is derived from PdfTemplate)
            PdfImportedPage mark_page = writer.getImportedPage(mark, 1);

            for (int ii = 0; ii < num_pages;) {
                // iterate over document's pages, adding mark_page as
                // a layer 'underneath' the page content; scale mark_page
                // and move it so it fits within the document's page;
                // if document's page is cropped, then this scale might
                // not be small enough

                ++ii;
                Rectangle doc_page_size = document.getPageSize(ii);
                float h_scale = doc_page_size.getWidth() / mark_page_size.getWidth();
                float v_scale = doc_page_size.getHeight() / mark_page_size.getHeight();
                float mark_scale = (h_scale < v_scale) ? h_scale : v_scale;

                float h_trans = (float) ((doc_page_size.getWidth() - mark_page_size.getWidth() * mark_scale)
                        / 2.0);
                float v_trans = (float) ((doc_page_size.getHeight() - mark_page_size.getHeight() * mark_scale)
                        / 2.0);

                PdfContentByte contentByte = writer.getUnderContent(ii);
                contentByte.addTemplate(mark_page, mark_scale, 0, 0, mark_scale, h_trans, v_trans);
            }

            writer.close();
        } catch (Exception ee) {
            ee.printStackTrace();
        }
    } else { // input error
        System.err.println("arguments: in_document in_watermark out_pdf_fn");
    }

}

From source file:com.userweave.domain.service.pdf.ItextUtils.java

License:Open Source License

public OutputStream createPDF(InputStream generatedPDF, InputStream stampPDF, OutputStream out)
        throws IOException, DocumentException {

    // the document we're watermarking
    PdfReader document = new PdfReader(generatedPDF);
    int num_pages = document.getNumberOfPages();

    // the watermark (or letterhead, etc.)
    PdfReader mark = new PdfReader(stampPDF);
    Rectangle mark_page_size = mark.getPageSize(1);

    // the output document
    PdfStamper writer = new PdfStamper(document, out);

    // create a PdfTemplate from the first page of mark
    // (PdfImportedPage is derived from PdfTemplate)
    PdfImportedPage mark_page = writer.getImportedPage(mark, 1);

    for (int ii = 0; ii < num_pages;) {
        // iterate over document's pages, adding mark_page as
        // a layer 'underneath' the page content; scale mark_page
        // and move it so it fits within the document's page;
        // if document's page is cropped, then this scale might
        // not be small enough

        ++ii;/*  ww  w .j  av a 2 s  .  c  o  m*/
        Rectangle doc_page_size = document.getPageSize(ii);
        float h_scale = doc_page_size.getWidth() / mark_page_size.getWidth();
        float v_scale = doc_page_size.getHeight() / mark_page_size.getHeight();
        float mark_scale = (h_scale < v_scale) ? h_scale : v_scale;

        float h_trans = (float) ((doc_page_size.getWidth() - mark_page_size.getWidth() * mark_scale) / 2.0);
        float v_trans = (float) ((doc_page_size.getHeight() - mark_page_size.getHeight() * mark_scale) / 2.0);

        PdfContentByte contentByte = writer.getUnderContent(ii);
        contentByte.addTemplate(mark_page, mark_scale, 0, 0, mark_scale, h_trans, v_trans);
    }

    writer.close();

    return out;

    /*      
                  
                  
                  
                  
              PdfReader reader = new PdfReader(origPDF);
                      
              int n = reader.getNumberOfPages();
                      
              Document document = new Document(reader.getPageSizeWithRotation(1));
              PdfWriter writer = PdfWriter.getInstance(document, outfile);
              writer.setEncryption(PdfWriter.STRENGTH40BITS, "pdf", null,
    PdfWriter.AllowCopy);
              document.open();
              PdfContentByte cb = writer.getDirectContent();
              PdfImportedPage page;
              int rotation;
              int i = 0;
              while (i < n) {
    i++;
    document.setPageSize(reader.getPageSizeWithRotation(i));
    document.newPage();
    page = writer.getImportedPage(reader, i);
    rotation = reader.getPageRotation(i);
    if (rotation == 90 || rotation == 270) {
      cb.addTemplate(page, 0, -1f, 1f, 0, 0,
      reader.getPageSizeWithRotation(i).height());
    } else {
      cb.addTemplate(page, 1f, 0, 0, 1f, 0, 0);
    }
    System.out.println("Processed page " + i);
              }
              document.close();
            } catch( Exception e) {
              e.printStackTrace();
            }
          */

}

From source file:CPS.Core.TODOLists.PDFExporter.java

License:Open Source License

private Document prepareDocument(String filename, final String title, final String author, final String creator,
        final Rectangle pageSize) {

    System.out.println("DEBUG(PDFExporter): Creating document: " + filename);

    Document d = new Document();

    d.setPageSize(pageSize);/* w ww  . j  av  a 2 s.  c  o  m*/
    // TODO alter page orientation?  maybe useful for seed order worksheet

    d.addTitle(title);
    d.addAuthor(author);
    //        d.addSubject( );
    //        d.addKeywords( );
    d.addCreator(creator);

    // left, right, top, bottom - scale in points (~72 points/inch)
    d.setMargins(35, 35, 35, 44);

    try {
        PdfWriter writer = PdfWriter.getInstance(d, new FileOutputStream(filename));
        // add header and footer
        writer.setPageEvent(new PdfPageEventHelper() {
            public void onEndPage(PdfWriter writer, Document document) {
                try {
                    Rectangle page = document.getPageSize();

                    PdfPTable head = new PdfPTable(3);
                    head.getDefaultCell().setBorderWidth(0);
                    head.getDefaultCell().setHorizontalAlignment(PdfPCell.ALIGN_LEFT);
                    head.addCell(new Phrase(author, fontHeadFootItal));

                    head.getDefaultCell().setHorizontalAlignment(PdfPCell.ALIGN_CENTER);
                    head.addCell(new Phrase(title, fontHeadFootReg));

                    head.getDefaultCell().setHorizontalAlignment(PdfPCell.ALIGN_RIGHT);
                    head.addCell("");

                    head.setTotalWidth(page.getWidth() - document.leftMargin() - document.rightMargin());
                    head.writeSelectedRows(0, -1, document.leftMargin(),
                            page.getHeight() - document.topMargin() + head.getTotalHeight(),
                            writer.getDirectContent());

                    PdfPTable foot = new PdfPTable(3);

                    foot.getDefaultCell().setBorderWidth(0);
                    foot.getDefaultCell().setHorizontalAlignment(PdfPCell.ALIGN_LEFT);
                    foot.addCell(new Phrase(creator, fontHeadFootItal));

                    foot.getDefaultCell().setHorizontalAlignment(PdfPCell.ALIGN_CENTER);
                    foot.addCell("");

                    foot.getDefaultCell().setHorizontalAlignment(PdfPCell.ALIGN_RIGHT);
                    foot.addCell(new Phrase("Page " + document.getPageNumber(), fontHeadFootReg));

                    foot.setTotalWidth(page.getWidth() - document.leftMargin() - document.rightMargin());
                    foot.writeSelectedRows(0, -1, document.leftMargin(), document.bottomMargin(),
                            writer.getDirectContent());
                } catch (Exception e) {
                    throw new ExceptionConverter(e);
                }
            }
        });
    } catch (Exception e) {
        e.printStackTrace();
    }

    return d;
}