Exemplo n.º 1
0
 private void writeGraphDetails() throws IOException, DocumentException {
   if (collector.isStopped()) {
     return;
   }
   final PdfPTable jrobinTable = new PdfPTable(1);
   jrobinTable.setHorizontalAlignment(Element.ALIGN_CENTER);
   jrobinTable.setWidthPercentage(100);
   jrobinTable.getDefaultCell().setBorder(0);
   if (largeGraphs != null) {
     // si les graphiques ont été préinitialisés (en Swing) alors on les utilise
     for (final byte[] imageData : largeGraphs.values()) {
       final Image image = Image.getInstance(imageData);
       jrobinTable.addCell(image);
     }
   } else {
     final Collection<JRobin> counterJRobins = collector.getDisplayedCounterJRobins();
     if (counterJRobins.isEmpty()) {
       return;
     }
     for (final JRobin jrobin : counterJRobins) {
       // la hauteur de l'image est prévue pour qu'il n'y ait pas de graph seul sur une page
       final Image image =
           Image.getInstance(jrobin.graph(range, LARGE_GRAPH_WIDTH, LARGE_GRAPH_HEIGHT));
       jrobinTable.addCell(image);
     }
   }
   newPage();
   addToDocument(jrobinTable);
   newPage();
 }
Exemplo n.º 2
0
  /**
   * This function is used to draw very thin white borders over the outer edge of the raster map.
   * It's necessary because the map edge "bleeds" into the adjacent pixels, and we need to cover
   * that.
   *
   * <p>I think this quirky behaviour is possibly an iText bug
   */
  private void addWhiteMapBorder(Image img, Document doc) {

    try {

      Color color = Color.white;
      int borderWidth = 1;

      BufferedImage bufferedTop =
          new BufferedImage((int) img.getScaledWidth(), borderWidth, BufferedImage.TYPE_INT_RGB);
      Graphics2D g1 = bufferedTop.createGraphics();
      g1.setBackground(color);
      g1.clearRect(0, 0, bufferedTop.getWidth(), bufferedTop.getHeight());
      Image top = Image.getInstance(bufferedImage2ByteArray(bufferedTop));
      top.setAbsolutePosition(
          img.getAbsoluteX(),
          img.getAbsoluteY() + img.getScaledHeight() - bufferedTop.getHeight() / 2);

      BufferedImage bufferedBottom =
          new BufferedImage((int) img.getScaledWidth(), borderWidth, BufferedImage.TYPE_INT_RGB);
      Graphics2D g2 = bufferedBottom.createGraphics();
      g2.setBackground(color);
      g2.clearRect(0, 0, bufferedBottom.getWidth(), bufferedBottom.getHeight());
      Image bottom = Image.getInstance(bufferedImage2ByteArray(bufferedBottom));
      bottom.setAbsolutePosition(
          img.getAbsoluteX(), img.getAbsoluteY() - bufferedTop.getHeight() / 2);

      BufferedImage bufferedLeft =
          new BufferedImage(borderWidth, (int) img.getScaledHeight(), BufferedImage.TYPE_INT_RGB);
      Graphics2D g3 = bufferedLeft.createGraphics();
      g3.setBackground(color);
      g3.clearRect(0, 0, bufferedLeft.getWidth(), bufferedLeft.getHeight());
      Image left = Image.getInstance(bufferedImage2ByteArray(bufferedLeft));
      left.setAbsolutePosition(
          img.getAbsoluteX() - bufferedLeft.getWidth() / 2, img.getAbsoluteY());

      BufferedImage bufferedRight =
          new BufferedImage(borderWidth, (int) img.getScaledHeight(), BufferedImage.TYPE_INT_RGB);
      Graphics2D g4 = bufferedRight.createGraphics();
      g4.setBackground(color);
      g4.clearRect(0, 0, bufferedRight.getWidth(), bufferedRight.getHeight());
      Image right = Image.getInstance(bufferedImage2ByteArray(bufferedRight));
      right.setAbsolutePosition(
          img.getAbsoluteX() + img.getScaledWidth() - bufferedRight.getWidth() / 2,
          img.getAbsoluteY());

      doc.add(top);
      doc.add(bottom);
      doc.add(left);
      doc.add(right);
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
Exemplo n.º 3
0
  /**
   * Generates a PDF file with the text 'Hello World'
   *
   * @param args no arguments needed here
   */
  public static byte[] getDashboardPDFAsByteArray() {

    String localProviderURL = "t3://localhost:7001";
    System.setProperty(Context.INITIAL_CONTEXT_FACTORY, "weblogic.jndi.WLInitialContextFactory");
    System.setProperty(Context.PROVIDER_URL, localProviderURL);

    System.out.println("Generating VINSight DashBoard Reports");

    // step 1: creation of a document-object
    Document document = new Document();

    ByteArrayOutputStream baos = new ByteArrayOutputStream(100000);

    try {
      // step 2
      PdfWriter writer;
      writer = PdfWriter.getInstance(document, baos);
      // step 3
      document.open();
      // step 4: we add a paragraph to the document
      document.add(new Paragraph("VINSight Health Check"));
      document.add(new Paragraph("Report 1"));

      // create the chart1 image
      JFreeChart chart1 = VINSightDashboardReport.createVINSightDashBoardChart1();
      BufferedImage image1 = chart1.createBufferedImage(350, 350);
      image1.flush();

      document.add(com.lowagie.text.Image.getInstance(image1, null));
      document.add(new Paragraph("Report 2"));
      JFreeChart chart2 = VINSightDashboardReport.createVINSightDashBoardChart2();
      BufferedImage image2 = chart2.createBufferedImage(350, 350);
      image2.flush();

      document.add(com.lowagie.text.Image.getInstance(image2, null));

    } catch (DocumentException de) {
      de.printStackTrace();
    } catch (Exception e) {
      e.printStackTrace();
    } finally {
      // step 5
      document.close();
      try {
        baos.close();
      } catch (IOException ioe) {
        /*ignore*/
      }
    }

    return baos.toByteArray();
  }
Exemplo n.º 4
0
 private void writeGraphs(Collection<JRobin> jrobins, Map<String, byte[]> mySmallGraphs)
     throws IOException, DocumentException {
   if (collector.isStopped()) {
     // pas de graphs, ils seraient en erreur sans timer
     // mais un message d'avertissement à la place
     final String message = getString("collect_server_misusage");
     final Paragraph jrobinParagraph = new Paragraph(message, PdfFonts.BOLD.getFont());
     jrobinParagraph.setAlignment(Element.ALIGN_CENTER);
     addToDocument(jrobinParagraph);
     return;
   }
   final Paragraph jrobinParagraph =
       new Paragraph("", FontFactory.getFont(FontFactory.HELVETICA, 9f, Font.NORMAL));
   jrobinParagraph.setAlignment(Element.ALIGN_CENTER);
   jrobinParagraph.add(new Phrase("\n\n\n\n"));
   int i = 0;
   if (mySmallGraphs != null) {
     // si les graphiques ont été préinitialisés (en Swing) alors on les utilise
     for (final byte[] imageData : mySmallGraphs.values()) {
       if (i % 3 == 0 && i != 0) {
         // un retour après httpSessions et avant activeThreads pour l'alignement
         jrobinParagraph.add(new Phrase("\n\n\n\n\n"));
       }
       final Image image = Image.getInstance(imageData);
       image.scalePercent(50);
       jrobinParagraph.add(new Phrase(new Chunk(image, 0, 0)));
       jrobinParagraph.add(new Phrase(" "));
       i++;
     }
   } else {
     if (jrobins.isEmpty()) {
       return;
     }
     for (final JRobin jrobin : jrobins) {
       if (i % 3 == 0 && i != 0) {
         // un retour après httpSessions et avant activeThreads pour l'alignement
         jrobinParagraph.add(new Phrase("\n\n\n\n\n"));
       }
       final Image image =
           Image.getInstance(jrobin.graph(range, SMALL_GRAPH_WIDTH, SMALL_GRAPH_HEIGHT));
       image.scalePercent(50);
       jrobinParagraph.add(new Phrase(new Chunk(image, 0, 0)));
       jrobinParagraph.add(new Phrase(" "));
       i++;
     }
   }
   jrobinParagraph.add(new Phrase("\n"));
   addToDocument(jrobinParagraph);
 }
Exemplo n.º 5
0
    // Evento cuando que se ejecuta al terminar una página
    @Override
    public void onEndPage(PdfWriter writer, Document document) {
      // Creamos una tabla de dos culumnas
      PdfPTable table = new PdfPTable(2);
      table.setHorizontalAlignment(Element.ALIGN_CENTER);

      try {
        // Establecemos las medidas de la tabla
        table.setWidths(new int[] {24, 10});
        table.setTotalWidth(100);
        // Establecemos la altura de la celda
        table.getDefaultCell().setFixedHeight(20);
        // Quitamos el borde
        table.getDefaultCell().setBorder(Rectangle.NO_BORDER);
        // Alineamos el contenido a la derecha
        table.getDefaultCell().setHorizontalAlignment(Element.ALIGN_RIGHT);
        // Escribimos el primer texto
        // en la primera celda
        table.addCell(String.format("Página %d de ", writer.getCurrentPageNumber()));
        // Obtenemos el template total
        // y lo agregamos a la celda
        PdfPCell cell = new PdfPCell(Image.getInstance(total));
        // quitamos el borde
        cell.setBorder(Rectangle.NO_BORDER);
        // lo agregamos a la tabla
        table.addCell(cell);
        table.writeSelectedRows(0, -1, 330, 40, writer.getDirectContent());
      } catch (DocumentException de) {
        throw new ExceptionConverter(de);
      }
    }
Exemplo n.º 6
0
  /**
   * Adds an image to this Cell.
   *
   * @param i the image to add
   * @param left the left border
   * @param right the right border
   * @param extraHeight extra height to add above image
   * @param alignment horizontal alignment (constant from Element class)
   * @return the height of the image
   */
  private float addImage(Image i, float left, float right, float extraHeight, int alignment) {
    Image image = Image.getInstance(i);
    if (image.scaledWidth() > right - left) {
      image.scaleToFit(right - left, Float.MAX_VALUE);
    }
    flushCurrentLine();
    if (line == null) {
      line = new PdfLine(left, right, alignment, leading);
    }
    PdfLine imageLine = line;

    // left and right in chunk is relative to the start of the line
    right = right - left;
    left = 0f;

    if ((image.alignment() & Image.RIGHT) == Image.RIGHT) {
      left = right - image.scaledWidth();
    } else if ((image.alignment() & Image.MIDDLE) == Image.MIDDLE) {
      left = left + ((right - left - image.scaledWidth()) / 2f);
    }
    Chunk imageChunk = new Chunk(image, left, 0);
    imageLine.add(new PdfChunk(imageChunk, null));
    addLine(imageLine);
    return imageLine.height();
  }
Exemplo n.º 7
0
  private void doActionRemoveWatermark() throws PageException, IOException, DocumentException {
    required("pdf", "removeWatermark", "source", source);

    if (destination != null && destination.exists() && !overwrite)
      throw new ApplicationException("destination file [" + destination + "] already exists");

    railo.runtime.img.Image ri =
        new railo.runtime.img.Image(1, 1, BufferedImage.TYPE_INT_RGB, Color.BLACK);
    Image img = Image.getInstance(ri.getBufferedImage(), null, false);
    img.setAbsolutePosition(1, 1);

    PDFDocument doc = toPDFDocument(source, password, null);
    doc.setPages(pages);
    PdfReader reader = doc.getPdfReader();

    boolean destIsSource =
        destination != null && doc.getResource() != null && destination.equals(doc.getResource());
    java.util.List bookmarks = SimpleBookmark.getBookmark(reader);
    ArrayList master = new ArrayList();
    if (bookmarks != null) master.addAll(bookmarks);

    // output
    OutputStream os = null;
    if (!StringUtil.isEmpty(name) || destIsSource) {
      os = new ByteArrayOutputStream();
    } else if (destination != null) {
      os = destination.getOutputStream();
    }

    try {
      int len = reader.getNumberOfPages();
      PdfStamper stamp = new PdfStamper(reader, os);

      Set _pages = doc.getPages();
      for (int i = 1; i <= len; i++) {
        if (_pages != null && !_pages.contains(Integer.valueOf(i))) continue;
        PdfContentByte cb = foreground ? stamp.getOverContent(i) : stamp.getUnderContent(i);
        PdfGState gs1 = new PdfGState();
        gs1.setFillOpacity(0);
        cb.setGState(gs1);
        cb.addImage(img);
      }
      if (bookmarks != null) stamp.setOutlines(master);
      stamp.close();
    } finally {
      IOUtil.closeEL(os);
      if (os instanceof ByteArrayOutputStream) {
        if (destination != null)
          IOUtil.copy(
              new ByteArrayInputStream(((ByteArrayOutputStream) os).toByteArray()),
              destination,
              true); // MUST overwrite
        if (!StringUtil.isEmpty(name)) {
          pageContext.setVariable(
              name, new PDFDocument(((ByteArrayOutputStream) os).toByteArray(), password));
        }
      }
    }
  }
  private void generateHeaderTable(User c, PdfPTable headerTable) throws Exception {
    // Generic User Image
    // PdfPTable headerTable = new PdfPTable(3);
    Image userImage = Image.getInstance(c.getImageUrl(), null);
    userImage.setAlignment(Element.ALIGN_RIGHT);
    userImage.scalePercent(40);

    PdfPCell userImageCell = new PdfPCell(userImage, false);
    userImageCell.setBorder(0);
    headerTable.addCell(userImageCell);

    // Generic logo
    Image logoImage = Image.getInstance(c.getLogoUrl());
    logoImage.setAlignment(Element.ALIGN_RIGHT);
    logoImage.scalePercent(30);

    PdfPCell logoImageCell = new PdfPCell(logoImage, false);
    logoImageCell.setBorder(0);
    headerTable.addCell(logoImageCell);

    // Generic Stamp Image
    Image stampImage = Image.getInstance(c.getStampUrl());
    stampImage.setAlignment(Element.ALIGN_RIGHT);
    stampImage.scalePercent(30);
    PdfPCell stampImageCell = new PdfPCell(stampImage, false);
    stampImageCell.setBorder(0);
    headerTable.addCell(stampImageCell);
    // cell = PDFCellStyles.borderlessCell("Expense Form");
    // headerTable.addCell(cell);
    if (c.getName() != null && c.getName() != "") {
      headerTable.addCell(PDFCellStyles.borderlessCell(""));
      headerTable.addCell(PDFCellStyles.borderlessCell("User Name"));
      headerTable.addCell(PDFCellStyles.borderlessCell(c.getName()));
    }
    if (c.getAddress() != null && c.getAddress() != "") {
      headerTable.addCell(PDFCellStyles.borderlessCell(""));
      headerTable.addCell(PDFCellStyles.borderlessCell("Company"));
      headerTable.addCell(PDFCellStyles.borderlessCell(c.getAddress()));
    }
    if (c.getPhone() != null && c.getPhone() != "") {
      headerTable.addCell(PDFCellStyles.borderlessCell(""));
      headerTable.addCell(PDFCellStyles.borderlessCell("Phone Number"));
      headerTable.addCell(PDFCellStyles.borderlessCell(c.getPhone()));
    }
    // return headerTable;
  }
Exemplo n.º 9
0
  /**
   * double scaleDenom = page1.isCustomScale() ? page1.getCustomScale() :
   * map.getViewportModel().getScaleDenominator();
   *
   * @param mapWithRasterLayersOnly a map with only raster layers
   * @param mapBoundsInTemplate a rectangle indicating the coordinates of the top left, width and
   *     height (where the coordinate system has (0,0) in the top left.
   * @param doc the PDF document object
   */
  private void writeRasterLayersOnlyToDocument(
      Map mapWithRasterLayersOnly,
      org.eclipse.swt.graphics.Rectangle mapBoundsInTemplate,
      Document doc,
      Dimension pageSize,
      double currentViewportScaleDenom) {

    // set dimensions of the raster image to be the same ratio as
    // the required map bounds within the page, but scaled up so
    // we can achieve a higher DPI when we later insert the image
    // into the page (90 refers to the default DPI)
    int w = mapBoundsInTemplate.width * page1.getDpi() / 90;
    int h = mapBoundsInTemplate.height * page1.getDpi() / 90;

    BufferedImage imageOfRastersOnly = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
    Graphics2D g = imageOfRastersOnly.createGraphics();

    // define a DrawMapParameter object with a custom BoundsStrategy if a custom scale is set
    DrawMapParameter drawMapParameter = null;

    double scaleDenom =
        (page1.getScaleOption() == ExportPDFWizardPage1.CUSTOM_MAP_SCALE)
            ? page1.getCustomScale()
            : currentViewportScaleDenom;

    drawMapParameter =
        new DrawMapParameter(
            g,
            new java.awt.Dimension(w, h),
            mapWithRasterLayersOnly,
            new BoundsStrategy(scaleDenom),
            page1.getDpi(),
            SelectionStyle.EXCLUSIVE_ALL,
            null);

    try {

      // draw the map (at a high resolution as specified above)
      ApplicationGIS.drawMap(drawMapParameter);
      Image img = Image.getInstance(bufferedImage2ByteArray(imageOfRastersOnly));

      // scale the image down to fit into the page
      img.scaleAbsolute(mapBoundsInTemplate.width, mapBoundsInTemplate.height);

      // set the location of the image
      int left = mapBoundsInTemplate.x;
      int bottom = pageSize.height - mapBoundsInTemplate.height - mapBoundsInTemplate.y;
      img.setAbsolutePosition(left, bottom); // (0,0) is bottom left in the PDF coordinate system

      doc.add(img);
      addWhiteMapBorder(img, doc);

    } catch (Exception e) {
      // TODO: fail gracefully.
    }
  }
 public void onOpenDocument(PdfWriter pdfWriter, Document document) {
   try {
     baseFont = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
     headerImage = Image.getInstance(imageFilePath + "MetLifeLog.png");
     if (code39 == null) {
       code39 = new Barcode39();
     }
     code39.setCode(this.contNo);
     code39.setBarHeight(14f);
     // code39.setCodeType(Barcode39.);
     // initialization of the Graphic State
     pdfGState = new PdfGState();
     pdfGState.setFillOpacity(1f);
     pdfGState.setStrokeOpacity(1f);
   } catch (Exception ex) {
     ex.printStackTrace();
   }
 }
Exemplo n.º 11
0
 /*
  * (non-Javadoc)
  *
  * @see com.afunms.report.ExportInterface#insertChart(java.lang.String)
  */
 public void insertChart(String path) throws Exception {
   if (!document.isOpen()) {
     document.open();
   }
   Image png = Image.getInstance(path);
   // png.scaleAbsolute(560, 320);
   png.scalePercent(90);
   Table pngtable = new Table(1);
   pngtable.setAutoFillEmptyCells(true);
   pngtable.setAlignment(Element.ALIGN_CENTER);
   pngtable.setCellsFitPage(true);
   pngtable.setWidth(100);
   pngtable.setBorder(0);
   RtfCell cell = new RtfCell(png);
   cell.setBorder(0);
   pngtable.addCell(cell);
   document.add(pngtable);
 }
  public void preProcessPDF(Object document)
      throws IOException, BadElementException, DocumentException {
    String sep = File.separator;
    Document pdf = (Document) document;
    ExternalContext extContext = FacesContext.getCurrentInstance().getExternalContext();
    Map<String, String> params =
        FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap();

    String logo =
        extContext.getRealPath(
            "resources" + sep + "images" + sep + "LogoEncabezadoLiquidacion2.png");
    String titulo = params.get("titulo");

    pdf.open();
    pdf.setPageSize(PageSize.A4);
    pdf.addTitle(titulo);
    pdf.add(Image.getInstance(logo));
  }
  public void listadoMarcasPDF(Object document)
      throws IOException, BadElementException, DocumentException {

    Font fuenteNegra18 = new Font(Font.TIMES_ROMAN, 18, Font.BOLD, Color.BLACK);

    Paragraph titulo = new Paragraph();
    titulo.add(new Paragraph("Listado de Marcas de vehiculos en el Sistema ", fuenteNegra18));
    agregarLineasEnBlanco(titulo, 2);
    titulo.setAlignment(Element.ALIGN_CENTER);
    String sep = File.separator;
    Document pdf = (Document) document;
    pdf.open();
    pdf.setPageSize(PageSize.A4);
    ExternalContext extContext = FacesContext.getCurrentInstance().getExternalContext();
    String logo = extContext.getRealPath("resources" + sep + "images" + sep + "transacciones.png");
    pdf.addTitle("Usuarios");
    pdf.add(Image.getInstance(logo));
    pdf.add(titulo);
  }
 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.º 15
0
  /**
   * Overrides the method in PdfPageEventHelper from itext to create and set the headerTable with
   * relevant contents and set its logo image if there is a logoImage to be used.
   *
   * @param writer The PdfWriter for this document.
   * @param document The document.
   * @see com.lowagie.text.pdf.PdfPageEventHelper#onOpenDocument(com.lowagie.text.pdf.PdfWriter,
   *     com.lowagie.text.Document)
   */
  @Override
  public void onOpenDocument(PdfWriter writer, Document document) {
    LOG.debug("onOpenDocument() started.");
    try {
      float[] headerWidths = {0.20f, 0.60f, 0.20f};
      headerTable = new PdfPTable(headerWidths);
      headerTable.setWidthPercentage(100);
      headerTable.setHorizontalAlignment(Element.ALIGN_CENTER);

      headerTable.getDefaultCell().setBorderWidth(0);
      headerTable.getDefaultCell().setHorizontalAlignment(Element.ALIGN_CENTER);
      headerTable.getDefaultCell().setVerticalAlignment(Element.ALIGN_CENTER);

      if (StringUtils.isNotBlank(logoImage)) {
        logo = Image.getInstance(logoImage);
        logo.scalePercent(3, 3);
        headerTable.addCell(new Phrase(new Chunk(logo, 0, 0)));
      } else {
        // if we don't use images
        headerTable.addCell(new Phrase(new Chunk("")));
      }
      PdfPCell cell;
      cell =
          new PdfPCell(new Paragraph("REQUEST FOR QUOTATION\nTHIS IS NOT AN ORDER", ver_17_normal));
      cell.setBorderWidth(0);
      cell.setHorizontalAlignment(Element.ALIGN_CENTER);
      headerTable.addCell(cell);

      Paragraph p = new Paragraph();
      p.add(new Chunk("\n     R.Q. Number: ", ver_8_bold));
      p.add(new Chunk(po.getPurapDocumentIdentifier() + "\n", cour_10_normal));
      cell = new PdfPCell(p);
      cell.setBorderWidth(0);
      headerTable.addCell(cell);

      // initialization of the template
      tpl = writer.getDirectContent().createTemplate(100, 100);
      // initialization of the font
      helv = BaseFont.createFont("Helvetica", BaseFont.WINANSI, false);
    } catch (Exception e) {
      throw new ExceptionConverter(e);
    }
  }
Exemplo n.º 16
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 static void addComponyLogo(Document d, HttpServletRequest request)
     throws ConfigurationException, DocumentException {
   PdfPTable table = new PdfPTable(1);
   table.setHorizontalAlignment(Element.ALIGN_LEFT);
   table.setWidthPercentage(50);
   PdfPCell cell = null;
   try {
     imgPath =
         com.krawler.esp.utils.ConfigReader.getinstance().get("platformURL")
             + "b/"
             + companySubDomain
             + "/images/store/?company=true";
     Image img = Image.getInstance(imgPath);
     cell = new PdfPCell(img);
   } catch (Exception e) {
     cell = new PdfPCell(new Paragraph(companyName, fontBig));
   }
   cell.setBorder(0);
   cell.setHorizontalAlignment(Element.ALIGN_LEFT);
   table.addCell(cell);
   d.add(table);
 }
Exemplo n.º 18
0
 /**
  * 生成照片
  *
  * @param stdImage
  * @return
  * @throws IOException
  * @throws MalformedURLException
  * @throws BadElementException
  */
 private Image getImage(String StudentNo)
     throws BadElementException, MalformedURLException, IOException {
   /*
   Graphics2D g2d = null;
   Blob b=stdImage.getImage();
   long size;
   try {
   	size = b.length();
   	byte[] bs = b.getBytes(1, (int)size);
   	return Image.getInstance(bs);
   }catch(Exception e){
   	e.printStackTrace();
   	return null;
   }
   */
   // StdImage stdImage=(StdImage)list.get(0);
   // Blob b=stdImage.getImage();
   /*
   long size;
   try {
   	size = b.length();
   	byte[] bs = b.getBytes(1, (int)size);
   	return Image.getInstance(bs);
   } catch (Exception e) {
   	e.printStackTrace();
   	//URL url = new URL("http://ap.cust.edu.tw/CIS/pages/images/notFound.gif");
   	Image image=Image.getInstance("http://ap.cust.edu.tw/CIS/pages/images/notFound.gif");
   	//response.sendRedirect("/CIS/pages/images/notFound.gif");
   	return image;
   }
   */
   try {
     return Image.getInstance("http://localhost/eis/getStdimage?myStdNo=" + StudentNo);
   } catch (Exception e) {
     return null;
   }
 }
Exemplo n.º 19
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());
    }
  }
  protected void drawReplacedContent(final RenderableReplacedContentBox content) {
    final Graphics2D g2 = getGraphics();
    final Object o = content.getContent().getRawObject();
    if (o instanceof DrawableWrapper) {
      final DrawableWrapper drawableWrapper = (DrawableWrapper) o;
      if (drawDrawable(content, g2, drawableWrapper)) {
        drawImageMap(content);
      }
      return;
    }
    if (o instanceof Image) {
      if (drawImage(content, (Image) o)) {
        drawImageMap(content);
      }
      return;
    }

    if (o instanceof URLImageContainer) {
      final URLImageContainer imageContainer = (URLImageContainer) o;
      if (imageContainer.isLoadable() == false) {
        PdfLogicalPageDrawable.logger.info(
            "URL-image cannot be rendered, as it was declared to be not loadable: "
                + imageContainer.getSourceURLString());
      } else {
        final ResourceKey resource = imageContainer.getResourceKey();
        if (resource == null) {
          PdfLogicalPageDrawable.logger.info(
              "URL-image cannot be rendered, as it did not return a valid URL.");
        } else {
          try {
            final ResourceManager resourceManager = getResourceManager();
            final com.lowagie.text.Image instance;
            final com.lowagie.text.Image maybeImage = imageCache.get(resource);
            if (maybeImage != null) {
              instance = maybeImage;
            } else {
              final ResourceData data = resourceManager.load(resource);
              instance = com.lowagie.text.Image.getInstance(data.getResource(resourceManager));
              imageCache.put(resource, instance);
            }

            final Resource imageWrapped = resourceManager.create(resource, null, Image.class);
            final Image image = (Image) imageWrapped.getResource();

            if (drawImage(content, image, instance)) {
              drawImageMap(content);
            }
            return;
          } catch (InvalidReportStateException re) {
            throw re;
          } catch (Exception e) {
            PdfLogicalPageDrawable.logger.info(
                "URL-image cannot be rendered, as the image was not loadable.", e);
          }
        }
      }
    }

    if (o instanceof LocalImageContainer) {
      final LocalImageContainer imageContainer = (LocalImageContainer) o;
      final Image image = imageContainer.getImage();
      if (drawImage(content, image)) {
        drawImageMap(content);
      }
    } else {
      PdfLogicalPageDrawable.logger.debug("Unable to handle " + o);
    }
  }
