/**
   * Método que dibuja el número de página.
   *
   * @param writer Creador de documentos.
   * @param document Documento del informe.
   */
  public void drawPageNumber(PdfWriter writer, Document document) {
    PdfContentByte cb = writer.getDirectContent();
    cb.saveState();

    // Número de página
    String text =
        new StringBuffer()
            .append("Página ")
            .append(writer.getPageNumber())
            .append(" de ")
            .toString();

    float textSize = HELVETICA.getWidthPoint(text, 8);
    float textBase = document.bottom() - 20;

    cb.beginText();
    cb.setColorFill(FOOTER_COLOR);
    cb.setFontAndSize(HELVETICA, 8);
    cb.setTextMatrix(document.right() - textSize - 20, textBase);
    cb.showText(text);
    cb.endText();
    cb.addTemplate(tpl, document.right() - 20, textBase);

    cb.restoreState();
  }
  public void beginDraw() {
    //    long t0 = System.currentTimeMillis();

    if (document == null) {
      document = new Document(new Rectangle(width, height));
      try {
        if (file != null) {
          // BufferedOutputStream output = new BufferedOutputStream(stream, 16384);
          output = new BufferedOutputStream(new FileOutputStream(file), 16384);

        } else if (output == null) {
          throw new RuntimeException(
              "PGraphicsPDF requires a path " + "for the location of the output file.");
        }
        writer = PdfWriter.getInstance(document, output);
        document.open();
        content = writer.getDirectContent();
        //        template = content.createTemplate(width, height);

      } catch (Exception e) {
        e.printStackTrace();
        throw new RuntimeException("Problem saving the PDF file.");
      }

      //      System.out.println("beginDraw fonts " + (System.currentTimeMillis() - t));
      g2 = content.createGraphics(width, height, getMapper());
      //      g2 = template.createGraphics(width, height, mapper);
    }
    //    System.out.println("beginDraw " + (System.currentTimeMillis() - t0));
    super.beginDraw();
  }
Example #3
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);
      }
    }
    @Override
    public void onEndPage(PdfWriter writer, Document document) {
      try {
        Rectangle page = document.getPageSize();

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

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

        // Add page border

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

      } catch (JSONException e) {
        Logger.getLogger(ExportProjectReportServlet.class.getName()).log(Level.SEVERE, null, e);
        throw new ExceptionConverter(e);
      }
    }
Example #5
0
  public void toPDFGraphicFile(File file, int width, int height) throws IOException {
    // otherwise toolbar appears
    plotToolBar.setVisible(false);

    com.lowagie.text.Document document = new com.lowagie.text.Document();
    document.setPageSize(new Rectangle(width, height));
    FileOutputStream fos = new FileOutputStream(file);

    PdfWriter writer = null;
    try {
      writer = PdfWriter.getInstance(document, fos);
    } catch (DocumentException ex) {
      Logger.getLogger(PlotPanel.class.getName()).log(Level.SEVERE, null, ex);
    }
    document.open();
    PdfContentByte cb = writer.getDirectContent();
    PdfTemplate tp = cb.createTemplate(width, height);
    Graphics2D g2d = tp.createGraphics(width, height);

    Image image = createImage(getWidth(), getHeight());
    paint(image.getGraphics());
    image = new ImageIcon(image).getImage();

    g2d.drawImage(image, 0, 0, Color.WHITE, null);
    g2d.dispose();
    cb.addTemplate(tp, 1, 0, 0, 1, 0, 0);

    document.close();
    // make it reappear
    plotToolBar.setVisible(true);
  }
  protected void drawHyperlink(
      final RenderNode box, final String target, final String window, final String title) {
    if (box.isNodeVisible(getDrawArea()) == false) {
      return;
    }

    final PdfAction action = createActionForLink(target);

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

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

    if (action != null) {
      final PdfAnnotation annotation =
          new PdfAnnotation(writer, leftX, lowerY, rightX, upperY, action);
      writer.addAnnotation(annotation);
    } else if (StringUtils.isEmpty(title) == false) {
      final Rectangle rect = new Rectangle(leftX, lowerY, rightX, upperY);
      final PdfAnnotation commentAnnotation =
          PdfAnnotation.createText(writer, rect, "Tooltip", title, false, null);
      commentAnnotation.setAppearance(
          PdfAnnotation.APPEARANCE_NORMAL,
          writer.getDirectContent().createAppearance(rect.getWidth(), rect.getHeight()));
      writer.addAnnotation(commentAnnotation);
    }
  }
