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();
 }
Example #2
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));
        }
      }
    }
  }
Example #3
0
 /**
  * Returns the height needed to draw the remaining text.
  *
  * @return a height
  */
 public float remainingHeight() {
   float result = 0f;
   for (Iterator i = images.iterator(); i.hasNext(); ) {
     Image image = (Image) i.next();
     result += image.scaledHeight();
   }
   return remainingLines() * leading + 2 * cellpadding + cellspacing + result + leading / 2.5f;
 }
  /**
   * 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.
    }
  }
Example #5
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();
  }
 /**
  * Reads a PNG from an url.
  *
  * @param url the url
  * @throws IOException on error
  * @return the image
  */
 public static Image getImage(URL url) throws IOException {
   InputStream is = null;
   try {
     is = url.openStream();
     Image img = getImage(is);
     img.setUrl(url);
     return img;
   } finally {
     if (is != null) {
       is.close();
     }
   }
 }
Example #7
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();
  }
Example #8
0
  /**
   * Gets the lines of a cell that can be drawn between certain limits.
   *
   * <p>Remark: all the lines that can be drawn are removed from the object!
   *
   * @param top the top of the part of the table that can be drawn
   * @param bottom the bottom of the part of the table that can be drawn
   * @return an <CODE>ArrayList</CODE> of <CODE>PdfLine</CODE>s
   */
  public ArrayList getLines(float top, float bottom) {
    float lineHeight;
    float currentPosition = Math.min(top(), top);
    setTop(currentPosition + cellspacing);
    ArrayList result = new ArrayList();

    // if the bottom of the page is higher than the top of the cell: do nothing
    if (top() < bottom) {
      return result;
    }

    // we loop over the lines
    int size = lines.size();
    boolean aboveBottom = true;
    for (int i = 0; i < size && aboveBottom; i++) {
      line = (PdfLine) lines.get(i);
      lineHeight = line.height();
      currentPosition -= lineHeight;
      // if the currentPosition is higher than the bottom, we add the line to the result
      if (currentPosition > (bottom + cellpadding + getBorderWidthInside(BOTTOM))) {
        result.add(line);
      } else {
        aboveBottom = false;
      }
    }
    // if the bottom of the cell is higher than the bottom of the page, the cell is written, so we
    // can remove all lines
    float difference = 0f;
    if (!header) {
      if (aboveBottom) {
        lines = new ArrayList();
        contentHeight = 0f;
      } else {
        size = result.size();
        for (int i = 0; i < size; i++) {
          line = removeLine(0);
          difference += line.height();
        }
      }
    }
    if (difference > 0) {
      Image image;
      for (Iterator i = images.iterator(); i.hasNext(); ) {
        image = (Image) i.next();
        image.setAbsolutePosition(image.absoluteX(), image.absoluteY() - difference - leading);
      }
    }
    return result;
  }
Example #9
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);
      }
    }
 /**
  * Gets the width of the <CODE>PdfChunk</CODE> taking into account the extra character and word
  * spacing.
  *
  * @param charSpacing the extra character spacing
  * @param wordSpacing the extra word spacing
  * @return the calculated width
  */
 public float getWidthCorrected(float charSpacing, float wordSpacing) {
   if (image != null) {
     return image.getScaledWidth() + charSpacing;
   }
   int numberOfSpaces = 0;
   int idx = -1;
   while ((idx = value.indexOf(' ', idx + 1)) >= 0) ++numberOfSpaces;
   return width() + (value.length() * charSpacing + numberOfSpaces * wordSpacing);
 }
