示例#1
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 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();
    }
  }
  /**
   * 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();
    }
  }
示例#4
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();
  }
  @Override
  public Document create(Map<String, Object> model, Document doc) throws DocumentException {
    doc.newPage();

    List<Pasien> list = (List<Pasien>) model.get("list");
    String nomorMedrek = (String) model.get("nomor");

    Paragraph paragraph = new Paragraph();
    createTitle(paragraph);

    if (nomorMedrek != null && !nomorMedrek.equals("")) {
      createContentNomorMedrek(paragraph, nomorMedrek);
    } else {
      Date awal = (Date) model.get("awal");
      Date akhir = (Date) model.get("akhir");

      createContentDateRange(paragraph, awal, akhir);
    }

    createContent(paragraph, list);

    doc.add(paragraph);

    name = String.format("rekap-pasien-%s-%s", DateUtil.getDate(), DateUtil.getTime());

    return doc;
  }
示例#6
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();
    }
  }
示例#7
0
  public void print(
      PdfWriter pdfWriter, GroupingContainer groupingContainer, Document document, Locale locale)
      throws DocumentException {
    if (notPrintOperationAtFirstPage()) {
      document.newPage();
    }

    ListMultimap<String, OrderOperationComponent> titleToOperationComponent =
        groupingContainer.getTitleToOperationComponent();
    for (String title : titleToOperationComponent.keySet()) {
      operationSectionHeader.print(document, title);
      int count = 0;
      for (OrderOperationComponent orderOperationComponent :
          groupingContainer.getTitleToOperationComponent().get(title)) {
        count++;
        operationOrderSection.print(
            pdfWriter,
            groupingContainer,
            orderOperationComponent.getOrder(),
            orderOperationComponent.getOperationComponent(),
            document,
            locale);
        if (count != titleToOperationComponent.get(title).size()) {
          if (notPrintOperationAtFirstPage()) {
            document.add(Chunk.NEXTPAGE);
          }
        }
      }
    }
  }
示例#8
0
 /**
  * Adds a table to a document.
  *
  * @param document The document to add the table to.
  * @param table The table to add to the document.
  */
 public static void addTableToDocument(Document document, PdfPTable table) {
   try {
     document.add(table);
   } catch (DocumentException ex) {
     throw new RuntimeException("Failed to add table to document", ex);
   }
 }
示例#9
0
  /**
   * Demonstrates creating a footer with the current page number
   *
   * @param args Unused
   */
  public static void main(String[] args) {
    System.out.println("Demonstrates creating a footer with a page number");
    try {
      Document document = new Document();
      RtfWriter2.getInstance(document, new FileOutputStream("PageNumber.rtf"));

      // Create a new Paragraph for the footer
      Paragraph par = new Paragraph("Page ");
      par.setAlignment(Element.ALIGN_RIGHT);

      // Add the RtfPageNumber to the Paragraph
      par.add(new RtfPageNumber());

      // Create an RtfHeaderFooter with the Paragraph and set it
      // as a footer for the document
      RtfHeaderFooter footer = new RtfHeaderFooter(par);
      document.setFooter(footer);

      document.open();

      for (int i = 1; i <= 300; i++) {
        document.add(new Paragraph("Line " + i + "."));
      }

      document.close();
    } catch (FileNotFoundException fnfe) {
      fnfe.printStackTrace();
    } catch (DocumentException de) {
      de.printStackTrace();
    }
  }