Example #7
0
  /**
   * Generates simple PDF, RTF and HTML files using only one Document object.
   *
   * @param args no arguments needed here
   */
  public static void main(String[] args) {

    System.out.println("Hello World in PDF, RTF and HTML");

    // step 1: creation of a document-object
    Document document = new Document();
    try {
      // step 2:
      // we create 3 different writers that listen to the document
      File file1 = new File("HelloWorldPdf.pdf");
      File file2 = new File("HelloWorldRtf.rtf");
      File file3 = new File("HelloWorldHtml.html");

      if (!file1.exists()) {
        file1.canWrite();
      }
      if (!file2.exists()) {
        file2.canWrite();
      }
      if (!file3.exists()) {
        file3.canWrite();
      }

      PdfWriter pdf = PdfWriter.getInstance(document, new FileOutputStream(file1));
      RtfWriter2 rtf = RtfWriter2.getInstance(document, new FileOutputStream(file2));
      HtmlWriter.getInstance(document, new FileOutputStream(file3));

      // step 3: we open the document
      document.open();
      // step 4: we add a paragraph to the document
      document.add(new Paragraph("Hello World"));

      // we make references
      Anchor pdfRef = new Anchor("see Hello World in PDF.");
      pdfRef.setReference("./HelloWorldPdf.pdf");

      Anchor rtfRef = new Anchor("see Hello World in RTF.");
      rtfRef.setReference("./HelloWorldRtf.rtf");

      // we add the references, but only to the HTML page:

      pdf.pause();
      rtf.pause();
      document.add(pdfRef);
      document.add(Chunk.NEWLINE);
      document.add(rtfRef);
      pdf.resume();
      rtf.resume();

    } catch (DocumentException de) {
      System.err.println(de.getMessage());
    } catch (IOException ioe) {
      System.err.println(ioe.getMessage());
    }

    // step 5: we close the document
    document.close();
  }
 public static void main(String[] args) throws Exception {
   Document doc = new Document();
   PdfWriter writer =
       PdfWriter.getInstance(doc, new FileOutputStream("unsigned_signature_field.pdf"));
   doc.open();
   doc.add(new Paragraph("Hello world with digital signature block."));
   PdfAcroForm acroForm = writer.getAcroForm();
   acroForm.addSignature("sig", 73, 705, 149, 759);
   doc.close();
 }
Example #9
0
  /**
   * Creates a document with some goto actions.
   *
   * @param args no arguments needed
   */
  public static void main(String[] args) {

    System.out.println("Destinations");

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

      // step 2:
      PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream("Destinations.pdf"));
      // step 3:
      writer.setViewerPreferences(PdfWriter.PageModeUseOutlines);
      document.open();
      // step 4: we grab the ContentByte and do some stuff with it
      PdfContentByte cb = writer.getDirectContent();

      // we create a PdfTemplate
      PdfTemplate template = cb.createTemplate(25, 25);

      // we add some crosses to visualize the destinations
      template.moveTo(13, 0);
      template.lineTo(13, 25);
      template.moveTo(0, 13);
      template.lineTo(50, 13);
      template.stroke();

      // we add the template on different positions
      cb.addTemplate(template, 287, 787);
      cb.addTemplate(template, 187, 487);
      cb.addTemplate(template, 487, 287);
      cb.addTemplate(template, 87, 87);

      // we define the destinations
      PdfDestination d1 = new PdfDestination(PdfDestination.XYZ, 300, 800, 0);
      PdfDestination d2 = new PdfDestination(PdfDestination.FITH, 500);
      PdfDestination d3 = new PdfDestination(PdfDestination.FITR, 200, 300, 400, 500);
      PdfDestination d4 = new PdfDestination(PdfDestination.FITBV, 100);
      PdfDestination d5 = new PdfDestination(PdfDestination.FIT);

      // we define the outlines
      PdfOutline out1 = new PdfOutline(cb.getRootOutline(), d1, "root");
      PdfOutline out2 = new PdfOutline(out1, d2, "sub 1");
      new PdfOutline(out1, d3, "sub 2");
      new PdfOutline(out2, d4, "sub 2.1");
      new PdfOutline(out2, d5, "sub 2.2");
    } catch (Exception de) {
      de.printStackTrace();
    }

    // step 5: we close the document
    document.close();
  }
