Example usage for com.lowagie.text Rectangle getHeight

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

Introduction

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

Prototype

public float getHeight() 

Source Link

Document

Returns the height of the rectangle.

Usage

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

License:Open Source License

/**
 * Generate and export multiple boards to PDF
 * //from ww w  .  j  a  v  a 2 s  .co m
 * @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.teag.reports.CashFlows.java

private void page1() {
    CashFlowTable cft = new CashFlowTable();
    ClientBean cb = new ClientBean();
    CFRow row;//from w  w w  . j ava  2s. c om
    CFRow continueRow = null;
    float tallest = 0;

    cb.setPrimaryId(clientID);

    cft.setCb(cb);
    cft.init();
    cft.genTable();

    cft.reset();
    int colCount = MAX_ROWS;

    drawHeader(userInfo.getClientHeading(), "");
    Rectangle agt = placeHeading();

    float baseWidths[] = this.initWidths(colCount - 1);
    float widths[] = this.calcWidths(baseWidths, 11.f * 72);

    Rectangle rct = new Rectangle(prctFull);
    rct.setLeft(_1_4TH);
    rct.setRight(rct.getLeft() + 756);

    Rectangle r = doRow(leList(), widths, agt, 17);
    rct.setTop(r.getBottom());
    r = doRow(agesList(), widths, rct, 17);

    rct.setTop(r.getBottom());

    r = doRow(fiscalYearList(), widths, rct, 17);
    rct.setTop(r.getBottom());

    tallest = tallest < r.getHeight() ? r.getHeight() : tallest;

    while ((row = cft.getRow()) != null) {
        boolean flag;
        if (row.getColNumber() == 0 && row.getIndentLevel() == 0) {
            continueRow = row;
        }

        do {
            flag = false;
            boolean nPage = false;
            String pdfRow[] = buildRow(row, colCount);
            if (row.getHeader().startsWith("III.") && !row.getHeader().endsWith("(cont.)")) {
                nPage = true;
            }
            if (row.getHeader().startsWith("IV.") && !row.getHeader().endsWith("(cont.)")) {
                nPage = true;
            }

            // Rectangle r = doSimpleRow(pdfRow, rct);
            if (nPage) {
                // need to span to a new page
                newPage();
                drawHeader(client, "");
                agt = placeHeading();
                rct.setLeft(_1_4TH);
                rct.setRight(rct.getLeft() + 756);

                r = doRow(leList(), widths, agt, 17);
                rct.setTop(r.getBottom());
                r = doRow(agesList(), widths, rct, 17);
                rct.setTop(r.getBottom());
                r = doRow(fiscalYearList(), widths, rct, 17);
                rct.setTop(r.getBottom());
                tallest = tallest < r.getHeight() ? r.getHeight() : tallest;
                if (continueRow != null) {
                    if (!row.equals(continueRow)) {
                        row = continueRow;
                        row.setHeader(row.getHeader() + " (cont.)");
                        flag = true;

                    }
                }
                nPage = false;
            }

            r = this.doRow(pdfRow, widths, rct, colCount - 1);
            tallest = tallest < r.getHeight() ? r.getHeight() : tallest;
            rct.setTop(r.getBottom());

            if (rct.getTop() < (.5f * 72) + tallest) {
                // need to span to a new page
                newPage();
                drawHeader(client, "");
                agt = placeHeading();

                rct.setLeft(_1_4TH);
                rct.setRight(rct.getLeft() + 756);

                r = doRow(leList(), widths, agt, 17);
                rct.setTop(r.getBottom());
                r = doRow(agesList(), widths, rct, 17);
                rct.setTop(r.getBottom());
                r = doRow(fiscalYearList(), widths, rct, 17);
                rct.setTop(r.getBottom());
                tallest = tallest < r.getHeight() ? r.getHeight() : tallest;

                if (continueRow != null) {
                    if (!row.equals(continueRow)) {
                        row = continueRow;
                        row.setHeader(row.getHeader() + " (cont.)");
                        flag = true;
                    }
                }
            }
        } while (flag == true);
    }
    cft.cleanUp();
}

From source file:com.teag.reports.EstatePlan.java

private void page1() {
    EstatePlanTable ept = new EstatePlanTable();
    ClientBean cb = new ClientBean();
    CFRow row;/*from  w  w w  .  j a  v a 2 s  .  c  om*/
    float tallest = 0;

    drawHeader(client, "");
    String header = "Estimate Of Cash Flows - Scenario #2 After (in 000's)";

    Rectangle agt = placeHeading(header);
    cb.setPrimaryId(clientID);
    cb.initialize();

    ept.setClient(cb);
    ept.setScenarioId(epg.getScenarioId());
    ept.setEstate(epg);
    ept.initialize();
    ept.resetRows();

    int colCount = MAX_COLS;

    float baseWidths[] = this.initWidths(colCount - 1);
    float widths[] = this.calcWidths(baseWidths, 11.0f * 72);

    Rectangle rct = new Rectangle(prctFull);
    rct.setLeft(_1_4TH);
    rct.setRight(rct.getLeft() + 756);
    Rectangle r = doRow(leList(), widths, agt, colCount - 1);
    rct.setTop(r.getBottom());
    r = doRow(agesList(), widths, rct, colCount - 1);
    rct.setTop(r.getBottom());
    r = doRow(fiscalYearList(), widths, rct, colCount - 1);
    rct.setTop(r.getBottom());
    tallest = tallest < r.getHeight() ? r.getHeight() : tallest;

    boolean nPage = false;

    while ((row = ept.getRow()) != null) {
        if (rct.getTop() < (.5f * 72) + tallest) {
            // need to span to a new page
            newPage();
            drawHeader(client, "");
            header = "Estimate Of Net Worth - Scenario #2 After (in 000's)";
            agt = placeHeading(header);
            rct = new Rectangle(prctFull);
            rct.setLeft(_1_4TH);
            rct.setRight(rct.getLeft() + 756);
            r = doRow(leList(), widths, agt, colCount - 1);
            rct.setTop(r.getBottom());
            r = doRow(agesList(), widths, rct, colCount - 1);
            rct.setTop(r.getBottom());
            r = doRow(fiscalYearList(), widths, rct, colCount - 1);
            rct.setTop(r.getBottom());
            tallest = tallest < r.getHeight() ? r.getHeight() : tallest;
            nPage = true;
        }
        String pdfRow[] = buildRow(row, colCount);
        //Rectangle r = doSimpleRow(pdfRow, rct);

        if ((row.getHeader().startsWith("III.") || row.getHeader().startsWith("IV."))
                || row.getHeader().startsWith("II") && !nPage) {
            //              need to span to a new page
            newPage();
            drawHeader(client, "");
            header = "Estimate Of Net Worth - Scenario #2 After (in 000's)";
            agt = placeHeading(header);
            rct = new Rectangle(prctFull);
            rct.setLeft(_1_4TH);
            rct.setRight(rct.getLeft() + 756);
            r = doRow(leList(), widths, agt, colCount - 1);
            rct.setTop(r.getBottom());
            r = doRow(agesList(), widths, rct, colCount - 1);
            rct.setTop(r.getBottom());
            r = doRow(fiscalYearList(), widths, rct, colCount - 1);
            rct.setTop(r.getBottom());
            tallest = tallest < r.getHeight() ? r.getHeight() : tallest;
        }
        nPage = false;

        r = this.doRow(pdfRow, widths, rct, colCount - 1);
        tallest = tallest < r.getHeight() ? r.getHeight() : tallest;
        rct.setTop(r.getBottom());
        /*
        if(rct.getTop() < (.5f * 72) + tallest)
        {
           // need to span to a new page
           newPage();
           drawHeader(client, "");
             header = "Estimate Of Net Worth - Scenario #2 After (in 000's)";
           agt = placeHeading(header);
           rct = new Rectangle(prctFull);
           rct.setLeft(_1_4TH);
           rct.setRight(rct.getLeft() + 756);
           r = doRow(leList(), widths, agt, colCount-1);
           rct.setTop(r.getBottom());
           r = doRow(agesList(),widths,rct,colCount-1);
           rct.setTop(r.getBottom());
           r = doRow(fiscalYearList(),widths,rct,colCount-1);
           rct.setTop(r.getBottom());
           tallest = tallest < r.getHeight() ? r.getHeight() : tallest;
        nPage = true;
        }
        */

    }
}

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