示例#10
0
  @Test
  public void testNoBreakSpace() throws Exception {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    Document document = new Document();

    PdfWriter writer = PdfWriter.getInstance(document, baos);

    document.open();
    writer.setPageEvent(
        new PdfPageEventHelper() {
          public void onParagraph(PdfWriter writer, Document document, float position) {
            PdfContentByte cb = writer.getDirectContent();
            PdfDestination destination = new PdfDestination(PdfDestination.FITH, position);
            new PdfOutline(cb.getRootOutline(), destination, TITLE);
          }
        });
    document.add(new Paragraph("Hello World"));
    document.close();

    // read bookmark back
    PdfReader r = new PdfReader(baos.toByteArray());

    List<?> bookmarks = SimpleBookmark.getBookmark(r);
    assertEquals("bookmark size", 1, bookmarks.size());
    @SuppressWarnings("unchecked")
    HashMap<String, Object> b = (HashMap<String, Object>) bookmarks.get(0);
    String title = (String) b.get("Title");
    assertEquals("bookmark title", TITLE, title);
  }
 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();
       }
     }
   }
   // }
 }
  /**
   * 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.
    }
  }
示例#13
0
 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();
 }
  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);
  }
示例#15
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);
   }
 }
示例#16
0
 /*
  * (non-Javadoc)
  *
  * @see com.afunms.report.ExportInterface#insertTitle(java.lang.String, int,
  *      java.lang.String)
  */
 public void insertTitle(String title, int colspan, String timefromto) throws Exception {
   if (!document.isOpen()) {
     document.open();
   }
   SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
   Paragraph par1 = new Paragraph(title, new Font(bfChinese, 20, Font.BOLD));
   Paragraph par2 = new Paragraph("中国气象局卫星中心", new Font(bfChinese, 14, Font.BOLD));
   Paragraph time1 =
       new Paragraph("报表生成时间:" + sdf.format(new Date()), new Font(bfChinese, 14, Font.BOLD));
   Paragraph time2 =
       new Paragraph("报表统计时间:" + sdf.format(new Date()), new Font(bfChinese, 14, Font.BOLD));
   par1.setAlignment(Element.ALIGN_TOP);
   par2.setAlignment(Element.ALIGN_CENTER);
   time1.setAlignment(Element.ALIGN_UNDEFINED);
   time2.setAlignment(Element.ALIGN_CENTER);
   time1.spacingBefore();
   document.add(par1);
   document.add(par2);
   document.add(time1);
   document.add(time2);
 }
  public Document createForm(Document document) {
    System.out.println("[StockBalancePdfForm][createForm][Begin]");

    try {
      document.add(this.genHeader());
      document.add(this.brLine());
      document.add(this.brLine());
      document.add(this.genDetail());

    } catch (DocumentException de) {
      de.printStackTrace();
    } catch (MalformedURLException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    } catch (Exception e) {
      e.printStackTrace();
    } finally {
      System.out.println("[StockBalancePdfForm][createForm][End]");
    }

    return document;
  }
示例#18
0
  /**
   * Performs the action: generate a PDF from a GET or POST.
   *
   * @param request the Servlets request object
   * @param response the Servlets request object
   * @param methodGetPost the method that was used in the form
   */
  public void makePdf(
      HttpServletRequest request, HttpServletResponse response, String methodGetPost) {
    try {

      // take the message from the URL or create default message
      String msg = request.getParameter("msg");
      if (msg == null || msg.trim().length() <= 0)
        msg = "[ specify a message in the 'msg' argument on the URL ]";

      // create simple doc and write to a ByteArrayOutputStream
      Document document = new Document();
      ByteArrayOutputStream baos = new ByteArrayOutputStream();
      PdfWriter.getInstance(document, baos);
      document.open();
      document.add(new Paragraph(msg));
      document.add(Chunk.NEWLINE);
      document.add(new Paragraph("The method used to generate this PDF was: " + methodGetPost));
      document.close();

      // setting some response headers
      response.setHeader("Expires", "0");
      response.setHeader("Cache-Control", "must-revalidate, post-check=0, pre-check=0");
      response.setHeader("Pragma", "public");
      // setting the content type
      response.setContentType("application/pdf");
      // the contentlength is needed for MSIE!!!
      response.setContentLength(baos.size());
      // write ByteArrayOutputStream to the ServletOutputStream
      ServletOutputStream out = response.getOutputStream();
      baos.writeTo(out);
      out.flush();

    } catch (Exception e2) {
      System.out.println("Error in " + getClass().getName() + "\n" + e2);
    }
  }