Example #10
0
  @Override
  public void createITextObject(FacesContext context) {

    if (getBorderBackgroundPaint() != null) {
      chart.setBackgroundPaint(findColor(getBorderBackgroundPaint()));
    }

    if (getBorderPaint() != null) {
      chart.setBorderPaint(findColor(getBorderPaint()));
    }

    if (getBorderStroke() != null) {
      chart.setBorderStroke(findStroke(getBorderStroke()));
    }

    chart.setBorderVisible(getBorderVisible());

    configurePlot(chart.getPlot());

    try {
      UIDocument doc = (UIDocument) findITextParent(getParent(), UIDocument.class);
      if (doc != null) {
        PdfWriter writer = (PdfWriter) doc.getWriter();
        PdfContentByte cb = writer.getDirectContent();
        PdfTemplate tp = cb.createTemplate(getWidth(), getHeight());

        UIFont font = (UIFont) findITextParent(this, UIFont.class);

        DefaultFontMapper fontMapper;
        if (font == null) {
          fontMapper = new DefaultFontMapper();
        } else {
          fontMapper = new AsianFontMapper(font.getName(), font.getEncoding());
        }

        Graphics2D g2 = tp.createGraphics(getWidth(), getHeight(), fontMapper);
        chart.draw(g2, new Rectangle2D.Double(0, 0, getWidth(), getHeight()));
        g2.dispose();

        image = new ImgTemplate(tp);
      } else {
        ByteArrayOutputStream stream = new ByteArrayOutputStream();
        ChartUtilities.writeChartAsJPEG(stream, chart, getWidth(), getHeight());

        imageData = stream.toByteArray();
        stream.close();
      }
    } catch (Exception e) {
      throw new RuntimeException(e);
    }
  }
Example #11
0
 public void exportGraphic(Picture picture, OutputStream out) throws IOException {
   int width = picture.getPictureWidth();
   int height = picture.getPictureHeight();
   Document doc = new Document(new com.lowagie.text.Rectangle(width, height));
   try {
     PdfWriter pWriter = PdfWriter.getInstance(doc, out);
     doc.open();
     Graphics2D g = pWriter.getDirectContent().createGraphics(width, height);
     picture.paintPicture(g);
     g.dispose();
     doc.close();
   } catch (DocumentException e) {
     throw (IOException) new IOException(e.getMessage()).initCause(e);
   }
 }
  /**
   * @param index
   * @throws DocumentException
   * @throws IOException
   */
  public PdfHDPageWrapper(int index) throws DocumentException, IOException {
    // Read settings.
    // '_' - prefix for for temp file. After stamping file would be renamed
    outputFileName = "_" + index + WikiSettings.getInstance().getOutputFileName();

    // 72 pixels per inch
    // pdfDocument = new Document(new Rectangle(432, 648));//6" x 9"
    pdfDocument = new Document(new Rectangle(1918, 1018)); //

    // pdfDocument.setMargins(32, 32, 0, 32);
    pdfDocument.setMargins(32, 32, -565, 32);

    pdfWriter =
        PdfWriter.getInstance(
            pdfDocument,
            new FileOutputStream(
                WikiSettings.getInstance().getOutputFolder() + "/" + outputFileName));

    // header = new PageHeaderEvent(0);
    // pdfWriter.setPageEvent(header);

    pdfDocument.open();
    // pdfDocument.setMarginMirroring(true);
    _wikiFontSelector = new WikiFontSelector();

    // PdfContentByte cb = pdfWriter.getDirectContent();
    // ColumnText ct = new ColumnText(cb);
    openMultiColumn();
  }
