protected void drawHyperlink(
      final RenderNode box, final String target, final String window, final String title) {
    if (box.isNodeVisible(getDrawArea()) == false) {
      return;
    }

    final PdfAction action = createActionForLink(target);

    final AffineTransform affineTransform = getGraphics().getTransform();
    final float translateX = (float) affineTransform.getTranslateX();

    final float leftX = translateX + (float) (StrictGeomUtility.toExternalValue(box.getX()));
    final float rightX =
        translateX + (float) (StrictGeomUtility.toExternalValue(box.getX() + box.getWidth()));
    final float lowerY =
        (float) (globalHeight - StrictGeomUtility.toExternalValue(box.getY() + box.getHeight()));
    final float upperY = (float) (globalHeight - StrictGeomUtility.toExternalValue(box.getY()));

    if (action != null) {
      final PdfAnnotation annotation =
          new PdfAnnotation(writer, leftX, lowerY, rightX, upperY, action);
      writer.addAnnotation(annotation);
    } else if (StringUtils.isEmpty(title) == false) {
      final Rectangle rect = new Rectangle(leftX, lowerY, rightX, upperY);
      final PdfAnnotation commentAnnotation =
          PdfAnnotation.createText(writer, rect, "Tooltip", title, false, null);
      commentAnnotation.setAppearance(
          PdfAnnotation.APPEARANCE_NORMAL,
          writer.getDirectContent().createAppearance(rect.getWidth(), rect.getHeight()));
      writer.addAnnotation(commentAnnotation);
    }
  }
Exemplo n.º 2
0
 /**
  * Set the page size to use. This method will use guessFormat to try to guess the correct page
  * format. If no format could be guessed, the sizes from the pageSize are used and the landscape
  * setting is determined by comparing width and height;
  *
  * @param pageSize The pageSize to use
  */
 public void setPageSize(Rectangle pageSize) {
   if (!guessFormat(pageSize, false)) {
     this.pageWidth = (int) (pageSize.getWidth() * RtfElement.TWIPS_FACTOR);
     this.pageHeight = (int) (pageSize.getHeight() * RtfElement.TWIPS_FACTOR);
     this.landscape = pageWidth > pageHeight;
   }
 }
 /**
  * Sets the percentage width of the table from the absolute column width.
  *
  * @param columnWidth the absolute width of each column
  * @param pageSize the page size
  * @throws DocumentException
  */
 public void setWidthPercentage(float columnWidth[], Rectangle pageSize) throws DocumentException {
   if (columnWidth.length != this.relativeWidths.length)
     throw new IllegalArgumentException("Wrong number of columns.");
   float totalWidth = 0;
   for (int k = 0; k < columnWidth.length; ++k) totalWidth += columnWidth[k];
   widthPercentage = totalWidth / (pageSize.getRight() - pageSize.getLeft()) * 100f;
   setWidths(columnWidth);
 }
Exemplo n.º 4
0
  /**
   * Sets the bottom of the Rectangle and determines the proper {link #verticalOffset} to
   * appropriately align the contents vertically.
   *
   * @param value
   */
  public void setBottom(float value) {
    super.setBottom(value);
    float firstLineRealHeight = firstLineRealHeight();

    float totalHeight = ury - value; // can't use top (already compensates for cellspacing)
    float nonContentHeight = (cellpadding() * 2f) + (cellspacing() * 2f);
    nonContentHeight += getBorderWidthInside(TOP) + getBorderWidthInside(BOTTOM);

    float interiorHeight = totalHeight - nonContentHeight;
    float extraHeight = 0.0f;

    switch (verticalAlignment) {
      case Element.ALIGN_BOTTOM:
        extraHeight = interiorHeight - contentHeight;
        break;
      case Element.ALIGN_MIDDLE:
        extraHeight = (interiorHeight - contentHeight) / 2.0f;
        break;
      default: // ALIGN_TOP
        extraHeight = 0f;
    }

    extraHeight += cellpadding() + cellspacing();
    extraHeight += getBorderWidthInside(TOP);
    if (firstLine != null) {
      firstLine.height = firstLineRealHeight + extraHeight;
    }
  }
  /**
   * Populates the templates two boxes with a title and map
   *
   * @param page the parent(owner) page
   * @param map the Map to be drawn
   */
  public void init(Page page, Map map) {
    this.page = page;
    com.lowagie.text.Rectangle paperRectangle = getPaperSize();
    Dimension paperSize =
        new Dimension((int) paperRectangle.getWidth(), (int) paperRectangle.getHeight());
    // set the requested papersize
    page.setPaperSize(paperSize);
    // then apply the ratio of the papersize also to the page size.
    setPageSizeFromPaperSize(page, paperSize);

    float scaleFactor = (float) page.getSize().width / (float) page.getPaperSize().height;

    int height = page.getSize().height;
    int width = page.getSize().width;

    int xPos = getPercentagePieceOf(width, LEFT_MARGIN_PERCENT);
    int yPos = getPercentagePieceOf(height, UPPER_MARGIN_PERCENT);
    int w = getPercentagePieceOf(width, TITLE_WIDTH_PERCENT);
    int h = getPercentagePieceOf(height, TITLE_HEIGHT_PERCENT);
    // the base font size is good for the A4 size, scale every other proportional
    float scaledSize = (float) BASEFONT_SIZE * (float) paperSize.height / PageSize.A4.getHeight();
    // float scaledFontSize = scaleValue(page, paperSize, scaledSize);
    addLabelBox(formatName(map.getName()), xPos, yPos, w, h, (int) scaledSize, scaleFactor);

    xPos = getPercentagePieceOf(width, LEFT_MARGIN_PERCENT);
    yPos = getPercentagePieceOf(height, UPPER_MARGIN_PERCENT + TITLE_HEIGHT_PERCENT);
    w = getPercentagePieceOf(width, MAP_WIDTH_PERCENT);
    h = getPercentagePieceOf(height, MAP_HEIGHT_PERCENT);
    addMapBox(map, xPos, yPos, w, h, paperSize);

    // xPos = getPercentagePieceOf(width, 100f - RIGHT_MARGIN_PERCENT - SPACING_PERCENT * 3f
    // - LEGEND_WIDTH_PERCENT);
    // yPos = getPercentagePieceOf(height, 100f - BOTTOM_MARGIN_PERCENT - SPACING_PERCENT * 3f
    // - LEGEND_HEIGHT_PERCENT);
    // w = getPercentagePieceOf(width, LEGEND_WIDTH_PERCENT);
    // h = getPercentagePieceOf(height, LEGEND_HEIGHT_PERCENT);
    // addLegendBox(xPos, yPos, w, h);

    xPos = getPercentagePieceOf(width, LEFT_MARGIN_PERCENT + SPACING_PERCENT * 2f);
    yPos =
        getPercentagePieceOf(
            height, 100f - BOTTOM_MARGIN_PERCENT - SPACING_PERCENT * 3f - SCALE_HEIGHT_PERCENT);
    w = getPercentagePieceOf(width, SCALE_WIDTH_PERCENT);
    h = getPercentagePieceOf(height, SCALE_HEIGHT_PERCENT);
    addScale(xPos, yPos, w, h);
  }
  @SuppressWarnings("deprecation")
  @Override
  public void calculateSize(PdfContext context) {
    LegendComponent legendComponent = getLegend();
    assert (null != legendComponent)
        : "LegendGraphicComponent must be a descendant of a LegendComponent";

    Rectangle textSize = context.getTextSize(label, legendComponent.getFont());
    float margin = 0.25f * legendComponent.getFont().getSize();
    if (getConstraint().getMarginX() <= 0.0) {
      getConstraint().setMarginX(margin);
    }
    if (getConstraint().getMarginY() <= 0.0) {
      getConstraint().setMarginY(margin);
    }
    setBounds(new Rectangle(textSize.getHeight(), textSize.getHeight()));
  }
 @Override
 public void render(PdfContext context) {
   @SuppressWarnings("deprecation")
   float w = getSize().getWidth();
   @SuppressWarnings("deprecation")
   float h = getSize().getHeight();
   Rectangle iconRect = new Rectangle(0, 0, w, h);
   Color fillColor = Color.white;
   Color strokeColor = Color.black;
   float[] dashArray = null;
   if (styleInfo != null) {
     fillColor =
         context.getColor(styleInfo.getFillColor(), styleInfo.getFillOpacity(), Color.white);
     strokeColor =
         context.getColor(styleInfo.getStrokeColor(), styleInfo.getStrokeOpacity(), Color.black);
     dashArray = context.getDashArray(styleInfo.getDashArray());
   }
   float baseWidth = iconRect.getWidth() / 10;
   // draw symbol
   switch (layerType) {
     case RASTER:
       Image img = context.getImage("/images/layer-raster.png");
       context.drawImage(img, iconRect, null);
       break;
     case POINT:
     case MULTIPOINT:
       drawPoint(context, iconRect, fillColor, strokeColor);
       break;
     case LINESTRING:
     case MULTILINESTRING:
       drawLine(context, iconRect, strokeColor, dashArray);
       break;
     case POLYGON:
     case MULTIPOLYGON:
       context.fillRectangle(iconRect, fillColor);
       context.strokeRectangle(iconRect, strokeColor, baseWidth, dashArray);
       break;
     case GEOMETRY:
       drawPoint(context, iconRect, fillColor, strokeColor);
       drawLine(context, iconRect, strokeColor, dashArray);
       break;
     default:
       log.warn("Cannot draw unknown layerType " + layerType);
   }
 }
 private ByteArrayOutputStream getPdfData(
     JSONArray data, JSONArray res, HttpServletRequest request) throws ServiceException {
   ByteArrayOutputStream baos = new ByteArrayOutputStream();
   try {
     String[] colHeader = getColHeader();
     String[] colIndex = getColIndexes();
     String[] val = getColValues(colHeader, data);
     String[] resources = getResourcesColHeader(res, data);
     String[] mainHeader = {"Dates", "Duration", "Work", "Cost", "Tasks", "Resources"};
     Document document = null;
     if (landscape) {
       Rectangle recPage = new Rectangle(PageSize.A4.rotate());
       recPage.setBackgroundColor(new java.awt.Color(255, 255, 255));
       document = new Document(recPage, 15, 15, 30, 30);
     } else {
       Rectangle recPage = new Rectangle(PageSize.A4);
       recPage.setBackgroundColor(new java.awt.Color(255, 255, 255));
       document = new Document(recPage, 15, 15, 30, 30);
     }
     PdfWriter writer = PdfWriter.getInstance(document, baos);
     writer.setPageEvent(new EndPage());
     document.open();
     if (showLogo) {
       getCompanyDetails(request);
       addComponyLogo(document, request);
     }
     addTitleSubtitle(document);
     addTable(data, resources, colIndex, colHeader, mainHeader, val, document);
     document.close();
     writer.close();
     baos.close();
   } catch (ConfigurationException ex) {
     throw ServiceException.FAILURE("ExportProjectReport.getPdfData", ex);
   } catch (DocumentException ex) {
     throw ServiceException.FAILURE("ExportProjectReport.getPdfData", ex);
   } catch (JSONException e) {
     throw ServiceException.FAILURE("ExportProjectReport.getPdfData", e);
   } catch (IOException e) {
     throw ServiceException.FAILURE("ExportProjectReport.getPdfData", e);
   } catch (Exception e) {
     throw ServiceException.FAILURE("ExportProjectReport.getPdfData", e);
   }
   return baos;
 }