Exemplo n.º 21
0
  /**
   * Creates documents with some simple annotations.
   *
   * @param args no arguments needed
   */
  public static void main(String[] args) {

    System.out.println("Simple Annotations");

    // step 1: creation of a document-object
    Document document1 = new Document(PageSize.A4, 10, 10, 10, 10);
    Document document2 = new Document(PageSize.A4, 10, 10, 10, 10);
    try {

      // step 2:
      PdfWriter writer1 =
          PdfWriter.getInstance(document1, new FileOutputStream("SimpleAnnotations1.pdf"));
      PdfWriter writer2 =
          PdfWriter.getInstance(document2, new FileOutputStream("SimpleAnnotations2.pdf"));
      // step 3:
      writer2.setPdfVersion(PdfWriter.VERSION_1_5);
      document1.open();
      document2.open();
      // step 4:
      document1.add(new Paragraph("Each square on this page represents an annotation."));
      // document1
      PdfContentByte cb1 = writer1.getDirectContent();
      Annotation a1 =
          new Annotation(
              "authors",
              "Maybe it's because I wanted to be an author myself that I wrote iText.",
              250f,
              700f,
              350f,
              800f);
      document1.add(a1);
      Annotation a2 =
          new Annotation(250f, 550f, 350f, 650f, new URL("http://www.lowagie.com/iText/"));
      document1.add(a2);
      Annotation a3 = new Annotation(250f, 400f, 350f, 500f, "http://www.lowagie.com/iText");
      document1.add(a3);
      Image image = Image.getInstance("iText.gif");
      image.setAnnotation(a3);
      document1.add(image);
      Annotation a4 = new Annotation(250f, 250f, 350f, 350f, PdfAction.LASTPAGE);
      document1.add(a4);
      // draw rectangles to show where the annotations were added
      cb1.rectangle(250, 700, 100, 100);
      cb1.rectangle(250, 550, 100, 100);
      cb1.rectangle(250, 400, 100, 100);
      cb1.rectangle(250, 250, 100, 100);
      cb1.stroke();
      // more content
      document1.newPage();
      for (int i = 0; i < 5; i++) {
        document1.add(new Paragraph("blahblahblah"));
      }
      document1.add(
          new Annotation("blahblah", "Adding an annotation without specifying coordinates"));
      for (int i = 0; i < 3; i++) {
        document1.add(new Paragraph("blahblahblah"));
      }
      document1.newPage();
      document1.add(new Chunk("marked chunk").setLocalDestination("mark"));

      // document2
      document2.add(new Paragraph("Each square on this page represents an annotation."));
      PdfContentByte cb2 = writer2.getDirectContent();
      Annotation a5 = new Annotation(100f, 700f, 200f, 800f, "cards.mpg", "video/mpeg", true);
      document2.add(a5);
      Annotation a6 = new Annotation(100f, 550f, 200f, 650f, "SimpleAnnotations1.pdf", "mark");
      document2.add(a6);
      Annotation a7 = new Annotation(100f, 400f, 200f, 500f, "SimpleAnnotations1.pdf", 2);
      document2.add(a7);
      Annotation a8 =
          new Annotation(100f, 250f, 200f, 350f, "C://windows/notepad.exe", null, null, null);
      document2.add(a8);
      // draw rectangles to show where the annotations were added
      cb2.rectangle(100, 700, 100, 100);
      cb2.rectangle(100, 550, 100, 100);
      cb2.rectangle(100, 400, 100, 100);
      cb2.rectangle(100, 250, 100, 100);
      cb2.stroke();
    } catch (Exception de) {
      de.printStackTrace();
    }

    // step 5: we close the document
    document1.close();
    document2.close();
  }