Example #13
0
  /**
   * An example using MultiColumnText with irregular columns.
   *
   * @param args no arguments needed
   */
  public static void main(String[] args) {

    System.out.println("Simple MultiColumnText");
    try {
      Document document = new Document();
      OutputStream out = new FileOutputStream("multicolumnsimple.pdf");
      PdfWriter.getInstance(document, out);
      document.open();

      MultiColumnText mct = new MultiColumnText();

      // set up 3 even columns with 10pt space between
      mct.addRegularColumns(document.left(), document.right(), 10f, 3);

      // Write some iText poems
      for (int i = 0; i < 30; i++) {
        mct.addElement(new Paragraph(String.valueOf(i + 1)));
        mct.addElement(newPara(randomWord(noun), Element.ALIGN_CENTER, Font.BOLDITALIC));
        for (int j = 0; j < 4; j++) {
          mct.addElement(newPara(poemLine(), Element.ALIGN_LEFT, Font.NORMAL));
        }
        mct.addElement(newPara(randomWord(adverb), Element.ALIGN_LEFT, Font.NORMAL));
        mct.addElement(newPara("\n\n", Element.ALIGN_LEFT, Font.NORMAL));
      }
      document.add(mct);
      document.close();
    } catch (DocumentException e) {
      e.printStackTrace();
    } catch (FileNotFoundException e) {
      e.printStackTrace();
    }
  }
  protected void drawImageMap(final RenderableReplacedContentBox content) {
    if (version < '6') {
      return;
    }

    final ImageMap imageMap = RenderUtility.extractImageMap(content);
    // only generate a image map, if the user does not specify their own onw via the override.
    // Of course, they would have to provide the map by other means as well.

    if (imageMap == null) {
      return;
    }

    final ImageMapEntry[] imageMapEntries = imageMap.getMapEntries();
    for (int i = 0; i < imageMapEntries.length; i++) {
      final ImageMapEntry imageMapEntry = imageMapEntries[i];
      final String link = imageMapEntry.getAttribute(LibXmlInfo.XHTML_NAMESPACE, "href");
      final String tooltip = imageMapEntry.getAttribute(LibXmlInfo.XHTML_NAMESPACE, "title");
      if (StringUtils.isEmpty(tooltip)) {
        continue;
      }

      final AffineTransform affineTransform = getGraphics().getTransform();
      final float translateX = (float) affineTransform.getTranslateX();
      final int x = (int) (translateX + StrictGeomUtility.toExternalValue(content.getX()));
      final int y = (int) StrictGeomUtility.toExternalValue(content.getY());
      final float[] translatedCoords =
          translateCoordinates(imageMapEntry.getAreaCoordinates(), x, y);

      final PolygonAnnotation polygonAnnotation = new PolygonAnnotation(writer, translatedCoords);
      polygonAnnotation.put(PdfName.CONTENTS, new PdfString(tooltip, PdfObject.TEXT_UNICODE));
      writer.addAnnotation(polygonAnnotation);
    }
  }
  protected boolean drawPdfScript(final RenderNode box) {
    final Object attribute =
        box.getAttributes()
            .getAttribute(AttributeNames.Pdf.NAMESPACE, AttributeNames.Pdf.SCRIPT_ACTION);
    if (attribute == null) {
      return false;
    }

    final String attributeText = String.valueOf(attribute);
    final PdfAction action = PdfAction.javaScript(attributeText, writer, false);

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

    final float leftX = translateX + (float) (StrictGeomUtility.toExternalValue(box.getX()));
    final float rightX =
        translateX + (float) (StrictGeomUtility.toExternalValue(box.getX() + box.getWidth()));
    final float lowerY =
        (float) (globalHeight - StrictGeomUtility.toExternalValue(box.getY() + box.getHeight()));
    final float upperY = (float) (globalHeight - StrictGeomUtility.toExternalValue(box.getY()));
    final PdfAnnotation annotation =
        new PdfAnnotation(writer, leftX, lowerY, rightX, upperY, action);
    writer.addAnnotation(annotation);
    return true;
  }
  public void processLogicalPage(final LogicalPageKey key, final LogicalPageBox logicalPage)
      throws DocumentException {

    final float width = (float) StrictGeomUtility.toExternalValue(logicalPage.getPageWidth());
    final float height = (float) StrictGeomUtility.toExternalValue(logicalPage.getPageHeight());

    final Rectangle pageSize = new Rectangle(width, height);

    final Document document = getDocument();
    document.setPageSize(pageSize);
    document.setMargins(0, 0, 0, 0);

    if (awaitOpenDocument) {
      document.open();
      awaitOpenDocument = false;
    }

    final Graphics2D graphics =
        new PdfGraphics2D(writer.getDirectContent(), width, height, metaData);
    // and now process the box ..
    final PdfLogicalPageDrawable logicalPageDrawable =
        new PdfLogicalPageDrawable(
            logicalPage, metaData, writer, null, resourceManager, imageCache, version);
    logicalPageDrawable.draw(graphics, new Rectangle2D.Double(0, 0, width, height));

    graphics.dispose();

    document.newPage();
  }