Exemplo n.º 9
0
 public ImageResource getImageResource(String uri) {
   ImageResource resource = null;
   uri = resolveURI(uri);
   resource = (ImageResource) _imageCache.get(uri);
   if (resource == null) {
     InputStream is = resolveAndOpenStream(uri);
     if (is != null) {
       try {
         URL url = new URL(uri);
         if (url.getPath() != null && url.getPath().toLowerCase().endsWith(".pdf")) {
           PdfReader reader = _outputDevice.getReader(url);
           PDFAsImage image = new PDFAsImage(url);
           Rectangle rect = reader.getPageSizeWithRotation(1);
           image.setInitialWidth(rect.getWidth() * _outputDevice.getDotsPerPoint());
           image.setInitialHeight(rect.getHeight() * _outputDevice.getDotsPerPoint());
           resource = new ImageResource(uri, image);
         } else {
           Image image = Image.getInstance(url);
           scaleToOutputResolution(image);
           resource = new ImageResource(uri, new ITextFSImage(image));
         }
         _imageCache.put(uri, resource);
       } catch (IOException e) {
         XRLog.exception("Can't read image file; unexpected problem for URI '" + uri + "'", e);
       } catch (BadElementException e) {
         XRLog.exception("Can't read image file; unexpected problem for URI '" + uri + "'", e);
       } catch (URISyntaxException e) {
         XRLog.exception("Can't read image file; unexpected problem for URI '" + uri + "'", e);
       } finally {
         try {
           is.close();
         } catch (IOException e) {
           // ignore
         }
       }
     }
   }
   if (resource == null) {
     resource = new ImageResource(uri, null);
   }
   return resource;
 }
 private void drawLine(
     PdfContext context, Rectangle iconRect, Color strokeColor, float[] dashArray) {
   float baseWidth = iconRect.getWidth() / 10;
   context.drawRelativePath(
       new float[] {0f, 0.75f, 0.25f, 1f},
       new float[] {0f, 0.25f, 0.75f, 1f},
       iconRect,
       strokeColor,
       baseWidth * 2,
       dashArray);
 }
    public void onStartPage(PdfWriter writer, Document document) {
      try {
        PdfPTable table = new PdfPTable(1);
        table.setWidthPercentage(100);

        PdfPTable tab1 = new PdfPTable(1);

        // sub table 2
        PdfPTable subtab2 = new PdfPTable(1);
        subtab2.setWidthPercentage(100);
        subtab2.addCell(
            printStr("SINGAPORE CONSULATE-GENERAL HONG KONG", 1, 25, true, PdfPCell.NO_BORDER, 1));
        subtab2.addCell(printStr("Tel:2527 2212", 1, 25, true, PdfPCell.NO_BORDER, 1));
        PdfPCell subcel2 = new PdfPCell(subtab2);
        subcel2.setColspan(1);
        subcel2.setHorizontalAlignment(subcel2.ALIGN_LEFT);
        subcel2.setBorder(subcel2.NO_BORDER);
        subcel2.setPaddingBottom(0.0f);
        tab1.addCell(subcel2);

        float[] widths = {80};
        tab1.setWidths(widths);
        PdfPCell cel1 = new PdfPCell(tab1);
        cel1.setColspan(1);
        cel1.setHorizontalAlignment(cel1.ALIGN_LEFT);
        cel1.setBorder(cel1.NO_BORDER);
        cel1.setPaddingBottom(0.0f);
        cel1.setFixedHeight(120f);
        table.addCell(cel1);
        // col headers
        float[] widths4 = {80};
        table.setWidths(widths4);
        Rectangle page = document.getPageSize();
        table.setTotalWidth(page.width() - document.leftMargin() - document.rightMargin());
        table.writeSelectedRows(0, -1, 20, page.height() - 20 + table.getTotalHeight() - 90, cb);

      } catch (Exception e) {
        e.printStackTrace();
      }
    }
    @Override
    public void onEndPage(PdfWriter writer, Document document) {
      try {
        Rectangle page = document.getPageSize();

        getHeaderFooter(document);
        // Add page header
        header.setTotalWidth(page.getWidth() - document.leftMargin() - document.rightMargin());
        header.writeSelectedRows(
            0, -1, document.leftMargin(), page.getHeight() - 10, writer.getDirectContent());

        // Add page footer
        footer.setTotalWidth(page.getWidth() - document.leftMargin() - document.rightMargin());
        footer.writeSelectedRows(
            0, -1, document.leftMargin(), document.bottomMargin() - 5, writer.getDirectContent());

        // Add page border

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

      } catch (JSONException e) {
        Logger.getLogger(ExportProjectReportServlet.class.getName()).log(Level.SEVERE, null, e);
        throw new ExceptionConverter(e);
      }
    }
Exemplo n.º 13
0
  private void taxPie(
      Rectangle rct, double totalValue, double tax, String taxLabel, String netLabel) {
    double taxPercent = (tax / totalValue) * 100;
    double netValuePercent = 100 - taxPercent;

    DefaultPieDataset dataset = new DefaultPieDataset();
    dataset.setValue(taxLabel, taxPercent);
    dataset.setValue(netLabel, netValuePercent);

    PiePlot3D plot = new PiePlot3D(dataset);
    plot.setLabelGenerator(new StandardPieItemLabelGenerator());
    plot.setInsets(new Insets(0, 5, 5, 5));
    plot.setToolTipGenerator(new CustomToolTipGenerator());
    plot.setLabelGenerator(new CustomLabelGenerator());
    plot.setSectionPaint(0, new Color(pgRed));
    plot.setSectionPaint(1, new Color(pgGreen));
    plot.setForegroundAlpha(.6f);
    plot.setOutlinePaint(Color.white);
    plot.setBackgroundPaint(Color.white);

    JFreeChart chart =
        new JFreeChart("Asset Distribution", JFreeChart.DEFAULT_TITLE_FONT, plot, true);

    chart.setBackgroundPaint(Color.white);
    chart.setAntiAlias(true);

    Rectangle page = rct;

    try {
      Image img =
          Image.getInstance(
              chart.createBufferedImage((int) page.getWidth(), (int) page.getHeight()), null);
      drawDiagram(img, rct, 0, 72);
    } catch (Exception e) {
      System.out.println(e.getMessage());
    }
  }