License:Open Source License

public void createPdfToStream(OutputStream ostream, DiagramHandler handler) {
    try {/*from   w  w  w.j a v a2 s  .  co  m*/
        // 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   w  ww  .j  a  v  a  2 s.c o  m*/
    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;/*from w  w  w .  j a  v 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);/*from w w w.  jav  a 2s . co 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;
}

From source file:de.unigoettingen.sub.commons.contentlib.pdflib.PDFManager.java

License:Apache License

/******************************************************************************************************
 * Adds the all pages.//from w  ww  . j  a v a 2s .co  m
 * 
 * @param pagesizemode {@link PdfPageSize}
 * @param writer {@link PdfWriter}
 * @param pdfdoc {@link Document}
 * @return {@link PdfPageLabels}
 * 
 * 
 * @throws ImageInterpreterException the image interpreter exception
 * @throws IOException Signals that an I/O exception has occurred.
 * @throws MalformedURLException the malformed url exception
 * @throws PDFManagerException the PDF manager exception
 * @throws ImageManagerException
 *******************************************************************************************************/
private PdfPageLabels addAllPages(PdfPageSize pagesizemode, PdfWriter writer, Document pdfdoc,
        Watermark myWatermark) throws ImageInterpreterException, IOException, MalformedURLException,
        PDFManagerException, ImageManagerException {

    PdfPageLabels pagelabels = new PdfPageLabels();
    int pageadded = 0;

    // sort the HashMap by the KeySet (pagenumber)
    Map<Integer, UrlImage> sortedMap = new TreeMap<Integer, UrlImage>(imageURLs);

    float scalefactor = 1; // scaling factor of the image
    int page_w = PaperSize.A4.width;
    int page_h = PaperSize.A4.height;
    LOGGER.debug("iterate over " + imageURLs.size() + " pages.");
    for (Integer imageKey : sortedMap.keySet()) {

        Watermark watermark = myWatermark;
        Image pdfImage = null; // PDF-Image
        LOGGER.debug("Writing page " + imageKey);

        boolean errorPage = false; // true if the image does not exists
        URL errorUrl = null; // url of the image that does not exists

        // ------------------------------------------------------------------------------------------------
        // Title page available. Render it in pdftitlepage
        // ------------------------------------------------------------------------------------------------
        if ((pdftitlepages != null) && (pdftitlepages.get(imageKey) != null)) {
            // title page
            PDFTitlePage pdftitlepage = pdftitlepages.get(imageKey);
            // create new PDF page
            try {
                pdfdoc.setPageSize(PageSize.A4);
                pdfdoc.setMargins(pdftitlepage.getLeftMargin(), pdftitlepage.getRightMargin(),
                        pdftitlepage.getTopMargin(), pdftitlepage.getBottomMargin());
                pageadded++;
                pdfdoc.newPage(); // create new page
                // set page name
                pagelabels.addPageLabel(pageadded, PdfPageLabels.EMPTY, "-");
            } catch (Exception e1) {
                throw new PDFManagerException("PDFManagerException occured while creating new page in PDF", e1);
            }
            // render title page
            pdftitlepage.render(pdfdoc);
        }

        // ------------------------------------------------------------------------------------------------
        // Process image with imageKey
        // ------------------------------------------------------------------------------------------------
        UrlImage pdfpage = imageURLs.get(imageKey);
        if (pdfpage.getURL() != null) {
            boolean added = false;
            boolean scaled = false;
            URL url = pdfpage.getURL();
            // pdf hack
            if (ContentServerConfiguration.getInstance().getUsePdf()) {
                LOGGER.debug("trying to find original pdf");
                PdfContentByte pdfcb = null;
                PdfReader pdfreader = null;
                PdfImportedPage importpage = null;
                try {
                    String pdfpath = ContentServerConfiguration.getInstance().getRepositoryPathPdf()
                            .replace("file:///", "");
                    LOGGER.debug("looking in " + pdfpath + " for pdf file");
                    String tiffPath = ContentServerConfiguration.getInstance().getRepositoryPathImages()
                            .replace("file:///", "");
                    // String urlString = url.toString();
                    int pageNumber = pdfpage.getPageNumber();
                    // UrlImage copy = new PDFPage(pdfpage);
                    URL pdfurl = new URL(url.toString().replace(tiffPath, pdfpath)
                            .replace(url.toString().substring(url.toString().lastIndexOf(".")), ".pdf"));
                    LOGGER.debug("pdfurl = " + pdfurl);

                    if (new File(pdfurl.toURI()).exists()) {
                        LOGGER.debug("found pdf " + pdfurl.toURI());
                        // copy.setURL(pdfurl);
                        pdfcb = writer.getDirectContent();
                        pdfreader = new PdfReader(pdfurl);
                        importpage = writer.getImportedPage(pdfreader, pageNumber);

                        LOGGER.debug("creating orig pdf page");
                        Rectangle rect = pdfreader.getPageSize(pageNumber);
                        try {
                            pdfdoc.setPageSize(rect);
                            pdfdoc.newPage(); // create new page
                        } catch (Exception e1) {
                            throw new PDFManagerException("Exception occured while creating new page in PDF",
                                    e1);
                        }
                        pageadded++;
                        pdfcb.addTemplate(importpage, 0, 0);
                        added = true;
                        LOGGER.debug("page:" + imageKey + "  url: " + pdfurl.toString());

                    }
                } catch (URISyntaxException e) {
                    LOGGER.debug(e);
                    added = false;
                } finally {
                    if (writer != null) {
                        writer.freeReader(pdfreader);
                        writer.flush();
                    }
                    if (pdfreader != null) {
                        pdfreader.close();
                    }
                }
            }
            if (!added) {
                // image file
                LOGGER.debug("using image to create pdf page");
                // try to get ImageInterpreter from url
                ImageInterpreter myInterpreter = ImageFileFormat.getInterpreter(url, httpproxyhost,
                        httpproxyport, httpproxyuser, httpproxypassword);

                try {
                    // check preferred compression type depending on color depth
                    Embedd preferredEmbeddingType = Embedd.ORIGBYTESTREAM;
                    if (myInterpreter.getColordepth() == 1) {
                        // bitonal image
                        preferredEmbeddingType = embeddBitonalImage;
                    } else if ((myInterpreter.getColordepth() > 1)
                            && (myInterpreter.getSamplesperpixel() == 1)) {
                        // greyscale image
                        preferredEmbeddingType = embeddGreyscaleImage;
                    } else {
                        // color image
                        preferredEmbeddingType = embeddColorImage;
                    }

                    // -------------------------------------------------------------------------------------
                    // Try to generate image
                    // -------------------------------------------------------------------------------------
                    pdfImage = generatePdfImageFromInterpreter(myInterpreter, preferredEmbeddingType, errorPage,
                            watermark, errorUrl);

                    // -------------------------------------------------------------------------------------
                    // image couldn't be embedded yet (emergencyCase)
                    // -------------------------------------------------------------------------------------
                    if (pdfImage == null) {
                        LOGGER.warn(
                                "Couldn't use preferred method for embedding the image. Instead had to use JPEG or RenderedImage");

                        // Get Interpreter and rendered Image
                        // ---------------------------------------------------------------------------------------------------------------------------------
                        RenderedImage ri = null;
                        if (preferredEmbeddingType == embeddBitonalImage) {
                            ImageManager sourcemanager = new ImageManager(url);
                            boolean watermarkscale = ContentServerConfiguration.getInstance()
                                    .getScaleWatermark(); // should we scale
                            // the watermark ?
                            ri = sourcemanager.scaleImageByPixel(3000, 0, ImageManager.SCALE_BY_WIDTH, 0, null,
                                    null, watermark, watermarkscale, ImageManager.BOTTOM);
                            myInterpreter = sourcemanager.getMyInterpreter();
                        } else {
                            ri = myInterpreter.getRenderedImage();
                            if (watermark != null) {
                                ri = addwatermark(ri, watermark, 2);
                                myInterpreter.setHeight(
                                        myInterpreter.getHeight() + watermark.getRenderedImage().getHeight());
                            }
                        }

                        // scale rendered image
                        // ---------------------------------------------------------------------------------------------------------------------------------
                        // float scalefactorX = 1;
                        // float scalefactorY = 1;
                        // switch (pagesizemode) {
                        // case ORIGINAL:
                        // scalefactorX = 72f / myInterpreter.getXResolution();
                        // scalefactorY = 72f / myInterpreter.getYResolution();
                        // break;
                        // default:
                        // /*
                        // * check, if the image needs to be scaled, because
                        // * it's bigger than A4 calculate the new scalefactor
                        // */
                        // float page_w_pixel = (float) (page_w *
                        // myInterpreter.getXResolution() / 25.4);
                        // float page_h_pixel = (float) (page_h *
                        // myInterpreter.getYResolution() / 25.4);
                        //
                        // float res_x = myInterpreter.getXResolution();
                        // float res_y = myInterpreter.getYResolution();
                        //
                        // long w = myInterpreter.getWidth(); // get height and
                        // // width
                        // long h = myInterpreter.getHeight();
                        //
                        // if ((w > page_w_pixel) || (h > page_h_pixel)) {
                        // LOGGER.debug("scale image to fit the page");
                        // float scalefactor_w = page_w_pixel / w;
                        // float scalefactor_h = page_h_pixel / h;
                        // if (scalefactor_h < scalefactor_w) {
                        // scalefactor = scalefactor_h;
                        // } else {
                        // scalefactor = scalefactor_w;
                        // }
                        // w = (long) (w * scalefactor);
                        // h = (long) (h * scalefactor);
                        // }
                        // scalefactorX = (72f / res_x) * scalefactor;
                        // scalefactorY = (72f / res_y) * scalefactor;
                        // break;
                        // }
                        // //scalefactorX = 0.2f;
                        // //scalefactorY = 0.2f;
                        // if (preferredEmbeddingType == embeddBitonalImage) {
                        // ImageManager sourcemanager = new ImageManager(url);
                        // ri = sourcemanager.scaleImageByPixel((int)
                        // (scalefactorX*100), (int) (scalefactorY*100),
                        // ImageManager.SCALE_BY_PERCENT, 0, null, null,
                        // watermark, true, ImageManager.BOTTOM);
                        // }else{
                        // ri = ImageManipulator.scaleInterpolationBilinear(ri,
                        // scalefactorX, scalefactorY);
                        // }
                        // myInterpreter.setHeight(ri.getHeight());
                        // myInterpreter.setWidth(ri.getWidth());
                        // scaled = true;

                        // add Watermark
                        // ---------------------------------------------------------------------------------------------------------------------------------
                        // ri = addwatermark(ri, watermark,
                        // ImageManager.BOTTOM);
                        // myInterpreter.setHeight(myInterpreter.getHeight() +
                        // watermark.getRenderedImage().getHeight());

                        // Try to write into pdfImage
                        // ---------------------------------------------------------------------------------------------------------------------------------
                        if (myInterpreter.getColordepth() > 1) {
                            // compress image if greyscale or color
                            ByteArrayOutputStream bytesoutputstream = new ByteArrayOutputStream();
                            // JpegInterpreter jpint = new JpegInterpreter(ri);
                            // jpint.setXResolution(myInterpreter.getXResolution());
                            // jpint.setYResolution(myInterpreter.getYResolution());
                            // jpint.writeToStream(null, bytesoutputstream);
                            LOGGER.error("WritingJPEGImage");
                            writeJpegFromRenderedImageToStream(bytesoutputstream, ri, null, myInterpreter);
                            byte[] returnbyteArray = bytesoutputstream.toByteArray();
                            if (bytesoutputstream != null) {
                                bytesoutputstream.flush();
                                bytesoutputstream.close();
                            }
                            pdfImage = Image.getInstance(returnbyteArray);
                            returnbyteArray = null;
                        } else {
                            // its bitonal, but can't be embedded directly,
                            // need to go via RenderedImage
                            BufferedImage buffImage = ImageManipulator.fromRenderedToBuffered(ri);
                            pdfImage = Image.getInstance(buffImage, null, false);
                            if (myWatermark != null) {
                                // create Image for Watermark
                                JpegInterpreter jpint = new JpegInterpreter(myWatermark.getRenderedImage());
                                ByteArrayOutputStream bytesoutputstream = new ByteArrayOutputStream();
                                jpint.setXResolution(myInterpreter.getXResolution());
                                jpint.setYResolution(myInterpreter.getYResolution());
                                jpint.writeToStream(null, bytesoutputstream);
                                byte[] returnbyteArray = bytesoutputstream.toByteArray();
                                jpint.clear();
                                if (bytesoutputstream != null) {
                                    bytesoutputstream.flush();
                                    bytesoutputstream.close();
                                }
                                Image blaImage = Image.getInstance(returnbyteArray);
                                returnbyteArray = null;
                                // set Watermark as Footer at fixed position
                                // (200,200)
                                Chunk c = new Chunk(blaImage, 200, 200);
                                Phrase p = new Phrase(c);
                                HeaderFooter hf = new HeaderFooter(p, false);
                                pdfdoc.setFooter(hf);
                            }
                            // pdfdoc.setPageSize(arg0)
                            // TODO das scheint nicht zu funktionieren... sollte
                            // dieser Code entfernt werden?

                        }
                    } // end of : if (pdfImage == null) {
                } catch (BadElementException e) {
                    throw new PDFManagerException("Can't create a PDFImage from a Buffered Image.", e);
                } catch (ImageManipulatorException e) {
                    LOGGER.warn(e);
                }

                // ---------------------------------------------------------------------------------------------------------
                // place the image on the page
                // ---------------------------------------------------------------------------------------------------------
                if (pagesizemode == PdfPageSize.ORIGINAL) {
                    // calculate the image width and height in points, create
                    // the rectangle in points

                    Rectangle rect = null;
                    if (!scaled) {
                        float image_w_points = (myInterpreter.getWidth() / myInterpreter.getXResolution()) * 72;
                        float image_h_points = ((myInterpreter.getHeight()) / myInterpreter.getYResolution())
                                * 72;
                        rect = new Rectangle(image_w_points, image_h_points);
                    } else {
                        rect = new Rectangle(myInterpreter.getWidth(), myInterpreter.getHeight());
                    }

                    // create the pdf page according to this rectangle
                    LOGGER.debug("creating original page sized PDF page:" + rect.getWidth() + " x "
                            + rect.getHeight());
                    pdfdoc.setPageSize(rect);

                    // create new page to put the content
                    try {
                        pageadded++;
                        pdfdoc.newPage();
                    } catch (Exception e1) {
                        throw new PDFManagerException(
                                "DocumentException occured while creating page " + pageadded + " in PDF", e1);
                    }

                    // scale image and place it on page; scaling the image does
                    // not scale the images bytestream
                    if (!scaled) {
                        pdfImage.scalePercent((72f / myInterpreter.getXResolution() * 100),
                                (72f / myInterpreter.getYResolution() * 100));
                    }
                    pdfImage.setAbsolutePosition(0, 0); // set image to lower
                                                        // left corner

                    boolean result;
                    try {
                        result = pdfdoc.add(pdfImage); // add it to PDF
                        if (!result) {
                            throw new PDFManagerException("Image \"" + url.toString()
                                    + "\" can's be added to PDF! Error during placing image on page");
                        }
                    } catch (DocumentException e) {
                        throw new PDFManagerException("DocumentException occured while adding the image to PDF",
                                e);
                    }
                } else {
                    /*
                     * it is not the original page size PDF will contain only A4 pages
                     */
                    LOGGER.debug("creating A4 pdf page");

                    // create new page to put the content
                    try {
                        pageadded++;
                        pdfdoc.setPageSize(PageSize.A4);
                        pdfdoc.newPage(); // create new page
                    } catch (Exception e1) {
                        throw new PDFManagerException("Exception occured while creating new page in PDF", e1);
                    }

                    float page_w_pixel = (float) (page_w * myInterpreter.getXResolution() / 25.4);
                    float page_h_pixel = (float) (page_h * myInterpreter.getYResolution() / 25.4);

                    float res_x = myInterpreter.getXResolution();
                    float res_y = myInterpreter.getYResolution();

                    long w = myInterpreter.getWidth(); // get height and width
                    long h = myInterpreter.getHeight();

                    /*
                     * if the page is landscape, we have to rotate the page; this is only done in PDF, the orig image bytestream is NOT rotated
                     */
                    if (w > h) {
                        LOGGER.debug("rotate image");
                        // must be rotated
                        pdfImage.setRotationDegrees(90);
                        // change width and height
                        long dummy = w;
                        w = h;
                        h = dummy;
                        // change the resolutions x and y
                        float dummy2 = res_x;
                        res_x = res_y;
                        res_y = dummy2;
                    }

                    /*
                     * check, if the image needs to be scaled, because it's bigger than A4 calculate the new scalefactor
                     */
                    if ((w > page_w_pixel) || (h > page_h_pixel)) {
                        LOGGER.debug("scale image to fit the page");
                        float scalefactor_w = page_w_pixel / w;
                        float scalefactor_h = page_h_pixel / h;
                        if (scalefactor_h < scalefactor_w) {
                            scalefactor = scalefactor_h;
                        } else {
                            scalefactor = scalefactor_w;
                        }
                        w = (long) (w * scalefactor);
                        h = (long) (h * scalefactor);
                    }
                    if (!scaled) {
                        pdfImage.scalePercent((72f / res_x * 100) * scalefactor,
                                (72f / res_y * 100) * scalefactor);
                    }

                    // center the image on the page
                    // ---------------------------------------------------------------
                    float y_offset = 0; // y - offset
                    // get image size in cm; height
                    float h_cm = (float) (h / (res_x / 2.54));
                    // float w_cm = (float) (w / (res_y / 2.54)); // and width
                    if ((h_cm + 2) < (page_h / 10)) {
                        y_offset = 2 * 72f / 2.54f;
                    }
                    float freespace_x = ((page_w_pixel - w) / res_x * 72f);
                    float freespace_y = ((page_h_pixel - h) / res_y * 72f) - (y_offset);
                    // set position add image
                    pdfImage.setAbsolutePosition(freespace_x / 2, freespace_y);
                    boolean result;
                    try {
                        result = pdfdoc.add(pdfImage);
                    } catch (DocumentException e) {
                        LOGGER.error(e);
                        throw new PDFManagerException("DocumentException occured while adding the image to PDF",
                                e);
                    }
                    if (!result) {
                        // placing the image in the PDF was not successful
                        throw new PDFManagerException("Image \"" + url.toString()
                                + "\" can's be added to PDF! Error during placing image on page");
                    }

                    // draw box around the image page
                    // ------------------------------------------------------------------------------------------------
                    if (pagesizemode == PdfPageSize.A4BOX) {
                        LOGGER.debug("draw box around the image page");

                        // draw a black frame around the image
                        PdfContentByte pcb = writer.getDirectContent();

                        // calculate upper left corner of the box (measurment is
                        // in points)
                        float left_x = (freespace_x / 2);
                        float left_y = freespace_y;

                        // calculate the lower right corner of the box
                        // (measurement is in points)
                        float image_w_points = (w / res_x) * 72;
                        float image_h_points = (h / res_y) * 72;

                        pcb.setLineWidth(1f);
                        pcb.stroke();
                        pcb.rectangle(left_x, left_y, image_w_points, image_h_points);

                        pcb.stroke();
                    }

                } // end of: if (pagesizemode == PdfPageSize.ORIGINAL) {
                pdfImage = null;
                myInterpreter.clear();
                // writer.freeReader(new PdfReader(pdfpage.getURL()));
            } // end of : if (pdfpage.getURL() != null) {

            // ------------------------------------------------------------------------------------------------
            // it is a page from a PDF file which should be inserted
            // ------------------------------------------------------------------------------------------------
            else if (pdfpage.getClass() == PDFPage.class && ((PDFPage) pdfpage).getPdfreader() != null) {

                PdfContentByte pdfcb = writer.getDirectContent();

                PdfReader pdfreader = ((PDFPage) pdfpage).getPdfreader();
                PdfImportedPage importpage = writer.getImportedPage(pdfreader, pdfpage.getPageNumber());

                if (pagesizemode == PdfPageSize.ORIGINAL) {
                    LOGGER.debug("creating orig pdf page");
                    Rectangle rect = pdfreader.getPageSize(pdfpage.getPageNumber());
                    try {
                        pdfdoc.setPageSize(rect);
                        pdfdoc.newPage(); // create new page
                    } catch (Exception e1) {
                        throw new PDFManagerException("Exception occured while creating new page in PDF", e1);
                    }
                    // add content
                    pageadded++;
                    pdfcb.addTemplate(importpage, 0, 0);

                } else {
                    LOGGER.debug("creating A4 pdf page");
                    try {
                        pdfdoc.setPageSize(PageSize.A4);
                        pdfdoc.newPage(); // create new page
                    } catch (Exception e1) {
                        throw new PDFManagerException("Exception occured while creating new page in PDF", e1);
                    }

                    // add content
                    pageadded++;
                    pdfcb.addTemplate(importpage, 0, 0);

                    // draw box
                    // if (pagesizemode == PdfPageSize.A4BOX) {
                    // FIXME: nichts implementiert ?
                    // }
                }

            }
            // handle pagename
            if (imageNames != null) {
                String pagename = imageNames.get(imageKey);

                if (pagename != null) {
                    pagelabels.addPageLabel(pageadded, PdfPageLabels.EMPTY, pagename);
                } else {
                    pagelabels.addPageLabel(pageadded, PdfPageLabels.EMPTY, "unnumbered");
                }
            }
            // handle bookmarks and set destinator for bookmarks
            LOGGER.debug("handle bookmark(s) for page");

            PdfDestination destinator = new PdfDestination(PdfDestination.FIT);
            setBookmarksForPage(writer, destinator, imageKey); // the key in the
            writer.flush();
            // mashMap is the pagenumber

        } // end of while iterator over all pages

    }
    return pagelabels;

}

From source file:es.gob.afirma.signers.pades.PdfPreProcessor.java

License:Open Source License

/** Sobreimpone una imagen en un documento PDF.
 * @param extraParams Datos de la imagen a a&ntilde;adir como <a href="doc-files/extraparams.html">par&aacute;metros adicionales</a>
 * @param stp Estampador de PDF, debe abrirse y cerrarse fuera de este m&eacute;todo
 * @throws IOException Cuando ocurren errores de entrada / salida */
static void addImage(final Properties extraParams, final PdfStamper stp) throws IOException {

    if (extraParams == null || stp == null) {
        return;/*from  w ww  .  j ava  2 s .  com*/
    }

    final String imageDataBase64 = extraParams.getProperty("image"); //$NON-NLS-1$
    if (imageDataBase64 == null || imageDataBase64.length() < 1) {
        return;
    }
    final byte[] image = Base64.decode(imageDataBase64);

    final Rectangle rect = getPositionOnPage(extraParams, "image"); //$NON-NLS-1$

    if (rect == null) {
        return;
    }

    final String imagePage = extraParams.getProperty("imagePage"); //$NON-NLS-1$
    if (imagePage == null) {
        return;
    }

    final int pageNum;
    try {
        pageNum = Integer.parseInt(imagePage);
    } catch (final NumberFormatException e) {
        throw new IOException(
                "Se ha indicado un numero de pagina con formato invalido para insertar la imagen (" + imagePage //$NON-NLS-1$
                        + "): " + e, //$NON-NLS-1$
                e);
    }

    addImage(image, (int) rect.getWidth(), (int) rect.getHeight(), (int) rect.getLeft(), (int) rect.getBottom(),
            pageNum, null, stp);

    LOGGER.info("Anadida imagen al PDF antes de la firma"); //$NON-NLS-1$
}

From source file:it.eng.spagobi.engines.documentcomposition.exporterUtils.PdfCreator.java

License:Mozilla Public License

public FileOutputStream createPdfFile(FileOutputStream fileOutputStream,
        Map<String, DocumentContainer> documentsMap, boolean defaultStyle)
        throws MalformedURLException, IOException, DocumentException {

    logger.debug("IN");

    Document document = new Document(PageSize.A4.rotate());
    Rectangle rect = document.getPageSize();
    docWidth = rect.getWidth();/*w  w w  .ja v  a 2  s  .c o m*/
    docHeight = rect.getHeight();

    logger.debug("document size width: " + docWidth + " height: " + docHeight);

    //PdfWriter writer=PdfWriter.getInstance(document,new FileOutputStream("C:/comp/SpagoBIProva.pdf"));
    PdfWriter writer = PdfWriter.getInstance(document, fileOutputStream);
    document.open();

    int documentsNumber = documentsMap.keySet().size();
    int columnnsNumber = 2;

    if (defaultStyle == true) {
        logger.debug("use default style");
        int cellsCounter = 0;

        PdfPTable table = new PdfPTable(columnnsNumber);
        table.setWidthPercentage(100);

        for (Iterator iterator = documentsMap.keySet().iterator(); iterator.hasNext();) {
            String label = (String) iterator.next();
            DocumentContainer docContainer = documentsMap.get(label);
            byte[] content = docContainer.getContent();
            if (content != null) {
                Image img = null;
                try {
                    img = Image.getInstance(content);
                    table.addCell(img);
                } catch (Exception e) {
                    logger.debug("Trying to evaluate response as a PDF file... ");
                    table.addCell("");
                    //                  try {
                    //                     PdfReader reader = new PdfReader(content);
                    //                     PdfImportedPage page = writer.getImportedPage(reader, 1);
                    //                     writer.addPage(page);
                    //                     table.addCell("");
                    //                  } catch (Exception x) {
                    //                     logger.error("Error in inserting image for document " + label, e);
                    //                     logger.error("Error in inserting pdf file for document " + label, x);
                    //                     table.addCell("");
                    //                  }
                }
            }
            cellsCounter++;
        }

        // if cell counter is not pair make it pair
        if (cellsCounter % 2 != 0) {
            table.addCell("");
        }
        document.add(table);

    } else { // ************* NO DEFAULT STYLE *****************
        logger.debug("No default style");

        // I want to calculate total height of scaled heights!!
        //int totalScaledHeight=calculateTotaleScaledHeights(documentsMap, defaultStyle);

        // run on all documents
        for (Iterator iterator = documentsMap.keySet().iterator(); iterator.hasNext();) {
            String label = (String) iterator.next();
            logger.debug("document with label " + label);

            DocumentContainer docContainer = documentsMap.get(label);
            MetadataStyle style = docContainer.getStyle();

            // one table for each image, set at absolute position
            PdfPTable table = new PdfPTable(1);

            // width and height specified for the container by style attribute
            int widthStyle = style.getWidth();
            int heightStyle = style.getHeight();
            logger.debug("style for document width: " + widthStyle + " height: " + heightStyle);

            // width and height for the table scaled to the document size
            int tableWidth = calculatePxSize(docWidth, widthStyle, videoWidth);
            int tableHeight = calculatePxSize(docHeight, heightStyle, videoHeight);

            logger.debug("table for document width: " + tableWidth + " height: " + tableHeight);

            // x and y position as specified for the container by the style attribute
            int yStyle = style.getY();
            int xStyle = style.getX();
            // width and height scaled to the document size
            int xPos = (calculatePxPos(docWidth, xStyle, videoWidth));
            int yPos = (int) docHeight - (calculatePxPos(docHeight, yStyle, videoHeight));
            logger.debug("Table position at x: " + xPos + " y: " + yPos);

            // get the image
            byte[] content = docContainer.getContent();
            if (content != null) {
                Image img = null;
                try {
                    img = Image.getInstance(content);
                } catch (Exception e) {
                    logger.debug("Trying to evaluate response as a PDF file... ");
                    try {
                        PdfReader reader = new PdfReader(content);
                        PdfContentByte cb = writer.getDirectContent();
                        PdfImportedPage page = writer.getImportedPage(reader, 1);
                        float[] tm = getTransformationMatrix(page, xPos, yPos, tableWidth, tableHeight);
                        cb.addTemplate(page, tm[0], tm[1], tm[2], tm[3], tm[4], tm[5]);
                    } catch (Exception x) {
                        logger.error("Error in inserting image for document " + label, e);
                        logger.error("Error in inserting pdf file for document " + label, x);
                    }
                    continue;
                }

                //if it is a REPORT and has more than one page, too large, you have to resize the image, but how to understand it?
                // if image size is more than double of the container size cut the first part,otherwise scale it
                if (docContainer.getDocumentType().equals("REPORT")) {
                    boolean cutImageWIdth = isToCutWidth(img, tableWidth);
                    boolean cutImageHeight = isToCutHeight(img, tableWidth);

                    if (cutImageWIdth == true || cutImageHeight == true) {
                        logger.debug(
                                "Report will be cut to width " + tableWidth + " and height " + tableHeight);
                        try {
                            img = cutImage(content, cutImageHeight, cutImageWIdth, tableHeight, tableWidth,
                                    (int) img.getWidth(), (int) img.getHeight());
                        } catch (Exception e) {
                            logger.error(
                                    "Error in image cut, cutt will be ignored and image will be drawn anyway ",
                                    e);
                        }
                    }
                }

                // this is percentage to resize
                // The image must be size within the cell               
                int percToResize = percentageToResize((int) img.getWidth(), (int) img.getHeight(), tableWidth,
                        tableHeight);
                logger.debug("image will be scaled of percentage " + percToResize);
                img.scalePercent(percToResize);

                PdfPCell cell = new PdfPCell(img);
                cell.setNoWrap(true);
                cell.setFixedHeight(tableHeight);
                cell.setBorderWidth(0);
                cell.setHorizontalAlignment(Element.ALIGN_CENTER);
                cell.setVerticalAlignment(Element.ALIGN_CENTER);
                table.addCell(cell);

                //table.setWidthPercentage(tableWidthPerc);
                table.setTotalWidth(tableWidth);
                table.setLockedWidth(true);
            } else {
                // TODO: setALT!
            }
            logger.debug("Add table");
            table.writeSelectedRows(0, -1, xPos, yPos, writer.getDirectContent());
            logger.debug("Document added");
        }

    }
    document.close();
    logger.debug("OUT");
    return fileOutputStream;
}