Exemplo n.º 22
0
  /**
   * Método que dibuja la cabecera de la página.
   *
   * @param writer Creador de documentos.
   * @param document Documento del informe.
   */
  protected void drawHeader(PdfWriter writer, Document document) {
    try {
      PdfContentByte cb = writer.getDirectContent();
      cb.saveState();

      PdfPTable tableExt = new PdfPTable(1);
      tableExt.setTotalWidth(document.right() - document.left());
      tableExt.setLockedWidth(true);
      tableExt.setHorizontalAlignment(Element.ALIGN_CENTER);
      tableExt.getDefaultCell().setBorder(Rectangle.BOX);
      tableExt.getDefaultCell().setBorderWidth(0.1F);
      tableExt.getDefaultCell().setBorderColor(BORDER_COLOR);
      tableExt.getDefaultCell().setFixedHeight(69);
      tableExt.getDefaultCell().setHorizontalAlignment(Element.ALIGN_CENTER);
      tableExt.getDefaultCell().setVerticalAlignment(Element.ALIGN_MIDDLE);

      PdfPTable tableInt = new PdfPTable(3);
      tableInt.setTotalWidth(new float[] {108, document.right() - document.left() - 222, 108});
      tableInt.setLockedWidth(true);
      tableInt.setHorizontalAlignment(Element.ALIGN_CENTER);
      tableInt.getDefaultCell().setBorder(Rectangle.TOP | Rectangle.BOTTOM);
      tableInt.getDefaultCell().setBorderWidth(1);
      tableInt.getDefaultCell().setBorderColor(Color.BLUE);
      tableInt.getDefaultCell().setFixedHeight(69);
      tableInt.getDefaultCell().setHorizontalAlignment(Element.ALIGN_CENTER);
      tableInt.getDefaultCell().setVerticalAlignment(Element.ALIGN_MIDDLE);

      Image logo = null;
      try {
        logo = Image.getInstance(ORGANIZACION_IMAGE_URL);
      } catch (Exception e) {
        logo = ConfiguracionArchivoManager.getInstance().getBlankImage();
      }
      logo.setBorder(Rectangle.BOX);
      logo.setBorderWidth(0.1F);
      logo.setBorderColor(BORDER_COLOR);
      tableInt.addCell(logo);

      PdfPTable tableInfo = new PdfPTable(1);
      tableInfo.setTotalWidth(300);
      tableInfo.setLockedWidth(true);
      tableInfo.setHorizontalAlignment(Element.ALIGN_CENTER);
      tableInfo.getDefaultCell().setBorder(Rectangle.NO_BORDER);
      tableInfo.getDefaultCell().setBorderWidth(0.5f);
      tableInfo.getDefaultCell().setBorderColor(Color.BLUE);
      tableInfo.getDefaultCell().setHorizontalAlignment(Element.ALIGN_CENTER);
      tableInfo.getDefaultCell().setVerticalAlignment(Element.ALIGN_MIDDLE);

      // tableInfo.addCell(new Phrase(new Chunk(GOBIERNO,
      // CABECERA_H1_FONT)));
      tableInfo.addCell(new Phrase(new Chunk(TITULO, CABECERA_H1_FONT)));

      PdfPCell cell = new PdfPCell(tableInfo.getDefaultCell());
      if (StringUtils.isNotEmpty(SUBTITULO1)) {
        cell.setBorder(Rectangle.TOP | Rectangle.BOTTOM);
        // cell.setPhrase(new Phrase(new Chunk(CONSEJERIA,
        // CABECERA_H2_FONT)));
        cell.setPhrase(new Phrase(new Chunk(SUBTITULO1, CABECERA_H2_FONT)));
        tableInfo.addCell(cell);
      }

      if (StringUtils.isNotEmpty(SUBTITULO2)) {
        cell = new PdfPCell(tableInfo.getDefaultCell());
        cell.setBorder(Rectangle.TOP | Rectangle.BOTTOM);
        // cell.setPhrase(new Phrase(new Chunk(VICECONSEJERIA,
        // CABECERA_H3_FONT)));
        cell.setPhrase(new Phrase(new Chunk(SUBTITULO2, CABECERA_H3_FONT)));
        tableInfo.addCell(cell);
      }

      if (StringUtils.isNotEmpty(SUBTITULO3)) {
        // tableInfo.addCell(new Phrase(new Chunk(DIRECCION,
        // CABECERA_H3_FONT)));
        tableInfo.addCell(new Phrase(new Chunk(SUBTITULO3, CABECERA_H3_FONT)));
      }

      tableInt.addCell(tableInfo);

      // tableInt.addCell(new Phrase(new Chunk(APPLICATION_NAME,
      // APP_NAME_FONT)));
      Image logoArchivo = null;

      try {
        logoArchivo = Image.getInstance(ARCHIVO_IMAGE_URL);
      } catch (Exception e) {
        logoArchivo = ConfiguracionArchivoManager.getInstance().getBlankImage();
      }
      tableInt.addCell(logoArchivo);

      tableExt.addCell(tableInt);
      tableExt.writeSelectedRows(0, -1, document.left(), document.top() + 80, cb);

      cb.restoreState();
    } catch (Exception e) {
      throw new ExceptionConverter(e);
    }
  }