Example #17
0
    // Evento cuando que se ejecuta al comenzar una documento
    @Override
    public void onOpenDocument(PdfWriter writer, Document document) {

      // Definimos las medidas del template
      total = writer.getDirectContent().createTemplate(10, 16);
      System.out.println(total);
    }
Example #18
0
 public static void main(String[] args) throws Exception {
   Document doc = new Document();
   PdfWriter.getInstance(doc, new FileOutputStream("htmlToPdfAuto.pdf"));
   doc.open();
   HtmlParser.parse(
       doc, new InputSource(HtmlToPdfAuto.class.getResourceAsStream("/htmlToPdfSaxAuto.html")));
   doc.close();
 }
 /**
  * Método que se ejecuta cuando se cierra el documento.
  *
  * @param writer Creador de documentos.
  * @param document Documento del informe.
  */
 public void onCloseDocument(PdfWriter writer, Document document) {
   // Plantilla con el número total de páginas del documento
   tpl.beginText();
   tpl.setFontAndSize(HELVETICA, 8);
   tpl.setTextMatrix(0, 0);
   tpl.showText("" + (writer.getPageNumber() - 1));
   tpl.endText();
 }
 public void onOpenDocument(PdfWriter writer, Document document) {
   try {
     cb = writer.getDirectContent();
     template = cb.createTemplate(50, 50);
   } catch (Exception e) {
     e.printStackTrace();
   }
 }