示例#19
0
  public ActionForward execute(
      ActionMapping mapping,
      ActionForm form,
      HttpServletRequest request,
      HttpServletResponse response)
      throws Exception {

    Document document = new Document();
    try {
      // OutputStream file = new FileOutputStream(new File("D:\\Test.pdf"));
      response.setContentType("application/pdf");
      // PdfWriter.getInstance(document, file);
      PdfWriter.getInstance(document, response.getOutputStream());
      document.open();
      document.add(new Paragraph("Hello Sasi"));
      document.add(new Paragraph(new Date().toString()));
      // file.close();
    } catch (Exception e) {
      e.printStackTrace();
    }
    document.close();

    return null;
  }
  private static void addTitleSubtitle(Document d) throws DocumentException, JSONException {
    java.awt.Color tColor = new Color(0, 0, 0);
    fontBold.setColor(tColor);
    fontRegular.setColor(tColor);
    PdfPTable table = new PdfPTable(1);
    table.setHorizontalAlignment(Element.ALIGN_CENTER);
    java.text.SimpleDateFormat df = new java.text.SimpleDateFormat("yyyy-MM-dd");
    java.util.Date today = new java.util.Date();

    table.setWidthPercentage(100);
    table.setSpacingBefore(6);

    // Report Title
    PdfPCell cell = new PdfPCell(new Paragraph("Project Summary", fontBold));
    cell.setBorder(0);
    cell.setBorderWidth(0);
    cell.setHorizontalAlignment(Element.ALIGN_CENTER);
    table.addCell(cell);

    // Sub-title(s)
    cell = new PdfPCell(new Paragraph("(on comparison with " + baseName + ")", fontRegular));
    cell.setBorder(0);
    cell.setBorderWidth(0);
    cell.setHorizontalAlignment(Element.ALIGN_CENTER);
    table.addCell(cell);

    // Separator line
    PdfPTable line = new PdfPTable(1);
    line.setWidthPercentage(100);
    PdfPCell cell1 = null;
    cell1 = new PdfPCell(new Paragraph(""));
    cell1.setBorder(PdfPCell.BOTTOM);
    line.addCell(cell1);
    d.add(table);
    d.add(line);
  }
示例#21
0
  /**
   * Extended font example.
   *
   * @param args Unused
   */
  public static void main(String[] args) {
    System.out.println("Demonstrates the extended font support");
    try {
      Document document = new Document();
      RtfWriter2.getInstance(document, new FileOutputStream("ExtendedFont.rtf"));
      document.open();

      // Create a RtfFont with the desired font name.
      RtfFont msComicSans = new RtfFont("Comic Sans MS");

      // Use the RtfFont like any other Font.
      document.add(new Paragraph("This paragraph uses the" + " Comic Sans MS font.", msComicSans));

      // Font size, font style and font colour can also be specified.
      RtfFont bigBoldGreenArial = new RtfFont("Arial", 36, Font.BOLD, Color.GREEN);

      document.add(new Paragraph("This is a really big bold green Arial text", bigBoldGreenArial));
      document.close();
    } catch (FileNotFoundException fnfe) {
      fnfe.printStackTrace();
    } catch (DocumentException de) {
      de.printStackTrace();
    }
  }
示例#22
0
  private static void addContent(
      Document document, List<EventoBean> eventi, IEventiService eventiService)
      throws UtilsException, DocumentException {
    Anchor anchor = new Anchor("Eventi Selezionati", catFont);
    anchor.setName("Eventi Selezionati");

    // Second parameter is the number of the chapter
    Chapter catPart = new Chapter(new Paragraph(anchor), 1);

    for (EventoBean eventoBean : eventi) {

      Evento evento = eventoBean.getDTO();
      Paragraph subPara = new Paragraph("Evento Id[" + evento.getId() + "]", subFont);

      Section subCatPart = catPart.addSection(subPara);

      addEmptyLine(subCatPart, 1);

      createEventoTable(subCatPart, evento);

      addEmptyLine(subCatPart, 1);

      Infospcoop infospcoop =
          eventoBean.getInfospcoop() != null ? eventoBean.getInfospcoop().getDTO() : null;
      if (infospcoop != null) {
        //			if(evento.getCategoria().equals(Categoria.INTERFACCIA) && evento.getIdEgov()!= null){

        //				Infospcoop infospcoop = eventiService.getInfospcoopByIdEgov(evento.getIdEgov());

        Paragraph infoParg = new Paragraph("Infospcoop", subFont);

        subCatPart.addSection(infoParg);

        addEmptyLine(subCatPart, 1);

        createInfospcoopTable(subCatPart, infospcoop);

        // subCatPart.add(new Paragraph(infospcoop.toXml()));
      }

      addEmptyLine(subCatPart, 1);

      catPart.newPage();
    }

    // now add all this to the document
    document.add(catPart);
  }