Exemplo n.º 23
0
  /**
   * This method for getting the watermark from the database.
   *
   * @param statusCode is the status of the protocol
   * @return WatermarkBean LOG Exception
   * @see org.kuali.kra.util.watermark.WatermarkDao#getProtocolWatermarkBeanObject(java.lang.String)
   */
  @SuppressWarnings("unchecked")
  public WatermarkBean getProtocolWatermarkBeanObject(String protocolStatusCode) {
    WatermarkBean watermarkBean = new WatermarkBean();
    Watermark watermark = null;
    Map<String, Object> fields = new HashMap<String, Object>();
    fields.put("statusCode", protocolStatusCode);
    if (getPersistableBusinessObject() instanceof Protocol) {
      fields.put("groupName", WatermarkConstants.IRB);
    } else if (getPersistableBusinessObject() instanceof IacucProtocol) {
      fields.put("groupName", WatermarkConstants.IACUC);
    }
    Collection<Watermark> watermarks =
        getBusinessObjectService().findMatching(Watermark.class, fields);
    if (watermarks != null && watermarks.size() > 0) {
      watermark = watermarks.iterator().next();
    }
    if (watermark != null && watermark.isWatermarkStatus()) {
      try {
        String watermarkFontSize =
            watermark.getFontSize() == null
                ? WatermarkConstants.DEFAULT_FONT_SIZE_CHAR
                : watermark.getFontSize();
        String watermarkFontColour =
            watermark.getFontColor() == null
                ? WatermarkConstants.FONT_COLOR
                : watermark.getFontColor();
        watermarkBean.setType(
            watermark.getWatermarkType() == null
                ? WatermarkConstants.WATERMARK_TYPE_TEXT
                : watermark.getWatermarkType());
        watermarkBean.setPosition(
            watermark.getWatermarkPosition() == null
                ? WatermarkConstants.WATERMARK_POSITION_HEADER
                : watermark.getWatermarkPosition());

        String watermarkPositionFontSize =
            watermark.getPositionFontSize() == null
                ? WatermarkConstants.DEFAULT_FONT_SIZE_CHAR
                : watermark.getPositionFontSize();

        watermarkBean.setAlignment(
            watermark.getWatermarkAlignment() == null
                ? WatermarkConstants.ALIGN_CENTER
                : watermark.getWatermarkAlignment());

        watermarkBean.setFont(
            getWatermarkFont(WatermarkConstants.FONT, watermarkFontSize, watermarkFontColour));
        watermarkBean.setPositionFont(
            getWatermarkPositionFont(
                WatermarkConstants.FONT, watermarkPositionFontSize, watermarkFontColour));

        ProtocolNotificationRendererBase renderer =
            getNewProtocolNotificationRendererInstanceHook(
                (ProtocolBase) getPersistableBusinessObject());

        if (watermark.getWatermarkText() != null) {
          watermarkBean.setText(renderer.render(watermark.getWatermarkText()));
        }

        if (watermarkBean.getType().equals(WatermarkConstants.WATERMARK_TYPE_IMAGE)) {
          watermarkBean.setText(watermark.getFileName());
          byte[] imageData = watermark.getAttachmentContent();
          if (imageData != null) {
            Image imageFile = Image.getInstance(imageData);
            watermarkBean.setFileImage(imageFile);
          }
        }

      } catch (Exception e) {
        LOG.error("Exception Occured in (ProtocolPrintWatermarkBase) :", e);
      }
      return watermarkBean;
    }
    return null;
  }