Example #21
0
 public void manipulatePdf(String src, String dest, int pow)
     throws IOException, DocumentException {
   PdfReader reader = new PdfReader(src);
   Rectangle pageSize = reader.getPageSize(1);
   Rectangle newSize =
       (pow % 2) == 0
           ? new Rectangle(pageSize.getWidth(), pageSize.getHeight())
           : new Rectangle(pageSize.getHeight(), pageSize.getWidth());
   Rectangle unitSize = new Rectangle(pageSize.getWidth(), pageSize.getHeight());
   for (int i = 0; i < pow; i++) {
     unitSize = new Rectangle(unitSize.getHeight() / 2, unitSize.getWidth());
   }
   int n = (int) Math.pow(2, pow);
   int r = (int) Math.pow(2, pow / 2);
   int c = n / r;
   Document document = new Document(newSize, 0, 0, 0, 0);
   PdfWriter writer =
       PdfWriter.getInstance(document, new FileOutputStream(String.format(dest, n)));
   document.open();
   PdfContentByte cb = writer.getDirectContent();
   PdfImportedPage page;
   Rectangle currentSize;
   float offsetX, offsetY, factor;
   int total = reader.getNumberOfPages();
   for (int i = 0; i < total; ) {
     if (i % n == 0) {
       document.newPage();
     }
     currentSize = reader.getPageSize(++i);
     factor =
         Math.min(
             unitSize.getWidth() / currentSize.getWidth(),
             unitSize.getHeight() / currentSize.getHeight());
     offsetX =
         unitSize.getWidth() * ((i % n) % c)
             + (unitSize.getWidth() - (currentSize.getWidth() * factor)) / 2f;
     offsetY =
         newSize.getHeight()
             - (unitSize.getHeight() * (((i % n) / c) + 1))
             + (unitSize.getHeight() - (currentSize.getHeight() * factor)) / 2f;
     page = writer.getImportedPage(reader, i);
     cb.addTemplate(page, factor, 0, 0, factor, offsetX, offsetY);
   }
   document.close();
 }
 private boolean txt2Pdf(File inputFile, File outputFile, Charset inputFileCharset) {
   // // 先将txt转成odt
   // String fileName = inputFile.getAbsolutePath();
   // if (fileName.endsWith(".txt")) {
   BufferedReader bufferedReader = null;
   try {
     // 判断原始txt文件的编码格式,获取响应的文件读入
     bufferedReader =
         new BufferedReader(
             new InputStreamReader(new FileInputStream(inputFile), inputFileCharset));
     // 将txt内容直接生成pdf
     Document document = new Document();
     BaseFont bfChinese =
         BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
     Font font_normal = new Font(bfChinese, 10, Font.NORMAL); // 设置字体大小
     document.setPageSize(PageSize.A4); // 设置页面大小
     if (!outputFile.exists()) {
       outputFile.createNewFile();
     }
     try {
       PdfWriter.getInstance(document, new FileOutputStream(outputFile));
       document.open();
     } catch (Exception e) {
       e.printStackTrace();
     }
     String content = null;
     while ((content = bufferedReader.readLine()) != null) {
       document.add(new Paragraph(content, font_normal));
     }
     document.close();
     bufferedReader.close();
     return true;
   } catch (ConnectException cex) {
     cex.printStackTrace();
     // System.out.println("转换失败!");
     return false;
   } catch (FileNotFoundException e) {
     e.printStackTrace();
     return false;
   } catch (IOException e) {
     e.printStackTrace();
     return false;
   } catch (DocumentException e) {
     e.printStackTrace();
     return false;
   } finally {
     // close the connection
     if (bufferedReader != null) {
       try {
         bufferedReader.close();
       } catch (IOException e) {
         e.printStackTrace();
       }
     }
   }
   // }
 }
 private ByteArrayOutputStream getPdfData(
     JSONArray data, JSONArray res, HttpServletRequest request) throws ServiceException {
   ByteArrayOutputStream baos = new ByteArrayOutputStream();
   try {
     String[] colHeader = getColHeader();
     String[] colIndex = getColIndexes();
     String[] val = getColValues(colHeader, data);
     String[] resources = getResourcesColHeader(res, data);
     String[] mainHeader = {"Dates", "Duration", "Work", "Cost", "Tasks", "Resources"};
     Document document = null;
     if (landscape) {
       Rectangle recPage = new Rectangle(PageSize.A4.rotate());
       recPage.setBackgroundColor(new java.awt.Color(255, 255, 255));
       document = new Document(recPage, 15, 15, 30, 30);
     } else {
       Rectangle recPage = new Rectangle(PageSize.A4);
       recPage.setBackgroundColor(new java.awt.Color(255, 255, 255));
       document = new Document(recPage, 15, 15, 30, 30);
     }
     PdfWriter writer = PdfWriter.getInstance(document, baos);
     writer.setPageEvent(new EndPage());
     document.open();
     if (showLogo) {
       getCompanyDetails(request);
       addComponyLogo(document, request);
     }
     addTitleSubtitle(document);
     addTable(data, resources, colIndex, colHeader, mainHeader, val, document);
     document.close();
     writer.close();
     baos.close();
   } catch (ConfigurationException ex) {
     throw ServiceException.FAILURE("ExportProjectReport.getPdfData", ex);
   } catch (DocumentException ex) {
     throw ServiceException.FAILURE("ExportProjectReport.getPdfData", ex);
   } catch (JSONException e) {
     throw ServiceException.FAILURE("ExportProjectReport.getPdfData", e);
   } catch (IOException e) {
     throw ServiceException.FAILURE("ExportProjectReport.getPdfData", e);
   } catch (Exception e) {
     throw ServiceException.FAILURE("ExportProjectReport.getPdfData", e);
   }
   return baos;
 }
  public void generatorPDF(Document d, PdfWriter writer)
      throws DocumentException, MalformedURLException, IOException {
    // Rectangle pageSize = new Rectangle(650, 950);
    // pageSize.setBackgroundColor(new java.awt.Color(0xDF, 0xFF, 0xDE));
    // Document d = new Document(pageSize);
    // Document d = new Document();
    writer.setPageEvent(new HeaderAndFooter(writer, _user.getLogoUrl()));
    try {
      // d.open();
      // addMetaData(d);
      // writer.setEncryption(USER_PASS.getBytes(), OWNER_PASS.getBytes(),PdfWriter.AllowPrinting,
      // PdfWriter.STRENGTH128BITS);
      if (!_monthExpenseList.isEmpty()) {
        PdfPTable headerTable = new PdfPTable(3);
        generateHeaderTable(_user, headerTable);
        d.add(headerTable);
        int flag = 0;
        for (MonthExpense me : _monthExpenseList) {
          String MonthName = null;
          if (!me.getExpenseItem().isEmpty()) {
            DateFormat outputFormatter = new SimpleDateFormat("EEE, dd MMM yyyy");
            Date date = (Date) outputFormatter.parse(me.getExpenseItem().get(0).getDate());
            MonthName = new SimpleDateFormat("MMMM-yyyy").format(date);

            Paragraph preface = new Paragraph();
            preface.add(
                new Paragraph("Expense Breakup(" + MonthName + "):-", PDFCellStyles.smallBold));
            addEmptyLine(preface, 1);
            d.add(preface);
            PdfPTable table = generateLineItemTable(me.getExpenseItem(), MonthName);
            d.add(table);
            flag++;
            if (flag < _monthExpenseList.size()) {
              d.newPage(); // Start a new page
            }
          }
        }
        Paragraph note =
            new Paragraph(
                "\n\nNote:- \n\tExpense between Rs.100 and Rs.500 are marked by blue.\n\tExpense greater than Rs.500 are marked by Red.",
                PDFCellStyles.smallItalic);
        Paragraph p = new Paragraph("\nFor more, please visit ");
        Anchor anchor =
            new Anchor(
                "www.Ihalkhata.com",
                FontFactory.getFont(FontFactory.COURIER, 12, Font.UNDERLINE, new Color(0, 0, 255)));

        p.add(anchor);
        d.add(note);
        d.add(p);
      }
      // d.close();
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
  /** @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();
    }
  }
 /**
  * Writing vertical text.
  *
  * @param args no arguments needed
  */
 public static void main(String[] args) {
   Document document = new Document(PageSize.A4, 50, 50, 50, 50);
   try {
     texts[3] = convertCid(texts[0]);
     texts[4] = convertCid(texts[1]);
     texts[5] = convertCid(texts[2]);
     PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream("vertical.pdf"));
     int idx = 0;
     document.open();
     PdfContentByte cb = writer.getDirectContent();
     for (int j = 0; j < 2; ++j) {
       BaseFont bf = BaseFont.createFont("KozMinPro-Regular", encs[j], false);
       cb.setRGBColorStroke(255, 0, 0);
       cb.setLineWidth(0);
       float x = 400;
       float y = 700;
       float height = 400;
       float leading = 30;
       int maxLines = 6;
       for (int k = 0; k < maxLines; ++k) {
         cb.moveTo(x - k * leading, y);
         cb.lineTo(x - k * leading, y - height);
       }
       cb.rectangle(x, y, -leading * (maxLines - 1), -height);
       cb.stroke();
       int status;
       VerticalText vt = new VerticalText(cb);
       vt.setVerticalLayout(x, y, height, maxLines, leading);
       vt.addText(new Chunk(texts[idx++], new Font(bf, 20)));
       vt.addText(new Chunk(texts[idx++], new Font(bf, 20, 0, Color.blue)));
       status = vt.go();
       System.out.println(status);
       vt.setAlignment(Element.ALIGN_RIGHT);
       vt.addText(new Chunk(texts[idx++], new Font(bf, 20, 0, Color.orange)));
       status = vt.go();
       System.out.println(status);
       document.newPage();
     }
     document.close();
   } catch (Exception de) {
     de.printStackTrace();
   }
 }
Example #27
0
 /*
  * crea un file pdf contenente lo stack trace dell'eccezione
  */
 private void createErrorFile(String url, File outputFile, Exception exception) {
   Document document = new Document();
   PdfWriter pdfwriter = null;
   try {
     pdfwriter = PdfWriter.getInstance(document, new FileOutputStream(outputFile));
     document.open();
     StringBuilder buffer = new StringBuilder("Non è stato possibile generare");
     buffer.append(" il file pdf per l'URL\n\n");
     buffer.append(url);
     buffer.append("\n\na causa del seguente errore:\n\n");
     document.add(new Paragraph(buffer.toString()));
     StringWriter stringWriter = new StringWriter();
     exception.printStackTrace(new PrintWriter(stringWriter));
     document.add(new Paragraph(stringWriter.toString()));
     document.close();
     pdfwriter.close();
   } catch (FileNotFoundException | DocumentException e) {
     log.error("errore di scrittura del file di errore", e);
   }
 }
Example #28
0
 @Override
 public void onCloseDocument(PdfWriter writer, Document document) {
   // Escribimos el contenido al cerrar el documento
   ColumnText.showTextAligned(
       total,
       Element.ALIGN_LEFT,
       new Phrase(String.valueOf(writer.getPageNumber() - 1)),
       2,
       2,
       0);
 }
Example #29
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();
  }
Example #30
0
  public AbstractPDFGenerator(final OutputStream out, final String type) {
    this.out = out;
    try {
      if (type != null && "landscape".equalsIgnoreCase(type))
        document = new Document(PageSize.A4.rotate());
      else document = new Document();

      PdfWriter.getInstance(document, out);
      document.open();
    } catch (final Exception e) {
      throw new ApplicationRuntimeException("estimate.pdf.error", e);
    }
  }