Exemplo n.º 14
0
 protected Rectangle rotatePageIfNecessary(Rectangle suggestedPageSize) {
   // rotate the page if dimensions are given as portrait, but template prefers landscape
   if (suggestedPageSize.getHeight() > suggestedPageSize.getWidth() && page1.isLandscape()) {
     float temp = suggestedPageSize.getWidth();
     float newWidth = suggestedPageSize.getHeight();
     float newHeight = temp;
     return new Rectangle(suggestedPageSize.getHeight(), suggestedPageSize.getWidth());
   }
   return suggestedPageSize;
 }
Exemplo n.º 15
0
 /**
  * Gets a Rectangle that is altered to fit on the page.
  *
  * @param top the top position
  * @param bottom the bottom position
  * @return a <CODE>Rectangle</CODE>
  */
 public Rectangle rectangle(float top, float bottom) {
   Rectangle tmp = new Rectangle(left(), bottom(), right(), top());
   tmp.cloneNonPositionParameters(this);
   if (top() > top) {
     tmp.setTop(top);
     tmp.setBorder(border - (border & TOP));
   }
   if (bottom() < bottom) {
     tmp.setBottom(bottom);
     tmp.setBorder(border - (border & BOTTOM));
   }
   return tmp;
 }
 private void drawPoint(
     PdfContext context, Rectangle iconRect, Color fillColor, Color strokeColor) {
   float baseWidth = iconRect.getWidth() / 10;
   SymbolInfo symbol = styleInfo.getSymbol();
   if (symbol.getImage() != null) {
     try {
       Image pointImage = Image.getInstance(symbol.getImage().getHref());
       context.drawImage(pointImage, iconRect, iconRect);
     } catch (Exception ex) { // NOSONAR
       log.error("Not able to create image for POINT Symbol", ex);
     }
   } else if (symbol.getRect() != null) {
     context.fillRectangle(iconRect, fillColor);
     context.strokeRectangle(iconRect, strokeColor, baseWidth / 2);
   } else {
     context.fillEllipse(iconRect, fillColor);
     context.strokeEllipse(iconRect, strokeColor, baseWidth / 2);
   }
 }
Exemplo n.º 17
0
  @Override
  public boolean performFinish() {

    // create the document
    Rectangle suggestedPageSize = getITextPageSize(page1.getPageSize());
    Rectangle pageSize = rotatePageIfNecessary(suggestedPageSize); // rotate if we need landscape

    Document document = new Document(pageSize);

    try {

      // Basic setup of the Document, and get instance of the iText Graphics2D
      //   to pass along to uDig's standard "printing" code.
      String outputFile =
          page1.getDestinationDir()
              + System.getProperty("file.separator")
              + //$NON-NLS-1$
              page1.getOutputFile();
      PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(outputFile));
      document.open();
      Graphics2D graphics = null;
      Template template = getTemplate();

      int i = 0;
      int numPages = 1;
      do {

        // sets the active page
        template.setActivePage(i);

        PdfContentByte cb = writer.getDirectContent();

        Page page = makePage(pageSize, document, template);

        graphics = cb.createGraphics(pageSize.getWidth(), pageSize.getHeight());

        // instantiate a PrinterEngine (pass in the Page instance)
        PrintingEngine engine = new PrintingEngine(page);

        // make page format
        PageFormat pageFormat = new PageFormat();
        pageFormat.setOrientation(PageFormat.PORTRAIT);
        java.awt.print.Paper awtPaper = new java.awt.print.Paper();
        awtPaper.setSize(pageSize.getWidth() * 3, pageSize.getHeight() * 3);
        awtPaper.setImageableArea(0, 0, pageSize.getWidth(), pageSize.getHeight());
        pageFormat.setPaper(awtPaper);

        // run PrinterEngine's print function
        engine.print(graphics, pageFormat, 0);

        graphics.dispose();
        document.newPage();
        if (i == 0) {
          numPages = template.getNumPages();
        }
        i++;

      } while (i < numPages);

      // cleanup
      document.close();
      writer.close();
    } catch (DocumentException e) {
      e.printStackTrace();
      return false;
    } catch (IOException e) {
      e.printStackTrace();
      return false;
    } catch (PrinterException e) {
      e.printStackTrace();
    }
    return true;
  }