Exemplo n.º 24
0
  /** Demonstrates the use of ColumnText. */
  @Test
  public void main() throws Exception {

    // step 1: creation of a document-object
    Document document = new Document();

    // step 2: creation of the writer
    PdfWriter writer =
        PdfWriter.getInstance(document, PdfTestBase.getOutputStream("columnirregular.pdf"));

    // step 3: we open the document
    document.open();

    // step 4:
    // we grab the contentbyte and do some stuff with it
    PdfContentByte cb = writer.getDirectContent();

    PdfTemplate t = cb.createTemplate(600, 800);
    Image caesar = Image.getInstance(PdfTestBase.RESOURCES_DIR + "caesar_coin.jpg");
    cb.addImage(caesar, 100, 0, 0, 100, 260, 595);
    t.setGrayFill(0.75f);
    t.moveTo(310, 112);
    t.lineTo(280, 60);
    t.lineTo(340, 60);
    t.closePath();
    t.moveTo(310, 790);
    t.lineTo(310, 710);
    t.moveTo(310, 580);
    t.lineTo(310, 122);
    t.stroke();
    cb.addTemplate(t, 0, 0);

    ColumnText ct = new ColumnText(cb);
    ct.addText(
        new Phrase(
            "GALLIA est omnis divisa in partes tres, quarum unam incolunt Belgae, aliam Aquitani, tertiam qui ipsorum lingua Celtae, nostra Galli appellantur.  Hi omnes lingua, institutis, legibus inter se differunt. Gallos ab Aquitanis Garumna flumen, a Belgis Matrona et Sequana dividit. Horum omnium fortissimi sunt Belgae, propterea quod a cultu atque humanitate provinciae longissime absunt, minimeque ad eos mercatores saepe commeant atque ea quae ad effeminandos animos pertinent important, proximique sunt Germanis, qui trans Rhenum incolunt, quibuscum continenter bellum gerunt.  Qua de causa Helvetii quoque reliquos Gallos virtute praecedunt, quod fere cotidianis proeliis cum Germanis contendunt, cum aut suis finibus eos prohibent aut ipsi in eorum finibus bellum gerunt.\n",
            FontFactory.getFont(FontFactory.HELVETICA, 12)));
    ct.addText(
        new Phrase(
            "[Eorum una, pars, quam Gallos obtinere dictum est, initium capit a flumine Rhodano, continetur Garumna flumine, Oceano, finibus Belgarum, attingit etiam ab Sequanis et Helvetiis flumen Rhenum, vergit ad septentriones. Belgae ab extremis Galliae finibus oriuntur, pertinent ad inferiorem partem fluminis Rheni, spectant in septentrionem et orientem solem. Aquitania a Garumna flumine ad Pyrenaeos montes et eam partem Oceani quae est ad Hispaniam pertinet; spectat inter occasum solis et septentriones.]\n",
            FontFactory.getFont(FontFactory.HELVETICA, 12)));
    ct.addText(
        new Phrase(
            "Apud Helvetios longe nobilissimus fuit et ditissimus Orgetorix.  Is M. Messala, [et P.] M.  Pisone consulibus regni cupiditate inductus coniurationem nobilitatis fecit et civitati persuasit ut de finibus suis cum omnibus copiis exirent:  perfacile esse, cum virtute omnibus praestarent, totius Galliae imperio potiri.  Id hoc facilius iis persuasit, quod undique loci natura Helvetii continentur:  una ex parte flumine Rheno latissimo atque altissimo, qui agrum Helvetium a Germanis dividit; altera ex parte monte Iura altissimo, qui est inter Sequanos et Helvetios; tertia lacu Lemanno et flumine Rhodano, qui provinciam nostram ab Helvetiis dividit.  His rebus fiebat ut et minus late vagarentur et minus facile finitimis bellum inferre possent; qua ex parte homines bellandi cupidi magno dolore adficiebantur.  Pro multitudine autem hominum et pro gloria belli atque fortitudinis angustos se fines habere arbitrabantur, qui in longitudinem milia passuum CCXL, in latitudinem CLXXX patebant.\n",
            FontFactory.getFont(FontFactory.HELVETICA, 12)));
    ct.addText(
        new Phrase(
            "His rebus adducti et auctoritate Orgetorigis permoti constituerunt ea quae ad proficiscendum pertinerent comparare, iumentorum et carrorum quam maximum numerum coemere, sementes quam maximas facere, ut in itinere copia frumenti suppeteret, cum proximis civitatibus pacem et amicitiam confirmare.  Ad eas res conficiendas biennium sibi satis esse duxerunt; in tertium annum profectionem lege confirmant.  Ad eas res conficiendas Orgetorix deligitur.  Is sibi legationem ad civitates suscipit.  In eo itinere persuadet Castico, Catamantaloedis filio, Sequano, cuius pater regnum in Sequanis multos annos obtinuerat et a senatu populi Romani amicus appellatus erat, ut regnum in civitate sua occuparet, quod pater ante habuerit; itemque Dumnorigi Haeduo, fratri Diviciaci, qui eo tempore principatum in civitate obtinebat ac maxime plebi acceptus erat, ut idem conaretur persuadet eique filiam suam in matrimonium dat.  Perfacile factu esse illis probat conata perficere, propterea quod ipse suae civitatis imperium obtenturus esset:  non esse dubium quin totius Galliae plurimum Helvetii possent; se suis copiis suoque exercitu illis regna conciliaturum confirmat.  Hac oratione adducti inter se fidem et ius iurandum dant et regno occupato per tres potentissimos ac firmissimos populos totius Galliae sese potiri posse sperant.\n",
            FontFactory.getFont(FontFactory.HELVETICA, 12)));
    ct.addText(
        new Phrase(
            "Ea res est Helvetiis per indicium enuntiata.  Moribus suis Orgetoricem ex vinculis causam dicere coegerunt; damnatum poenam sequi oportebat, ut igni cremaretur.  Die constituta causae dictionis Orgetorix ad iudicium omnem suam familiam, ad hominum milia decem, undique coegit, et omnes clientes obaeratosque suos, quorum magnum numerum habebat, eodem conduxit; per eos ne causam diceret se eripuit.  Cum civitas ob eam rem incitata armis ius suum exequi conaretur multitudinemque hominum ex agris magistratus cogerent, Orgetorix mortuus est; neque abest suspicio, ut Helvetii arbitrantur, quin ipse sibi mortem consciverit.",
            FontFactory.getFont(FontFactory.HELVETICA, 12)));

    float[] left1 = {70, 790, 70, 60};
    float[] right1 = {300, 790, 300, 700, 240, 700, 240, 590, 300, 590, 300, 106, 270, 60};
    float[] left2 = {320, 790, 320, 700, 380, 700, 380, 590, 320, 590, 320, 106, 350, 60};
    float[] right2 = {550, 790, 550, 60};

    int status = 0;
    int column = 0;
    while ((status & ColumnText.NO_MORE_TEXT) == 0) {
      if (column == 0) {
        ct.setColumns(left1, right1);
        column = 1;
      } else {
        ct.setColumns(left2, right2);
        column = 0;
      }
      status = ct.go();
      ct.setYLine(790);
      ct.setAlignment(Element.ALIGN_JUSTIFIED);
      status = ct.go();
      if ((column == 0) && ((status & ColumnText.NO_MORE_COLUMN) != 0)) {
        document.newPage();
        cb.addTemplate(t, 0, 0);
        cb.addImage(caesar, 100, 0, 0, 100, 260, 595);
      }
    }

    // step 5: we close the document
    document.close();
  }