Example #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 execute(PdfContentByte cb, BaseFont bf) {
   String t = sanitizeText(getText());
   Barcode128 code128 = new Barcode128();
   code128.setGenerateChecksum(true);
   code128.setCode(t);
   if (!isShowText()) {
     code128.setFont(null);
   }
   code128.setBarHeight(getSize());
   Image img = code128.createImageWithBarcode(cb, getColor(), getColor());
   // float w = code128.getBarcodeSize().width() / 2;
   img.setAbsolutePosition(getOffsetX(), getOffsetY());
   img.setRotationDegrees(getDirection());
   try {
     cb.addImage(img);
   } catch (DocumentException e) {
     // Do nothing for the time being...
   }
 }
  /**
   * Truncates this <CODE>PdfChunk</CODE> if it's too long for the given width.
   *
   * <p>Returns <VAR>null</VAR> if the <CODE>PdfChunk</CODE> wasn't truncated.
   *
   * @param width a given width
   * @return the <CODE>PdfChunk</CODE> that doesn't fit into the width.
   */
  PdfChunk truncate(float width) {
    if (image != null) {
      if (image.getScaledWidth() > width) {
        PdfChunk pc = new PdfChunk("", this);
        value = "";
        attributes.remove(Chunk.IMAGE);
        image = null;
        font = PdfFont.getDefaultFont();
        return pc;
      } else return null;
    }

    int currentPosition = 0;
    float currentWidth = 0;

    // it's no use trying to split if there isn't even enough place for a space
    if (width < font.width()) {
      String returnValue = value.substring(1);
      value = value.substring(0, 1);
      PdfChunk pc = new PdfChunk(returnValue, this);
      return pc;
    }

    // loop over all the characters of a string
    // or until the totalWidth is reached
    int length = value.length();
    boolean surrogate = false;
    char character;
    while (currentPosition < length) {
      // the width of every character is added to the currentWidth
      surrogate = Utilities.isSurrogatePair(value, currentPosition);
      if (surrogate) currentWidth += font.width(Utilities.convertToUtf32(value, currentPosition));
      else currentWidth += font.width(value.charAt(currentPosition));
      if (currentWidth > width) break;
      if (surrogate) currentPosition++;
      currentPosition++;
    }

    // if all the characters fit in the total width, null is returned (there is no overflow)
    if (currentPosition == length) {
      return null;
    }

    // otherwise, the string has to be truncated
    // currentPosition -= 2;
    // we have to chop off minimum 1 character from the chunk
    if (currentPosition == 0) {
      currentPosition = 1;
      if (surrogate) ++currentPosition;
    }
    String returnValue = value.substring(currentPosition);
    value = value.substring(0, currentPosition);
    PdfChunk pc = new PdfChunk(returnValue, this);
    return pc;
  }
Example #14
0
  /**
   * Gets the images of a cell that can be drawn between certain limits.
   *
   * <p>Remark: all the lines that can be drawn are removed from the object!
   *
   * @param top the top of the part of the table that can be drawn
   * @param bottom the bottom of the part of the table that can be drawn
   * @return an <CODE>ArrayList</CODE> of <CODE>Image</CODE>s
   */
  public ArrayList getImages(float top, float bottom) {

    // if the bottom of the page is higher than the top of the cell: do nothing
    if (top() < bottom) {
      return new ArrayList();
    }
    top = Math.min(top(), top);
    // initialisations
    Image image;
    float height;
    ArrayList result = new ArrayList();
    // we loop over the images
    for (Iterator i = images.iterator(); i.hasNext() && !header; ) {
      image = (Image) i.next();
      height = image.absoluteY();
      // if the currentPosition is higher than the bottom, we add the line to the result
      if (top - height > (bottom + cellpadding)) {
        image.setAbsolutePosition(image.absoluteX(), top - height);
        result.add(image);
        i.remove();
      }
    }
    return result;
  }
  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 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();
   }
 }
 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);
   }
 }
  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);
  }
Example #19
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);
    }
  }
Example #20
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 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);
 }
 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);
 }
Example #23
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;
   }
 }
Example #24
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());
    }
  }
  /**
   * 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;
    }
  }
  /** @see com.lowagie.toolbox.AbstractTool#execute() */
  public void execute() {
    try {
      if (getValue("odd") == null)
        throw new InstantiationException("You need to choose a sourcefile for the odd pages");
      File odd_file = (File) getValue("odd");
      if (getValue("even") == null)
        throw new InstantiationException("You need to choose a sourcefile for the even pages");
      File even_file = (File) getValue("even");
      if (getValue("destfile") == null)
        throw new InstantiationException("You need to choose a destination file");
      File pdf_file = (File) getValue("destfile");
      RandomAccessFileOrArray odd = new RandomAccessFileOrArray(odd_file.getAbsolutePath());
      RandomAccessFileOrArray even = new RandomAccessFileOrArray(even_file.getAbsolutePath());
      Image img = TiffImage.getTiffImage(odd, 1);
      Document document = new Document(new Rectangle(img.getScaledWidth(), img.getScaledHeight()));
      PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(pdf_file));
      document.open();
      PdfContentByte cb = writer.getDirectContent();
      int count = Math.max(TiffImage.getNumberOfPages(odd), TiffImage.getNumberOfPages(even));
      for (int c = 0; c < count; ++c) {
        try {
          Image imgOdd = TiffImage.getTiffImage(odd, c + 1);
          Image imgEven = TiffImage.getTiffImage(even, count - c);
          document.setPageSize(new Rectangle(imgOdd.getScaledWidth(), imgOdd.getScaledHeight()));
          document.newPage();
          imgOdd.setAbsolutePosition(0, 0);
          cb.addImage(imgOdd);
          document.setPageSize(new Rectangle(imgEven.getScaledWidth(), imgEven.getScaledHeight()));
          document.newPage();
          imgEven.setAbsolutePosition(0, 0);
          cb.addImage(imgEven);

        } catch (Exception e) {
          System.out.println("Exception page " + (c + 1) + " " + e.getMessage());
        }
      }
      odd.close();
      even.close();
      document.close();
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
  /**
   * 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();
    }
  }
Example #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));
        }
      }
    }
  }
  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();
    }
  }
Example #30
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
  }