Exemplo n.º 18
0
  private void savePDF() {
    File f =
        new File(
            logSource.getFile(".")
                + "/"
                + logSource.name()
                + "-"
                + messageName
                + "."
                + varName
                + "."
                + curEntity
                + "-"
                + cmapCombo.getSelectedItem().toString()
                + ".pdf");

    Rectangle pageSize = PageSize.A4.rotate();
    try {
      FileOutputStream out = new FileOutputStream(f);

      Document doc = new Document(pageSize);
      PdfWriter writer = PdfWriter.getInstance(doc, out);
      doc.open();
      PdfContentByte cb = writer.getDirectContent();
      java.awt.Graphics2D g2 = cb.createGraphicsShapes(pageSize.getWidth(), pageSize.getHeight());
      int width = (int) pageSize.getWidth();
      int height = (int) pageSize.getHeight();

      int prevWidth = defaultWidth;
      int prevHeight = defaultHeight;

      defaultWidth = width;
      defaultHeight = height;

      BufferedImage img = bufImage;

      com.lowagie.text.Image pdfImage = com.lowagie.text.Image.getInstance(writer, img, 0.8f);
      pdfImage.setAbsolutePosition(0, 0);
      cb.addImage(pdfImage);

      double maxX = dd.maxX + 5;
      double maxY = dd.maxY + 5;
      double minX = dd.minX - 5;
      double minY = dd.minY - 5;

      // width/height
      double dx = maxX - minX;
      double dy = maxY - minY;

      double ratio1 = (double) defaultWidth / (double) defaultHeight;
      double ratio2 = dx / dy;

      if (ratio2 < ratio1) dx = dy * ratio1;
      else dy = dx / ratio1;

      drawLegend(g2, (ColorMap) cmapCombo.getSelectedItem(), 0);

      doc.close();
      defaultWidth = prevWidth;
      defaultHeight = prevHeight;

      JOptionPane.showMessageDialog(this, "PDF saved to log directory");
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
Exemplo n.º 19
0
  public ActionForward execute(
      ActionMapping mapping,
      ActionForm form,
      HttpServletRequest request,
      HttpServletResponse response)
      throws Exception {
    regService = new RegService();
    nuser = (RegForm) form;
    nuser = regService.authenticate(nuser);
    String uname = nuser.getUserName();
    String pwd = nuser.getFpassword();
    String cpwd = nuser.getCpassword();
    String acc = nuser.getAccno();
    String fn = nuser.getFirstName();
    String ln = nuser.getLastName();
    String sx = nuser.getSex();
    String add = nuser.getAddress();
    String co = nuser.getCountry();
    String zp = nuser.getZip();
    String mb = nuser.getMobile();
    String em = nuser.getEmail();

    RegForm regForm = (RegForm) form;
    Rectangle pageSize = new Rectangle(400, 400);
    pageSize.setBackgroundColor(new java.awt.Color(0xDF, 0xFF, 0xDE));
    Document document = new Document(pageSize);
    PdfWriter.getInstance(
        document, new FileOutputStream("D:/kowthal training/java/31rep/Report.pdf"));
    document.open();
    PdfPTable table = new PdfPTable(2);
    table.addCell("UserName");
    table.addCell(uname);
    table.addCell("Password");
    table.addCell(pwd);
    table.addCell("Confirm Password");
    table.addCell(cpwd);
    table.addCell("First Name");
    table.addCell(fn);
    table.addCell("Last Name");
    table.addCell(ln);
    table.addCell("Sex");
    table.addCell(sx);
    table.addCell("Address");
    table.addCell(add);
    table.addCell("Country");
    table.addCell(co);
    table.addCell("Zip Code");
    table.addCell(zp);
    table.addCell("Mobile");
    table.addCell(mb);
    table.addCell("E-mail id");
    table.addCell(em);
    System.out.println("before fetch");
    document.add(table);
    System.out.println("after fetch");
    document.add(new Paragraph("Created by Kowthal(947)"));
    document.close();

    target = "success";
    return mapping.findForward(target);
  }
Exemplo n.º 20
0
 /**
  * This method tries to fit the <code>Rectangle pageSize</code> to one of the predefined PageSize rectangles.
  * If a match is found the pageWidth and pageHeight will be set according to values determined from files
  * generated by MS Word2000 and OpenOffice 641. If no match is found the method will try to match the rotated
  * Rectangle by calling itself with the parameter rotate set to true.
  *
  * @param pageSize the page size for which to guess the correct format
  * @param rotate Whether we should try to rotate the size befor guessing the format
  * @return <code>True</code> if the format was guessed, <code>false/<code> otherwise
  */
 private boolean guessFormat(Rectangle pageSize, boolean rotate) {
   if (rotate) {
     pageSize = pageSize.rotate();
   }
   if (rectEquals(pageSize, PageSize.A3)) {
     pageWidth = 16837;
     pageHeight = 23811;
     landscape = rotate;
     return true;
   }
   if (rectEquals(pageSize, PageSize.A4)) {
     pageWidth = 11907;
     pageHeight = 16840;
     landscape = rotate;
     return true;
   }
   if (rectEquals(pageSize, PageSize.A5)) {
     pageWidth = 8391;
     pageHeight = 11907;
     landscape = rotate;
     return true;
   }
   if (rectEquals(pageSize, PageSize.A6)) {
     pageWidth = 5959;
     pageHeight = 8420;
     landscape = rotate;
     return true;
   }
   if (rectEquals(pageSize, PageSize.B4)) {
     pageWidth = 14570;
     pageHeight = 20636;
     landscape = rotate;
     return true;
   }
   if (rectEquals(pageSize, PageSize.B5)) {
     pageWidth = 10319;
     pageHeight = 14572;
     landscape = rotate;
     return true;
   }
   if (rectEquals(pageSize, PageSize.HALFLETTER)) {
     pageWidth = 7927;
     pageHeight = 12247;
     landscape = rotate;
     return true;
   }
   if (rectEquals(pageSize, PageSize.LETTER)) {
     pageWidth = 12242;
     pageHeight = 15842;
     landscape = rotate;
     return true;
   }
   if (rectEquals(pageSize, PageSize.LEGAL)) {
     pageWidth = 12252;
     pageHeight = 20163;
     landscape = rotate;
     return true;
   }
   if (!rotate && guessFormat(pageSize, true)) {
     int x = pageWidth;
     pageWidth = pageHeight;
     pageHeight = x;
     return true;
   }
   return false;
 }
Exemplo n.º 21
0
  public void page2() {
    drawBorder(pageIcon, "IDIT");
    drawHeader(userInfo.getClientHeading(), "Intentionally Defective Irrevocable Trust (IDIT)");

    Rectangle rct = new Rectangle(prctTop);

    rct.setTop(rct.getTop() - (12 * _1_4TH));
    rct.setBottom(rct.getBottom() - _1_4TH);
    rct.setLeft(rct.getLeft() - _1_4TH);

    if (useLLC) {
      if (userInfo.isSingle()) {
        if (userInfo.getClientGender().equalsIgnoreCase("M")) {
          drawDiagram("LLC-SIDIT-M.png", rct, CNTR_TB + LEFT);
        } else {
          drawDiagram("LLC-SIDIT-F.png", rct, CNTR_TB + LEFT);
        }
      } else {
        drawDiagram("LLC-SIDIT.png", rct, CNTR_TB + CNTR_LR);
      }

    } else {
      if (userInfo.isSingle()) {
        if (userInfo.getClientGender().equalsIgnoreCase("M")) {
          drawDiagram("SIDIT-M.png", rct, CNTR_TB + LEFT);
        } else {
          drawDiagram("SIDIT-F.png", rct, CNTR_TB + LEFT);
        }
      } else {
        drawDiagram("SIDIT.png", rct, CNTR_TB + CNTR_LR);
      }
    }

    double nRate = sidit.getNoteRate();
    int term = sidit.getNoteTerm();

    String process[];

    if (useLLC) {
      if (userInfo.isSingle()) {
        process =
            new String[] {
              "1.  A Limited Liability Company (LLC) is formed, with a business purpose, with a small Managing Member Interests (MMI) and a larger Member Interests (MI). Assets are transferred to the LLC with your retaining the  MMI/MI shares.",
              "2,3.  MI interests are sold to an Intentionally Defective Irrevocable Trust (IDIT) set up for the benefit of your children, grandchildren, etc. "
                  + "The sale price is discounted (where possible) due to the lack of control, and marketability, of the MI interests you have."
                  + "You obtain notes recievable for the discounted value, paying interest only ("
                  + percent.format(nRate)
                  + "/year), with a balloon payment due at the end of the term ("
                  + Integer.toString(term)
                  + " years).",
              "Note: Prior to selling assets to the IDIT in exchange for interest only notes, that trust should have assets in it that have a value of at least 10 percent of the value of the assets in the trust after the intended sale. In order to meet this requirement, you might consider gifting assets in an appropriate amount to the trust."
            };
      } else {
        process =
            new String[] {
              "1.  A Limited Liability Company (LLC) is formed, with a business purpose, with small Managing Member Interests (MMI) and a larger Member Interests (MI). Assets are transferred to the LLC with each of you recieving one half of the MMI/MI shares.",
              "2,3.  MI interests are sold by each of you to an Intentionally Defective Irrevocable Trust (IDIT) set up for the benefit of your children, grandchildren, etc. "
                  + "The sale price is discounted (where possible) due to the lack of control, and marketability, of the MI interests you each have.  "
                  + "You each obtain notes recievable for the discounted value, paying interest only ("
                  + percent.format(nRate)
                  + "/year), with a balloon payment due at the end of the term ("
                  + Integer.toString(term)
                  + " years).",
              "Note: Prior to selling assets to the IDIT in exchange for interest only notes, that trust should have assets in it that have a value of at least 10 percent of the value of the assets in the trust after the intended sale. In order to meet this requirement, you might consider gifting assets in an appropriate amount to the trust."
            };
      }
    } else {
      if (userInfo.isSingle()) {
        process =
            new String[] {
              "1.  A Family Limited Partnership (FLP) is formed, with a business purpose, with a small General Partnership (GP) interest and a larger Limited Partnership (LP) interest. Assets are transferred to the FLP, with you recieving the GP/LP shares.",
              "2,3.  LP interests are sold by you to an Intentionally Defective Irrevocable Trust (IDIT) set up for the benefit of your children, grandchildren, etc. "
                  + "The sale price is discounted (where possible) due to the lack of control, and marketability of the LP interests you have."
                  + "You obtain notes recievable for the discounted value, paying interest only ("
                  + percent.format(nRate)
                  + "/year), with a balloon payment due at the end of the term ("
                  + Integer.toString(term)
                  + " years).",
              "Note: Prior to selling assets to the IDIT in exchange for interest only notes, that trust should have assets in it that have a value of at least 10 percent of the value of the assets in the trust after the intended sale. In order to meet this requirement, you might consider gifting assets in an appropriate amount to the trust."
            };

      } else {
        process =
            new String[] {
              "1.  A Family Limited Partnership (FLP) is formed, with a business purpose, with a small General Partnership (GP) interest and a larger Limited Partnership (LP) interest. Assets are transferred to the FLP. with each of you recieving one half of the GP/LP shares.",
              "2,3.  LP interests are sold by each of you to an Intentionally Defective Irrevocable Trust (IDIT) set up for the benefit of your children, grandchildren, etc. "
                  + "The sale price is discounted (where possible) due to lack of control, and marketability of the LP interests you each have. "
                  + "You each obtain notes recievable for the discounted value, paying interest only ("
                  + percent.format(nRate)
                  + "/year), with a balloon payment due at the end of the term ("
                  + Integer.toString(term)
                  + " years).",
              "Note: Prior to selling assets to the IDIT in exchange for interest only notes, that trust should have assets in it that have a value of at least 10 percent of the value of the assets in the trust after the intended sale. In order to meet this requirement, you might consider gifting assets in an appropriate amount to the trust."
            };
      }
    }

    rct = new Rectangle(prctLLeft);
    rct.setTop(rct.getTop() - Page._1_4TH);
    drawSection(rct, "The Process", process, 0);

    String benefits[];

    if (useLLC) {
      benefits =
          new String[] {
            "The LLC is often eligible for discounts on the asset value.",
            "The IDIT enables the freezing of a rapidly growing value (appraisal needed).",
            "Future growth of the asset(s) sold is shifted to the younger generation(s) without gift or estate tax.",
            "The Grantor pays all income tax on the taxable income of the IDIT",
            "Grantor retains control over the assets with the Grantor/Seller retaining the right to choose who manages the Manager Interest of the LLC.",
            "Life Insurance can be obtained and premiums paid within the IDIT."
          };
    } else {
      benefits =
          new String[] {
            "The FLP is often eligible for discounts on the asset value (appraisal needed).",
            "The IDIT enables the freezing of a rapidly growing value.",
            "Future growth of the asset(s) sold is shifted to the younger generation(s) without gift or estate tax.",
            "The Grantor pays all income tax on the taxable income of the IDIT",
            "Grantor retains control over the assets with the Grantor/Seller retaining the right to choose who manages the General Partnership interest of the FLP.",
            "Life Insurance can be obtained and premiums paid within the IDIT."
          };
    }

    rct = new Rectangle(prctLRight);
    rct.setTop(rct.getTop() - Page._1_4TH);
    Rectangle r = this.drawSection(rct, "Benefits of using this technique.", benefits, 2);

    String effects[] = {
      "Assets are Irrevocably transferred to the family.",
      "Heirs lose the step-up in basis of the assets.",
      "The value of the note is subject to estate taxes."
    };

    rct.setTop(r.getBottom());
    r = drawSection(rct, "Side effects of this technique", effects, 2);
  }
 protected Rectangle getPaperSize() {
   Rectangle a0 = PageSize.A0;
   Rectangle a0Landscape = new Rectangle(0f, 0f, a0.getHeight(), a0.getWidth());
   return a0Landscape;
 }
Exemplo n.º 23
0
 public void manipulatePdf(String src, String dest, int pow)
     throws IOException, DocumentException {
   PdfReader reader = new PdfReader(src);
   Rectangle pageSize = reader.getPageSize(1);
   Rectangle newSize =
       (pow % 2) == 0
           ? new Rectangle(pageSize.getWidth(), pageSize.getHeight())
           : new Rectangle(pageSize.getHeight(), pageSize.getWidth());
   Rectangle unitSize = new Rectangle(pageSize.getWidth(), pageSize.getHeight());
   for (int i = 0; i < pow; i++) {
     unitSize = new Rectangle(unitSize.getHeight() / 2, unitSize.getWidth());
   }
   int n = (int) Math.pow(2, pow);
   int r = (int) Math.pow(2, pow / 2);
   int c = n / r;
   Document document = new Document(newSize, 0, 0, 0, 0);
   PdfWriter writer =
       PdfWriter.getInstance(document, new FileOutputStream(String.format(dest, n)));
   document.open();
   PdfContentByte cb = writer.getDirectContent();
   PdfImportedPage page;
   Rectangle currentSize;
   float offsetX, offsetY, factor;
   int total = reader.getNumberOfPages();
   for (int i = 0; i < total; ) {
     if (i % n == 0) {
       document.newPage();
     }
     currentSize = reader.getPageSize(++i);
     factor =
         Math.min(
             unitSize.getWidth() / currentSize.getWidth(),
             unitSize.getHeight() / currentSize.getHeight());
     offsetX =
         unitSize.getWidth() * ((i % n) % c)
             + (unitSize.getWidth() - (currentSize.getWidth() * factor)) / 2f;
     offsetY =
         newSize.getHeight()
             - (unitSize.getHeight() * (((i % n) / c) + 1))
             + (unitSize.getHeight() - (currentSize.getHeight() * factor)) / 2f;
     page = writer.getImportedPage(reader, i);
     cb.addTemplate(page, factor, 0, 0, factor, offsetX, offsetY);
   }
   document.close();
 }
Exemplo n.º 24
0
  // Include table
  public void page4() {
    drawBorder(pageIcon, "IDIT");
    drawHeader(userInfo.getClientHeading(), "Intentionally Defective Irrevocable Trust (IDIT)");

    // Summary
    Rectangle rct = new Rectangle(prctTop);
    PageTable table = new PageTable(writer);
    table.setTableFormat(rct, 3);
    table.setTableFont("arial.TTF");
    table.setTableFontBold("arialbd.TTF");
    table.setFontSize(12);
    float widths[] = {.45f, .1f, .45f};
    int alignments[] = {PdfPCell.ALIGN_LEFT, PdfPCell.ALIGN_CENTER, PdfPCell.ALIGN_RIGHT};
    table.setColumnWidths(widths);
    table.setColumnAlignments(alignments);

    String noteStructure = "Annual Level Principal + Interest";

    if (sidit.getNoteType() == 1) noteStructure = "Annual Amoritized";
    if (sidit.getNoteType() == 2) noteStructure = "Annual Interest + Balloon";

    String cells[][] = {
      {"SUMMARY", "", "", "[colspan=3,align=center,bold=1][][]"},
      {"", "", "", "[][][]"},
      {
        "Value of Assets to be Sold (pre discount)",
        "",
        dollar.format(sidit.getFmv() - sidit.getGiftAmount()),
        "[][][]"
      },
      {
        "Discount",
        "",
        percent.format(1.0 - (sidit.getDmv() / (sidit.getFmv() - sidit.getGiftAmount()))),
        "[][][]"
      },
      {"Net Value of Assets Sold", "", dollar.format(sidit.getDmv()), "[][][]"},
      {"Amount of Gift to Trust", "", dollar.format(sidit.getGiftAmount()), "[][][]"},
      {"Total Amount of Trust Assets", "", dollar.format(sidit.getFmv()), "[][][]"},
      {
        "Yield on Trust Assets(Growth/Income)",
        "",
        percent.format(sidit.getAssetGrowth() + sidit.getAssetIncome()),
        "[][][]"
      },
      {"Note Value", "", dollar.format(sidit.getDmv()), "[][][]"},
      {"Note Term", "", number.format(sidit.getNoteTerm()), "[][][]"},
      {"Note Interest Rate per Year", "", percent.format(sidit.getNoteRate()), "[][][]"},
      {"Note Payout Structure", "", noteStructure, "[][][]"},
      {
        "Life Premium (paid for " + Integer.toString(sidit.getNoteTerm()) + " years)",
        "",
        dollar.format(sidit.getLifePremium()),
        "[][][]"
      },
      {"Life Death Benefit", "", dollar.format(sidit.getLifeDeathBenefit()), "[][][]"}
    };

    table.buildTableEx(cells);
    table.drawTable();

    // Build the Cash Flow Table here!!!!
    // Draw cash flow table
    rct = new Rectangle(prctBottom);
    rct.setTop(rct.getTop() + (1.f * 72));
    float widths2[] = {.1f, .2f, .2f, .2f, .2f, .1f, .2f, .2f};
    int alignments2[] = {
      PdfPCell.ALIGN_CENTER,
      PdfPCell.ALIGN_RIGHT,
      PdfPCell.ALIGN_RIGHT,
      PdfPCell.ALIGN_RIGHT,
      PdfPCell.ALIGN_RIGHT,
      PdfPCell.ALIGN_RIGHT,
      PdfPCell.ALIGN_RIGHT,
      PdfCell.ALIGN_RIGHT
    };

    PageTable cashFlow = new PageTable(writer);
    cashFlow.setTableFormat(rct, 8);
    cashFlow.setTableFont("arial.TTF");
    cashFlow.setTableFontBold("arialbd.TTF");
    cashFlow.setFontSize(8);

    cashFlow.setColumnWidths(widths2);
    cashFlow.setColumnAlignments(alignments2);

    String heading[][] = {
      {
        "Trust Cash Flow",
        "",
        "",
        "",
        "",
        "",
        "",
        "",
        "[bold=1,colspan=8,align=center,ptsize=12][][][][][][][]"
      },
      {" ", "", "", "", "", "", "", "", "[][][][][][][][]"},
      {
        "Year",
        "Beg. Principal",
        "Growth",
        "Income",
        "Payout",
        "Premium Payment",
        "End Principal",
        "Amt. to Family *",
        "[bold=1,border=l+t+b+r,align=center][bold=1,border=l+t+b+r,align=center]"
            + "[bold=1,border=l+t+b+r,align=center][bold=1,border=l+t+b+r,align=center]"
            + "[bold=1,border=l+t+b+r,align=center][bold=1,border=l+t+b+r,align=center]"
            + "[bold=1,border=l+t+b+r,align=center][bold=1,border=l+t+b+r,align=center]"
      }
    };

    String rows[][] = getCashFlow();
    String singleRow[][] = new String[1][7];

    String cont[][] = {
      {
        "[Continued on Next Page]",
        "",
        "",
        "",
        "",
        "",
        "",
        "[bold=1,colspan=7,align=center][][][][][][][]"
      },
      {" ", "", "", "", "", "", "", "[][][][][][][][]"}
    };

    int idx = 0;

    if (sidit.getNoteTerm() > 17) {
      cashFlow.buildTableEx(heading);
      while (idx < 12) {
        singleRow[0] = rows[idx++];
        cashFlow.buildTableEx(singleRow);
      }
      cashFlow.buildTableEx(cont);
      cashFlow.drawTable();

      // Draw the following label at the bottom
      String lb1 =
          "* Includes life insurance should death occur at any year minus the value of the note.";

      drawLabel(lb1, prctBottom, "GARA.TTF", new Color(64, 64, 64), 9, LBL_LEFT, LBL_BOTTOM);

      newPage(); // We need to go to a new page

      // Redraw heading
      drawBorder(pageIcon, "IDIT");
      drawHeader(userInfo.getClientHeading(), "Intentionaly Defective Irrevocable Trust");

      // Readraw Table Heading
      rct = new Rectangle(prctTop);
      cashFlow = new PageTable(writer);
      cashFlow.setTableFormat(rct, 8);
      cashFlow.setTableFont("arial.TTF");
      cashFlow.setTableFontBold("arialbd.TTF");
      cashFlow.setFontSize(8);
      cashFlow.setColumnWidths(widths2);
      cashFlow.setColumnAlignments(alignments2);

      heading[0][0] = "Trust Cash Flow (Cont.)";
      cashFlow.buildTableEx(heading);

      // Include the missing rows
      while (idx < sidit.getNoteTerm()) {
        singleRow[0] = rows[idx++];
        cashFlow.buildTableEx(singleRow);
      }
      cashFlow.drawTable();
      drawLabel(lb1, prctBottom, "GARA.TTF", new Color(64, 64, 64), 9, LBL_LEFT, LBL_BOTTOM);
    } else {
      cashFlow.buildTableEx(heading);
      cashFlow.buildTableEx(getCashFlow());
      cashFlow.drawTable();
      // Draw the following label at the bottom
      String lb1 =
          "* Includes life insurance should death occur at any year minus the value of the note.";
      drawLabel(lb1, prctBottom, "GARA.TTF", new Color(64, 64, 64), 9, LBL_LEFT, LBL_BOTTOM);
    }
  }
Exemplo n.º 25
0
  public void page3() {
    drawBorder(pageIcon, "IDIT");
    drawHeader(userInfo.getClientHeading(), "Intentionally Defective Irrevocable Trust (IDIT)");

    Rectangle rct = new Rectangle(prctTop);

    rct.setTop(rct.getTop() - (12 * _1_4TH));
    rct.setBottom(rct.getBottom() - _1_4TH);
    rct.setLeft(rct.getLeft() - _1_4TH);

    if (useLLC) {
      if (userInfo.isSingle()) {
        if (userInfo.getClientGender().equalsIgnoreCase("M")) {
          drawDiagram("LLC-SIDIT-M.png", rct, CNTR_TB + CNTR_LR);
        } else {
          drawDiagram("LLC-SIDIT-F.png", rct, CNTR_TB + CNTR_LR);
        }
      } else {
        drawDiagram("LLC-SIDIT.png", rct, CNTR_TB + CNTR_LR);
      }

    } else {
      if (userInfo.isSingle()) {
        if (userInfo.getClientGender().equalsIgnoreCase("M")) {
          drawDiagram("SIDIT-M.png", rct, CNTR_TB + CNTR_LR);
        } else {
          drawDiagram("SIDIT-F.png", rct, CNTR_TB + CNTR_LR);
        }
      } else {
        drawDiagram("SIDIT.png", rct, CNTR_LR + CNTR_TB);
      }
    }

    // We now need the values placed on the left hand side of the page!
    // Now do the table.
    Rectangle lrct = new Rectangle(prctLLeft);
    lrct.setTop(lrct.getTop() - (_1_2TH + _1_4TH));

    drawSection(
        lrct,
        "Comparison in " + Integer.toString(sidit.getFinalDeath()) + " Years",
        new String[0],
        0);

    rct = new Rectangle(prctLLeft);
    rct.setTop(rct.getTop() - (_1_2TH + _1_2TH));

    PageTable table = new PageTable(writer);
    table.setTableFormat(rct, 4);
    CellInfoFactory cif = new CellInfoFactory();
    BaseFont baseFont = PageUtils.LoadFont("GARA.TTF");
    BaseFont baseFontBold = PageUtils.LoadFont("GARABD.TTF");

    float ptSize = 10f;
    cif.setDefaultFont(new Font(baseFont, ptSize));
    Color green = new Color(0, 176, 0);
    Color red = new Color(192, 0, 0);
    Font fontBold = new Font(baseFontBold, ptSize, Font.NORMAL);
    Font fontBGreen = new Font(baseFontBold, ptSize, Font.NORMAL, green);
    Font fontBRed = new Font(baseFontBold, ptSize, Font.NORMAL, red);

    double f = sidit.getFinalBalance();
    double t = f * .55;
    double result = f - t;

    double balance = sidit.getBalance()[sidit.getFinalDeath() - 1] + sidit.getLifeDeathBenefit();

    double note = sidit.getNoteBalance()[0];
    double noteTax = note * .55;
    double noteValueToFamily = note - noteTax;

    CellInfo cellData[][] = {
      // Column Headers
      {
        cif.getCellInfo(" "),
        cif.getCellInfo("Keep in the Estate", Element.ALIGN_CENTER, fontBold),
        cif.getCellInfo("IDIT", Element.ALIGN_CENTER, fontBold),
        cif.getCellInfo("Difference", Element.ALIGN_CENTER, fontBold)
      },
      {
        cif.getCellInfo("Estate/Gift Taxable:"),
        cif.getCellInfo(dollar.format(f), Element.ALIGN_CENTER, fontBold),
        cif.getCellInfo(dollar.format(note) + " **", Element.ALIGN_CENTER, fontBold),
        cif.getCellInfo(dollar.format(f - note), Element.ALIGN_CENTER, fontBold)
      },
      {
        cif.getCellInfo("Total Estate/Gift Taxes:"),
        cif.getCellInfo(dollar.format(t), Element.ALIGN_CENTER, fontBRed),
        cif.getCellInfo(dollar.format(noteTax), Element.ALIGN_CENTER, fontBRed),
        cif.getCellInfo(dollar.format(t - noteTax), Element.ALIGN_CENTER, fontBRed),
      },
      {
        cif.getCellInfo("Life Insurance:"),
        cif.getCellInfo("0", Element.ALIGN_CENTER, fontBGreen),
        cif.getCellInfo(
            dollar.format(sidit.getLifeDeathBenefit()), Element.ALIGN_CENTER, fontBGreen),
        cif.getCellInfo(
            dollar.format(sidit.getLifeDeathBenefit()), Element.ALIGN_CENTER, fontBGreen),
      },
      {
        cif.getCellInfo("Total to Family"),
        cif.getCellInfo(dollar.format(result), Element.ALIGN_CENTER, fontBGreen),
        cif.getCellInfo(
            dollar.format(balance + noteValueToFamily), Element.ALIGN_CENTER, fontBGreen),
        cif.getCellInfo(
            dollar.format((balance + noteValueToFamily) - result),
            Element.ALIGN_CENTER,
            fontBGreen),
      },
    };

    // Do the chart

    DefaultCategoryDataset dataSet = new DefaultCategoryDataset();
    String series1 = "Keep in Estate";
    String series2 = "IDIT";

    String cat1 = "Estate Taxes";
    String cat2 = "Total to Family";

    dataSet.addValue(t, series1, cat1);
    dataSet.addValue(noteTax, series2, cat1);

    dataSet.addValue(result, series1, cat2);
    dataSet.addValue(balance + noteValueToFamily, series2, cat2);

    BarChart barChart = new BarChart();

    barChart.setTitle("IDIT Comparison");
    barChart.setDataSet(dataSet);
    Rectangle barRect = new Rectangle(prctLRight);
    barRect.setRight(barRect.getRight() + _1_2TH);
    barChart.setRect(barRect);
    barChart.generateBarChart();
    barChart.setSeriesColor(new Color(0xff0000), new Color(0x00ff00));
    barChart.setColor(0, Color.red);
    barChart.setColor(1, Color.green);
    barChart.setLablesOff(true);
    Image img = barChart.getBarChartImage();
    drawDiagram(img, barRect, 0, 72);
    table.setTableData(cellData);
    table.drawTable();

    drawLabel(
        "** The value(s) of the note is kept inside the taxable estate.",
        prctBottom,
        "GARA.TTF",
        new Color(64, 64, 64),
        9,
        LBL_LEFT,
        LBL_BOTTOM);
  }
Exemplo n.º 26
0
  /**
   * Creates a page based on the template selected in the wizard **Note: this function may swap the
   * width and height if the template prefers different page orientation.
   *
   * @return a page
   */
  protected Page makePage(Rectangle pageSize, Document doc, Template template) {

    Map mapOnlyRasterLayers = null;
    Map mapNoRasterLayers = null;

    // **Note: the iText API doesn't render rasters at a high enough resolution if
    // they are written to the PDF via graphics2d.  To work around this problem, I
    // create two copies of the map: one with only the raster layers, and one with
    // everything else.
    // The "everything else" map gets drawn by a graphics2d.  The other layer must be
    // rasterized and inserted into the PDF via iText's API.

    // make one copy of the map with no raster layers
    mapNoRasterLayers = (Map) ApplicationGIS.copyMap(map);
    List<Layer> layersNoRasters = mapNoRasterLayers.getLayersInternal();
    List<Layer> toRemove = new ArrayList<Layer>();
    for (Layer layer : layersNoRasters) {
      for (IGeoResource resource : layer.getGeoResources()) {
        if (resource.canResolve(GridCoverageReader.class)) {
          toRemove.add(layer);
        }
      }
    }
    layersNoRasters.removeAll(toRemove);

    // adjust scale
    double currentViewportScaleDenom = map.getViewportModel().getScaleDenominator();
    if (currentViewportScaleDenom == -1)
      throw new IllegalStateException(
          "no scale denominator is available from the viewport model"); //$NON-NLS-1$

    if (page1.getScaleOption() == PrintWizardPage1.CUSTOM_MAP_SCALE) {
      float customScale = page1.getCustomScale();
      template.setMapScaleHint(customScale);
    } else if (page1.getScaleOption() == PrintWizardPage1.CURRENT_MAP_SCALE) {
      template.setMapScaleHint(currentViewportScaleDenom);
    } else if (page1.getScaleOption() == PrintWizardPage1.ZOOM_TO_SELECTION) {
      template.setZoomToSelectionHint(true);
      template.setMapScaleHint(currentViewportScaleDenom);
    }

    // 3. make the page itself
    Page page = ModelFactory.eINSTANCE.createPage();
    page.setSize(new Dimension((int) pageSize.getWidth(), (int) pageSize.getHeight()));

    // page name stuff not required, because this page will just get discarded
    MessageFormat formatter =
        new MessageFormat(Messages.CreatePageAction_newPageName, Locale.getDefault());
    if (page.getName() == null || page.getName().length() == 0) {
      page.setName(formatter.format(new Object[] {mapNoRasterLayers.getName()}));
    }

    template.init(page, mapNoRasterLayers);

    if (page1.getRasterEnabled()) {
      // make another copy with only raster layers
      mapOnlyRasterLayers = (Map) ApplicationGIS.copyMap(map);
      List<Layer> layersOnlyRasters = mapOnlyRasterLayers.getLayersInternal();
      List<Layer> toRemove2 = new ArrayList<Layer>();
      for (Layer layer : layersOnlyRasters) {
        for (IGeoResource resource : layer.getGeoResources()) {
          if (!resource.canResolve(GridCoverageReader.class)) {
            toRemove2.add(layer);
          }
        }
      }
      layersOnlyRasters.removeAll(toRemove2);

      // set bounds to match the other map
      SetViewportBBoxCommand cmdBbox =
          new SetViewportBBoxCommand(mapNoRasterLayers.getViewportModel().getBounds());
      mapOnlyRasterLayers.sendCommandSync(cmdBbox);

      if (layersNoRasters.size() > 0) {
        writeRasterLayersOnlyToDocument(
            mapOnlyRasterLayers,
            template.getMapBounds(),
            doc,
            page.getSize(), /*currentViewportScaleDenom*/
            mapNoRasterLayers.getViewportModel().getScaleDenominator());
      }
    }

    // copy the boxes from the template into the page
    Iterator<Box> iter = template.iterator();
    while (iter.hasNext()) {
      page.getBoxes().add(iter.next());
    }
    return page;

    // TODO Throw some sort of exception if the page can't be created

  }
Exemplo n.º 27
0
 /**
  * This method compares to Rectangles. They are considered equal if width and height are the same
  *
  * @param rect1 The first Rectangle to compare
  * @param rect2 The second Rectangle to compare
  * @return <code>True</code> if the Rectangles equal, <code>false</code> otherwise
  */
 private boolean rectEquals(Rectangle rect1, Rectangle rect2) {
   return (rect1.getWidth() == rect2.getWidth()) && (rect1.getHeight() == rect2.getHeight());
 }
Exemplo n.º 28
0
  @Override
  public void onEndPage(final PdfWriter writer, final Document document) {
    try {
      /* Adicionado o header */
      final Rectangle page = document.getPageSize();
      final PdfPTable header = new PdfPTable(1);
      header.setTotalWidth(page.getWidth() - document.leftMargin() - document.rightMargin());
      header.setLockedWidth(true);
      header.getDefaultCell().setFixedHeight(55);
      header.getDefaultCell().setHorizontalAlignment(Element.ALIGN_LEFT);

      final PdfPCell cellC = new PdfPCell();
      cellC.setBorder(1);

      final PdfPTable tableContent = new PdfPTable(3);

      /* Adicionando a LogoMarca */
      URL url = null;
      String caminho = "";
      String urlInicial = "";
      Image image = null;
      caminho =
          ParametroUtil.getValorParametroCitSmartHashMap(
              Enumerados.ParametroSistema.URL_LOGO_PADRAO_RELATORIO, "");

      if ("".equals(caminho.trim()) || !UtilImagem.verificaSeImagemExiste(caminho)) {
        urlInicial =
            ParametroUtil.getValorParametroCitSmartHashMap(
                Enumerados.ParametroSistema.URL_Sistema, "");
        caminho = urlInicial + "/imagens/logo/logo.png";
      }

      try {
        url = new URL(caminho);
        final URLConnection conn = url.openConnection();
        conn.connect();
      } catch (final MalformedURLException e) {
        // the URL is not in a valid form
        e.printStackTrace();
        url = null;
      } catch (final IOException e) {
        e.printStackTrace();
        url = null;
      }

      if (url == null) {
        if (Constantes.getValue("CAMINHO_LOGO_CITGERENCIAL") != null) {
          try {
            url = new URL(Constantes.getValue("CAMINHO_LOGO_CITGERENCIAL"));
          } catch (final Exception e) {
            e.printStackTrace();
          }
        }
      }

      if (url == null) {
        caminho =
            Constantes.getValue("SERVER_ADDRESS")
                + Constantes.getValue("CONTEXTO_APLICACAO")
                + "/imagens/logoPadraoRelatorio.png";
        try {
          url = new URL(caminho);
        } catch (final Exception e) {
          e.printStackTrace();
        }
      }

      if (url != null) {
        try {
          image = Image.getInstance(url);
        } catch (final BadElementException e) {
          e.printStackTrace();
        }
      }

      if (image != null) {
        image.scaleAbsolute(150, 50);
        image.setAlignment(Image.RIGHT);
        final Chunk ck = new Chunk(image, -3, -25);
        final PdfPCell cell = new PdfPCell();
        cell.addElement(ck);
        cell.setBorderWidth(0);
        cell.setRowspan(2);
        tableContent.addCell(cell);
      } else {
        tableContent.addCell("Citsmart");
      }

      final String strCab = Constantes.getValue("TEXTO_1a_LINHA_CABECALHO_CITGERENCIAL");
      if (strCab != null && !strCab.equalsIgnoreCase("")) {
        final PdfPCell cAux =
            new PdfPCell(
                new Phrase(strCab, new Font(Font.HELVETICA, 12, Font.BOLD, new Color(0, 0, 0))));
        cAux.setColspan(2);
        cAux.setBorderWidth(1);
        cAux.setHorizontalAlignment(PdfPCell.ALIGN_CENTER);
        tableContent.addCell(cAux);
      }

      /* Adicionado o Titulo do relatório */
      final PdfPCell titulo =
          new PdfPCell(
              new Phrase(titleReport, new Font(Font.HELVETICA, 14, Font.BOLD, new Color(0, 0, 0))));
      titulo.setColspan(2);
      titulo.setRowspan(1);
      titulo.setBorderWidth(0);
      titulo.setHorizontalAlignment(PdfPCell.ALIGN_CENTER);
      tableContent.addCell(titulo);

      /* Adicionado o filtro */
      String strFiltro =
          this.trataParameters(hshParameters, colParmsUtilizadosNoSQL, colDefinicaoParametros);
      if (strFiltro == null) {
        strFiltro = "";
      }
      final PdfPCell cFiltro =
          new PdfPCell(
              new Phrase(strFiltro, new Font(Font.HELVETICA, 8, Font.NORMAL, new Color(0, 0, 0))));
      cFiltro.setBorderWidth(0);
      cFiltro.setHorizontalAlignment(PdfPCell.ALIGN_CENTER);
      cFiltro.setColspan(2);
      tableContent.addCell(cFiltro);
      cellC.addElement(tableContent);
      header.addCell(tableContent);

      // Fim - Trata parametros
      if (!existeAgrupador) {
        if (listRetorno != null && listRetorno.size() > 0) {
          final Object[] row = (Object[]) listRetorno.get(0);
          this.geraCabecalhoPDF(row.length, gerencialItemDto, header, writer, document, page);
        }
      }

      if (page.getWidth() > 600) {
        if (!existeAgrupador) {
          header.writeSelectedRows(0, -1, 20, 565, writer.getDirectContent());
        } else {
          header.writeSelectedRows(0, -1, 20, 585, writer.getDirectContent());
        }
      } else {
        if (!existeAgrupador) {
          header.writeSelectedRows(
              0,
              -1,
              20,
              page.getHeight() - document.topMargin() + header.getTotalHeight(),
              writer.getDirectContent());
        } else {
          header.writeSelectedRows(0, -1, 20, 805, writer.getDirectContent());
        }
      }

      /* Adicionado o footer */
      final PdfPTable footer = new PdfPTable(2);
      final String emissao = (String) hshParameters.get("citcorpore.comum.emissao");
      final String pagina = (String) hshParameters.get("citcorpore.comum.pagina");

      PdfPCell cAuxPageNumber =
          new PdfPCell(
              new Phrase(
                  emissao
                      + ": "
                      + UtilDatas.convertDateToString(
                          TipoDate.DATE_DEFAULT,
                          UtilDatas.getDataAtual(),
                          WebUtil.getLanguage(request))
                      + " "
                      + UtilDatas.formatHoraFormatadaStr(UtilDatas.getHoraAtual()),
                  new Font(Font.HELVETICA, 8, Font.NORMAL, new Color(0, 0, 0))));
      cAuxPageNumber.setBorder(0);
      footer.addCell(cAuxPageNumber);

      cAuxPageNumber =
          new PdfPCell(
              new Phrase(
                  pagina + ": " + writer.getPageNumber(),
                  new Font(Font.HELVETICA, 8, Font.NORMAL, new Color(0, 0, 0))));
      cAuxPageNumber.setHorizontalAlignment(PdfPCell.ALIGN_RIGHT);
      cAuxPageNumber.setBorder(0);
      footer.addCell(cAuxPageNumber);
      footer.setTotalWidth(page.getWidth() - document.leftMargin() - document.rightMargin());
      footer.writeSelectedRows(
          0, -1, document.leftMargin(), document.bottomMargin(), writer.getDirectContent());
    } catch (final Exception e) {
      throw new ExceptionConverter(e);
    }
  }
Exemplo n.º 29
0
  public void page1() {
    drawBorder(pageIcon, "IDIT");
    drawHeader(userInfo.getClientHeading(), "The Problem");

    String sec1[] = {
      "Your assets of "
          + sidit.getAssetName()
          + " have the potential to grow very dramatically over the next few years. This is great news until we calculate your future estate tax liability",
    };
    String sec2[] = {
      "When an asset is growing very rapidly in one's estate, and the estate tax liability is growing faster than can be reduced by normal gifting techniques, a different approach can be taken.",
      " ",
      "Let's examine a combination of leveraging techniques that can be utilized with this circumstance."
    };

    Rectangle rct = new Rectangle(prctTop);
    Rectangle rctx = this.drawSection(rct, "", sec1, 0, 14, 14);

    rct.setTop(rctx.getBottom());
    rct.setLeft(rct.getLeft() + prctTop.getWidth() * .125f);
    rct.setRight(rct.getRight() - prctTop.getWidth() * .125f);

    // Draw the Table
    PageTable table = this.getTable(rct, 2);
    String rows[][] = {
      {"Today's Fair Market Value", "" + dollar.format(sidit.getFmv()), "[][bold=1]"},
      {"Projected Years of Growth", "" + integer.format(sidit.getFinalDeath()), "[][bold=1]"},
      {"Average Growth Rate", "" + percent.format(sidit.getAssetGrowth()), "[][bold=1]"},
      {"Average Income Rate", "" + percent.format(sidit.getAssetIncome()), "[][bold=1]"},
      {" ", "", "[colspan=1][]"},
      {
        "Total Value (projected) in Taxable Estate",
        "" + dollar.format(sidit.getFinalBalance()),
        "[bold=1][bold=1]"
      },
      {"", "", "[colspan=1][]"},
      {
        "Estate Tax (" + percent.format(.55) + ")",
        "" + dollar.format(sidit.getFinalBalance() * .55),
        "[Bold=1,Color=" + pgRed + "][Bold=1,Color=" + pgRed + "]"
      },
      {"", "", "[colspan=1][]"},
      {
        "Net Value Passing to Family",
        "" + dollar.format((sidit.getFinalBalance() - (sidit.getFinalBalance() * .55))),
        "[Bold=1,Color=" + pgGreen + "][Bold=1,Color=" + pgGreen + "]"
      }
    };

    int alignments[] = {LFT, RGT};
    table.setColumnAlignments(alignments);
    table.setFontSize(14);
    table.buildTableEx(rows);
    table.drawTable();

    // Draw the graph ************

    taxPie(
        prctLLeft,
        sidit.getFinalBalance(),
        sidit.getFinalBalance() * .55,
        "Estate Tax",
        "Net to Family");

    // *****************

    drawSection(prctLRight, "", sec2, 0, 14, 14);
  }
Exemplo n.º 30
0
  /**
   * PdfTemplates can be wrapped in an Image.
   *
   * @param args no arguments needed
   */
  public static void main(String[] args) {

    System.out.println("PdfTemplate wrapped in an Image");

    // step 1: creation of a document-object
    Rectangle rect = new Rectangle(PageSize.A4);
    rect.setBackgroundColor(new Color(238, 221, 88));
    Document document = new Document(rect, 50, 50, 50, 50);
    try {
      // step 2: we create a writer that listens to the document
      PdfWriter writer =
          PdfWriter.getInstance(document, new FileOutputStream("templateImages.pdf"));
      // step 3: we open the document
      document.open();
      // step 4:
      PdfTemplate template = writer.getDirectContent().createTemplate(20, 20);
      BaseFont bf =
          BaseFont.createFont(BaseFont.HELVETICA, BaseFont.WINANSI, BaseFont.NOT_EMBEDDED);
      String text = "Vertical";
      float size = 16;
      float width = bf.getWidthPoint(text, size);
      template.beginText();
      template.setRGBColorFillF(1, 1, 1);
      template.setFontAndSize(bf, size);
      template.setTextMatrix(0, 2);
      template.showText(text);
      template.endText();
      template.setWidth(width);
      template.setHeight(size + 2);
      template.sanityCheck();
      Image img = Image.getInstance(template);
      img.setRotationDegrees(90);
      Chunk ck = new Chunk(img, 0, 0);
      PdfPTable table = new PdfPTable(3);
      table.setWidthPercentage(100);
      table.getDefaultCell().setHorizontalAlignment(Element.ALIGN_CENTER);
      table.getDefaultCell().setVerticalAlignment(Element.ALIGN_MIDDLE);
      PdfPCell cell = new PdfPCell(img);
      cell.setPadding(4);
      cell.setBackgroundColor(new Color(0, 0, 255));
      cell.setHorizontalAlignment(Element.ALIGN_CENTER);
      table.addCell("I see a template on my right");
      table.addCell(cell);
      table.addCell("I see a template on my left");
      table.addCell(cell);
      table.addCell("I see a template everywhere");
      table.addCell(cell);
      table.addCell("I see a template on my right");
      table.addCell(cell);
      table.addCell("I see a template on my left");

      Paragraph p1 = new Paragraph("This is a template ");
      p1.add(ck);
      p1.add(" just here.");
      p1.setLeading(img.getScaledHeight() * 1.1f);
      document.add(p1);
      document.add(table);
      Paragraph p2 = new Paragraph("More templates ");
      p2.setLeading(img.getScaledHeight() * 1.1f);
      p2.setAlignment(Element.ALIGN_JUSTIFIED);
      img.scalePercent(70);
      for (int k = 0; k < 20; ++k) p2.add(ck);
      document.add(p2);
      // step 5: we close the document
      document.close();
    } catch (Exception de) {
      System.err.println(de.getMessage());
    }
  }