Exemplo n.º 25
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.º 26
0
  public void createPdf() throws ClassNotFoundException, SQLException {
    /*Declaramos documento como un objeto Document
    Asignamos el tamaño de hoja y los margenes */
    Document documento = new Document(PageSize.A4.rotate(), 1, 1, 20, 36);

    // writer es declarado como el método utilizado para escribir en el archivo
    PdfWriter writer = null;

    try {
      // Obtenemos la instancia del archivo a utilizar

      String filename =
          "C:/Program Files/Apache Software Foundation/Tomcat 6.0/webapps/documentos/reporteAutorizacion.pdf";

      File fichero = new File(filename);

      if (fichero.exists()) {
        System.out.println("El fichero  existe222222222");
        fichero.delete();
        System.out.println("El fichero elimino");
      } else {
        System.out.println("el fichero no existe");
      }

      writer = PdfWriter.getInstance(documento, new FileOutputStream(filename));

    } catch (Exception ex) {
      System.out.println("NO creooooo");
      ex.getMessage();
    }

    // Declaramos una instancia de los eventos en HeaderFooter
    HeaderFooter event = new HeaderFooter();
    writer.setPageEvent(event);

    // Agregamos un titulo al archivo
    documento.addTitle("ARCHIVO PDF");

    // Agregamos el autor del archivo
    documento.addAuthor("PROVIAS NACIONAL");

    // Abrimos el documento para edición
    documento.open();
    try {
      // Declaramos un texto como Paragraph
      // Le podemos dar formado como alineación, tamaño y color a la fuente.
      Paragraph title1 = new Paragraph();
      title1.setAlignment(Element.ALIGN_CENTER);

      PdfPTable ta1 = new PdfPTable(2);
      ta1.setHorizontalAlignment(Element.ALIGN_CENTER);
      ta1.getDefaultCell().setHorizontalAlignment(Element.ALIGN_CENTER);
      ta1.getDefaultCell().setVerticalAlignment(Element.ALIGN_MIDDLE);

      PdfPCell cel1 = new PdfPCell();
      com.lowagie.text.Image image =
          com.lowagie.text.Image.getInstance("D:/Provias/images/imgExports.jpg");
      // image.setWidthPercentage(500);
      cel1.addElement(image);
      cel1.setHorizontalAlignment(Element.ALIGN_CENTER);
      cel1.setVerticalAlignment(Element.ALIGN_MIDDLE);
      cel1.setBorder(Rectangle.NO_BORDER);
      ta1.addCell(cel1);
      PdfPCell cel2 = new PdfPCell();

      cel2.addElement(
          new Phrase(
              "Reporte de Autorizaciones Especiales",
              FontFactory.getFont(
                  FontFactory.HELVETICA, 12, Font.BOLD, new CMYKColor(0, 0, 0, 100))));
      cel2.setFixedHeight(90);
      cel2.setHorizontalAlignment(Element.ALIGN_CENTER);
      cel2.setVerticalAlignment(Element.ALIGN_MIDDLE);
      cel2.setBorder(Rectangle.NO_BORDER);
      ta1.addCell(cel2);

      float[] columnWidths1 = new float[] {180f, 100f};
      ta1.setWidths(columnWidths1);
      title1.add(ta1);

      // Agregamos el texto al documento
      documento.add(title1);

      // Agregamos un salto de linea
      documento.add(new Paragraph(" "));

      // Agregamos la tabla al documento haciendo
      // la llamada al método tabla()
      documento.add(tabla());
    } catch (Exception ex) {
      System.out.println("Por!!");
      ex.getMessage();
    }

    documento.close(); // Cerramos el documento
    writer.close(); // Cerramos writer
  }