示例#23
0
  /**
   * Extended headers / footers example
   *
   * @param args Unused
   */
  public static void main(String[] args) {
    System.out.println("Demonstrates use of the RtfHeaderFooter for extended headers and footers");
    try {
      Document document = new Document();
      RtfWriter2.getInstance(document, new FileOutputStream("ExtendedHeaderFooter.rtf"));

      // Create the Paragraphs that will be used in the header.
      Paragraph date = new Paragraph("01.01.2010");
      date.setAlignment(Paragraph.ALIGN_RIGHT);
      Paragraph address = new Paragraph("TheFirm\nTheRoad 24, TheCity\n" + "+00 99 11 22 33 44");

      // Create the RtfHeaderFooter with an array containing the Paragraphs to add
      RtfHeaderFooter header = new RtfHeaderFooter(new Element[] {date, address});

      // Set the header
      document.setHeader(header);

      // Create the table that will be used as the footer
      Table footer = new Table(2);
      footer.setBorder(0);
      footer.getDefaultCell().setBorder(0);
      footer.setWidth(100);
      footer.addCell(new Cell("(c) Mark Hall"));
      Paragraph pageNumber = new Paragraph("Page ");

      // The RtfPageNumber is an RTF specific element that adds a page number field
      pageNumber.add(new RtfPageNumber());
      pageNumber.setAlignment(Paragraph.ALIGN_RIGHT);
      footer.addCell(new Cell(pageNumber));

      // Create the RtfHeaderFooter and set it as the footer to use
      document.setFooter(new RtfHeaderFooter(footer));

      document.open();

      document.add(
          new Paragraph(
              "This document has headers and footers created"
                  + " using the RtfHeaderFooter class."));

      document.close();
    } catch (FileNotFoundException fnfe) {
      fnfe.printStackTrace();
    } catch (DocumentException de) {
      de.printStackTrace();
    }
  }
示例#24
0
 protected void printFooter() throws DocumentException {
   out("");
   out(
       renderEnd(
           renderMiddle("", "Page " + (iPageNo + 1)),
           "<"
               + iCurrentSubjectArea.getSubjectAreaAbbreviation()
               + (iCourseNumber != null ? " " + iCourseNumber : "")
               + ">  "));
   // FIXME: For some reason when a line starts with space, the line is shifted by one space in the
   // resulting PDF (when using iText 5.0.2)
   Paragraph p = new Paragraph(iBuffer.toString().replace("\n ", "\n  "), PdfFont.getFixedFont());
   p.setLeading(9.5f); // was 13.5f
   iDoc.add(p);
   iBuffer = new StringBuffer();
   iPageNo++;
 }
  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));
  }
示例#26
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);
 }
示例#27
0
  private static void addTitlePage(Document document) throws DocumentException {
    Paragraph preface = new Paragraph();
    // We add one empty line
    addEmptyLine(preface, 1);
    // Lets write a big header
    preface.add(new Paragraph("Eventi selezionati", catFont));

    addEmptyLine(preface, 1);
    // Will create: Report generated by: _name, _date
    preface.add(
        new Paragraph(
            "Report generated by: Govpay, " + new Date(), // $NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
            smallBold));
    addEmptyLine(preface, 3);
    preface.add(
        new Paragraph(
            "Il report contiene gli eventi selezionati per l'export nella console Govpay.",
            smallBold));

    document.add(preface);
  }
示例#28
0
文件: pdf.java 项目: darsh56/jb
  public void pv() {
    try {

      Document document = new Document(PageSize.A4, 36, 72, 108, 180);
      PdfWriter.getInstance(document, new FileOutputStream("pdfFile.pdf"));

      File f = new File("abc.txt");
      FileReader fr = new FileReader(f);
      BufferedReader br = new BufferedReader(fr);
      String i;
      while ((i = br.readLine()) != null) {

        document.open();
        document.add(new Paragraph(i));
      }
      System.out.println("fetched database  is inserted into pdf file");

      document.close();
    } catch (Exception e) {
    }
  }
 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);
 }
  /**
   * @see org.kuali.kfs.module.bc.service.PayrateImportService#generatePdf(java.lang.StringBuilder,
   *     java.io.ByteArrayOutputStream)
   */
  @NonTransactional
  public void generatePdf(List<ExternalizedMessageWrapper> logMessages, ByteArrayOutputStream baos)
      throws DocumentException {
    Document document = new Document();
    PdfWriter.getInstance(document, baos);
    document.open();
    for (ExternalizedMessageWrapper messageWrapper : logMessages) {
      String message;
      if (messageWrapper.getParams().length == 0)
        message =
            SpringContext.getBean(KualiConfigurationService.class)
                .getPropertyString(messageWrapper.getMessageKey());
      else {
        String temp =
            SpringContext.getBean(KualiConfigurationService.class)
                .getPropertyString(messageWrapper.getMessageKey());
        message = MessageFormat.format(temp, (Object[]) messageWrapper.getParams());
      }
      document.add(new Paragraph(message));
    }

    document.close();
  }