Exemplo n.º 27
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.º 28
0
  private void doActionAddWatermark() throws PageException, IOException, DocumentException {
    required("pdf", "addWatermark", "source", source);
    if (copyFrom == null && image == null)
      throw new ApplicationException(
          "at least one of the following attributes must be defined " + "[copyFrom,image]");

    if (destination != null && destination.exists() && !overwrite)
      throw new ApplicationException("destination file [" + destination + "] already exists");

    // image
    Image img = null;
    if (image != null) {
      railo.runtime.img.Image ri =
          railo.runtime.img.Image.createImage(pageContext, image, false, false, true);
      img = Image.getInstance(ri.getBufferedImage(), null, false);
    }
    // copy From
    else {
      byte[] barr;
      try {
        Resource res = Caster.toResource(pageContext, copyFrom, true);
        barr = IOUtil.toBytes(res);
      } catch (ExpressionException ee) {
        barr = Caster.toBinary(copyFrom);
      }
      img = Image.getInstance(PDFUtil.toImage(barr, 1).getBufferedImage(), null, false);
    }

    // position
    float x = UNDEFINED, y = UNDEFINED;
    if (!StringUtil.isEmpty(position)) {
      int index = position.indexOf(',');
      if (index == -1)
        throw new ApplicationException(
            "attribute [position] has a invalid value ["
                + position
                + "],"
                + "value should follow one of the following pattern [40,50], [40,] or [,50]");
      String strX = position.substring(0, index).trim();
      String strY = position.substring(index + 1).trim();
      if (!StringUtil.isEmpty(strX)) x = Caster.toIntValue(strX);
      if (!StringUtil.isEmpty(strY)) y = Caster.toIntValue(strY);
    }

    PDFDocument doc = toPDFDocument(source, password, null);
    doc.setPages(pages);
    PdfReader reader = doc.getPdfReader();
    reader.consolidateNamedDestinations();
    boolean destIsSource =
        destination != null && doc.getResource() != null && destination.equals(doc.getResource());
    java.util.List bookmarks = SimpleBookmark.getBookmark(reader);
    ArrayList master = new ArrayList();
    if (bookmarks != null) master.addAll(bookmarks);

    // output
    OutputStream os = null;
    if (!StringUtil.isEmpty(name) || destIsSource) {
      os = new ByteArrayOutputStream();
    } else if (destination != null) {
      os = destination.getOutputStream();
    }

    try {

      int len = reader.getNumberOfPages();
      PdfStamper stamp = new PdfStamper(reader, os);

      if (len > 0) {
        if (x == UNDEFINED || y == UNDEFINED) {
          PdfImportedPage first = stamp.getImportedPage(reader, 1);
          if (y == UNDEFINED) y = (first.getHeight() - img.getHeight()) / 2;
          if (x == UNDEFINED) x = (first.getWidth() - img.getWidth()) / 2;
        }
        img.setAbsolutePosition(x, y);
        // img.setAlignment(Image.ALIGN_JUSTIFIED); ration geht nicht anhand mitte

      }

      // rotation
      if (rotation != 0) {
        img.setRotationDegrees(rotation);
      }

      Set _pages = doc.getPages();
      for (int i = 1; i <= len; i++) {
        if (_pages != null && !_pages.contains(Integer.valueOf(i))) continue;
        PdfContentByte cb = foreground ? stamp.getOverContent(i) : stamp.getUnderContent(i);
        PdfGState gs1 = new PdfGState();
        // print.out("op:"+opacity);
        gs1.setFillOpacity(opacity);
        // gs1.setStrokeOpacity(opacity);
        cb.setGState(gs1);
        cb.addImage(img);
      }
      if (bookmarks != null) stamp.setOutlines(master);
      stamp.close();
    } finally {
      IOUtil.closeEL(os);
      if (os instanceof ByteArrayOutputStream) {
        if (destination != null)
          IOUtil.copy(
              new ByteArrayInputStream(((ByteArrayOutputStream) os).toByteArray()),
              destination,
              true); // MUST overwrite
        if (!StringUtil.isEmpty(name)) {
          pageContext.setVariable(
              name, new PDFDocument(((ByteArrayOutputStream) os).toByteArray(), password));
        }
      }
    }
  }
Exemplo n.º 29
0
  /**
   * Helperfunction to extract an image from an imagereference. If the image is contained as
   * java.awt.Image object only, the image is recoded into an PNG-Image.
   *
   * @param reference the image reference.
   * @return an image.
   * @throws com.lowagie.text.DocumentException if no PDFImageElement could be created using the
   *     given ImageReference.
   * @throws java.io.IOException if the image could not be read.
   */
  public Image getImage(final ImageContainer reference) throws DocumentException, IOException {
    if (reference == null) {
      throw new NullPointerException();
    }

    Object identity = null;
    java.awt.Image image = null;
    if (reference instanceof URLImageContainer) {
      final URLImageContainer urlImageContainer = (URLImageContainer) reference;
      final ResourceKey url = urlImageContainer.getResourceKey();
      if (url != null && urlImageContainer.isLoadable()) {
        identity = url;
        final Image cached = (Image) cachedImages.get(identity);
        if (cached != null) {
          return cached;
        }

        try {
          final ResourceData resourceData = resourceManager.load(url);
          final byte[] data = resourceData.getResource(resourceManager);
          final Image itextimage = Image.getInstance(data);
          cachedImages.put(identity, itextimage);
          return itextimage;
        } catch (ResourceException re) {
          RTFImageCache.logger.info("Caught illegal Image, will recode to PNG instead", re);
        } catch (BadElementException be) {
          RTFImageCache.logger.info("Caught illegal Image, will recode to PNG instead", be);
        } catch (IOException ioe) {
          RTFImageCache.logger.info(
              "Unable to read the raw-data, will try to recode image-data.", ioe);
        }

        try {
          final Resource resource = resourceManager.create(url, null, Image.class);
          image = (java.awt.Image) resource.getResource();
        } catch (ResourceException re) {
          RTFImageCache.logger.info("Caught illegal Image, will try to find local instance", re);
        }
      }
    }

    if (reference instanceof LocalImageContainer && image == null) {
      final LocalImageContainer localImageContainer = (LocalImageContainer) reference;
      image = localImageContainer.getImage();
      if (image != null) {
        // check, if the content was cached ...
        identity = localImageContainer.getIdentity();
        if (identity != null) {
          final Image cachedImage = (Image) cachedImages.get(identity);
          if (cachedImage != null) {
            return cachedImage;
          }
        }
      }
    }
    if (image == null) {
      return null;
    }

    final WaitingImageObserver obs = new WaitingImageObserver(image);
    obs.waitImageLoaded();

    try {
      final byte[] data = RenderUtility.encodeImage(image);
      final Image itextimage = Image.getInstance(data);
      if (identity != null) {
        cachedImages.put(identity, itextimage);
      }
      return itextimage;
    } catch (UnsupportedEncoderException uee) {
      logger.warn("Assertation-Failure: PNG encoding failed.", uee);
      return null;
    }
  }
Exemplo n.º 30
0
  public ByteArrayOutputStream create(Info in, Image toplogo) throws Exception {
    DocHelper dh = new DocHelper();
    Document document = new Document(PageSize.LETTER);
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    PdfWriter writer = PdfWriter.getInstance(document, baos);
    writer.setEncryption(
        PdfWriter.STRENGTH128BITS, "", "3p(0pdf", PdfWriter.AllowCopy | PdfWriter.AllowPrinting);
    // when creating based off this document, cut out from here---------------------

    contract.next();
    float amount = contract.getFloat("amount");
    String job_name = contract.getString("job_name");
    String company = contract.getString("company_name");
    String costCode = contract.getString("division") + " " + contract.getString("cost_code");
    String phaseCode = contract.getString("phase_code");

    float change_order_num = 0;
    int sub_co_number = 0;
    String item_number = "0";
    String co_desc, subject, status;
    float unit_amount = 0, unit_quantity = 0, net_cost = 0;
    float total = 0;
    DecimalFormat df = new DecimalFormat("$###,###,##0.00");
    DecimalFormat codf = new DecimalFormat("0.##");
    SimpleDateFormat sdf = new SimpleDateFormat("MMMM d, yyyy");

    // blank spacer for keeping tables apart
    PdfPTable spacer = new PdfPTable(1);
    /*
    spacer.setBorderWidth(0);
    spacer.setDefaultCellBorderWidth(0);
    spacer.setWidth(100);
    spacer.setPadding(0);
    spacer.setSpacing(0);
    */
    PdfPCell blank =
        new PdfPCell(
            new Phrase("", new Font(Font.TIMES_ROMAN, 1, Font.BOLD, new Color(255, 255, 255))));
    blank.setBorderWidth(0);
    // blank.setLeading(0);
    spacer.addCell(blank);

    // start of document
    Phrase p1 =
        new Phrase(
            "Printed: " + sdf.format(new java.util.Date()),
            new Font(Font.TIMES_ROMAN, 8, Font.ITALIC));
    HeaderFooter footer = new HeaderFooter(p1, false);
    footer.setAlignment(Element.ALIGN_CENTER);
    footer.setBorder(Rectangle.NO_BORDER);
    document.setFooter(footer);
    document.open();

    Image blank1_0 = Image.getInstance(in.path + "/jsp/images/blank1_0.jpg");
    blank1_0.scalePercent(60);
    toplogo.scalePercent(20);

    /*
    Table table1=new Table(1,1);
    table1.setBorderWidth(0);
    table1.setDefaultCellBorder(0);
    table1.setPadding(3);
    */

    PdfPTable table1 = new PdfPTable(2);
    // t.setBorder(0);
    // t.setDefaultPdfPCellBorder(0);
    table1.setWidthPercentage(100);

    PdfPCell cell = new PdfPCell(toplogo);
    dh.top(cell);
    cell.setPaddingBottom(4);
    cell.setBorder(0);
    table1.addCell(cell);

    Phrase name = new Phrase(job_name + "\n", dh.font(16));
    name.add(new Phrase("Subcontract CO Report", dh.font(14)));
    cell = new PdfPCell(name);
    dh.middle(cell);
    dh.center(cell);
    cell.setBorder(0);
    table1.addCell(cell);

    document.add(table1);

    table1 = new PdfPTable(1);
    table1.setWidthPercentage(100);

    p1 = new Phrase(costCode + "-" + phaseCode + ": " + company, dh.font(16, Font.BOLD));
    cell = new PdfPCell(p1);
    cell.setUseDescender(true);
    dh.center(cell);
    dh.middle(cell);
    dh.gray(cell);
    cell.setBorder(0);
    table1.addCell(cell);
    document.add(table1);
    document.add(spacer);

    // header cells
    table1 = new PdfPTable(5);
    int[] widths1 = {5, 5, 57, 15, 15};
    table1.setWidths(widths1);
    table1.setWidthPercentage(100);

    // data cells
    float grand_total = 0;
    while (item.next()) {
      change_order_num = item.getFloat("change_order_num");
      sub_co_number = item.getInt("sub_co_number");
      co_desc = item.getString("description");
      if (co_desc == null) co_desc = "";
      item_number = item.getString("item_number");
      subject = item.getString("subject");
      if (subject == null) subject = "";
      unit_amount = item.getFloat("unit_amount");
      unit_quantity = item.getFloat("unit_quantity");
      status = item.getString("status");
      // bonds_and_insurance = item.getFloat("bonds_and_insurance");
      // item_tax = item.getFloat("item_tax");
      // epco_markup = item.getFloat("epco_markup");

      net_cost = (unit_amount * unit_quantity);
      if (status.equals("Approved")) {
        total += net_cost;
        grand_total += net_cost;
      }

      // first row
      table1.addCell(blank);

      if (change_order_num == -1) co_desc = "Backcharge";
      if (change_order_num == 0) co_desc = "";
      p1 = new Phrase(Integer.toString(sub_co_number), new Font(Font.TIMES_ROMAN, 8, Font.NORMAL));
      cell = new PdfPCell(p1);
      dh.top(cell);
      cell.setBackgroundColor(new Color(225, 225, 225));
      cell.setBorder(0);
      table1.addCell(cell);

      cell = new PdfPCell(new Phrase(co_desc, new Font(Font.TIMES_ROMAN, 8, Font.NORMAL)));
      cell.setColspan(2);
      dh.top(cell);
      cell.setBackgroundColor(new Color(225, 225, 225));
      cell.setBorder(0);
      table1.addCell(cell);

      cell =
          new PdfPCell(
              new Phrase(
                  "CO# " + codf.format(change_order_num) + "-" + item_number,
                  new Font(Font.TIMES_ROMAN, 8, Font.NORMAL)));
      dh.top(cell);
      dh.right(cell);
      cell.setBackgroundColor(new Color(225, 225, 225));
      cell.setBorder(0);
      table1.addCell(cell);

      table1.addCell(blank);
      table1.addCell(blank);

      cell = new PdfPCell(new Phrase(subject, new Font(Font.TIMES_ROMAN, 8, Font.NORMAL)));
      dh.top(cell);
      cell.setBorder(0);
      table1.addCell(cell);

      cell =
          new PdfPCell(new Phrase(df.format(net_cost), new Font(Font.TIMES_ROMAN, 8, Font.NORMAL)));
      dh.right(cell);
      dh.top(cell);
      cell.setBorder(0);
      table1.addCell(cell);

      cell = new PdfPCell(new Phrase(status, new Font(Font.TIMES_ROMAN, 8, Font.NORMAL)));
      dh.right(cell);
      dh.top(cell);
      cell.setBorder(0);
      table1.addCell(cell);
    } // end while
    // Spit out final total row

    document.add(table1);
    document.add(spacer);

    table1 = new PdfPTable(3);
    int[] widths2 = {72, 15, 12};
    table1.setWidths(widths2);
    cell =
        new PdfPCell(
            new Phrase(
                "Total Approved Change Orders:", new Font(Font.TIMES_ROMAN, 10, Font.NORMAL)));
    dh.right(cell);
    dh.middle(cell);
    cell.setBorder(0);
    table1.addCell(cell);

    cell =
        new PdfPCell(
            new Phrase(df.format(grand_total), new Font(Font.TIMES_ROMAN, 10, Font.NORMAL)));
    dh.right(cell);
    dh.middle(cell);
    cell.setBorder(0);
    table1.addCell(cell);

    table1.addCell(blank);

    cell =
        new PdfPCell(
            new Phrase("Original Contract Amount:", new Font(Font.TIMES_ROMAN, 10, Font.NORMAL)));
    dh.right(cell);
    dh.middle(cell);
    cell.setBorder(0);
    table1.addCell(cell);

    cell = new PdfPCell(new Phrase(df.format(amount), new Font(Font.TIMES_ROMAN, 10, Font.NORMAL)));
    dh.right(cell);
    dh.middle(cell);
    cell.setBorder(0);
    table1.addCell(cell);

    table1.addCell(blank);

    cell =
        new PdfPCell(
            new Phrase("Current Approved Total:", new Font(Font.TIMES_ROMAN, 10, Font.NORMAL)));
    dh.right(cell);
    dh.middle(cell);
    cell.setBorder(0);
    table1.addCell(cell);

    grand_total += amount;
    cell =
        new PdfPCell(new Phrase(df.format(grand_total), new Font(Font.TIMES_ROMAN, 10, Font.BOLD)));
    dh.right(cell);
    dh.middle(cell);
    cell.setBorder(0);
    table1.addCell(cell);
    table1.addCell(blank);
    document.add(table1);

    if (contract != null) contract.getStatement().close();
    contract = null;
    if (item != null) item.getStatement().close();
    item = null;
    // -----------------------to here--------------------

    document.close();
    return baos;
  }