예제 #1
0
 private void exportGraphToPdf(mxGraph graph, String filename) {
   Rectangle bounds =
       new Rectangle(trackScheme.getGUI().graphComponent.getViewport().getViewSize());
   // step 1
   com.itextpdf.text.Rectangle pageSize =
       new com.itextpdf.text.Rectangle(bounds.x, bounds.y, bounds.width, bounds.height);
   com.itextpdf.text.Document document = new com.itextpdf.text.Document(pageSize);
   // step 2
   PdfWriter writer = null;
   Graphics2D g2 = null;
   try {
     writer = PdfWriter.getInstance(document, new FileOutputStream(filename));
     // step 3
     document.open();
     // step 4
     PdfContentByte canvas = writer.getDirectContent();
     g2 = canvas.createGraphics(pageSize.getWidth(), pageSize.getHeight());
     trackScheme.getGUI().graphComponent.getViewport().paintComponents(g2);
   } catch (FileNotFoundException e) {
     e.printStackTrace();
   } catch (DocumentException e) {
     e.printStackTrace();
   } finally {
     g2.dispose();
     document.close();
   }
 }
예제 #2
0
 private void startNewPage() {
   if (document.isOpen()) {
     document.newPage();
   } else {
     document.open();
   }
 }
예제 #3
0
 /**
  * Converts the given txt file to pdf. It writes the result into the file by the name given in the
  * outputFileName variable.
  *
  * @param inputFileName the name of a text file to convert to PDF
  * @param encoding used by the file
  * @param outputFontName for Polish files recommended is to use "lucon.ttf"
  * @param fontSize the size of font to use in the pdf
  * @param isLandscapeMode if true the pdf pages will be in landscape otherwise they are in
  *     portrait
  * @param outputFileName the name of a pdf file to convert to
  * @throws DocumentException
  * @throws IOException
  */
 public static void convertTextToPDFFile(
     String inputFileName,
     String encoding,
     String outputFontName,
     float fontSize,
     boolean isLandscapeMode,
     String outputFileName)
     throws DocumentException, IOException {
   String fileContent = ReadWriteTextFileWithEncoding.read(inputFileName, encoding);
   //		fileContent = fileContent.replaceAll("\t", tabAsSpaces);
   //	System.out.println("??? czy zawiera ten char ("+newPageChar+") -1 znaczy brak="+
   //		fileContent.indexOf(newPageChar));
   //	System.out.println("fileContent="+fileContent);
   Rectangle pageSize = PageSize.A4;
   if (isLandscapeMode) pageSize = PageSize.A4.rotate();
   Document document = new Document(pageSize);
   // we'll create the file in memory
   ByteArrayOutputStream baos = new ByteArrayOutputStream();
   PdfWriter.getInstance(document, baos);
   document.open();
   // stworz czcionke kompatibilna z polskimi literami/kodowaniem
   BaseFont bf = BaseFont.createFont(outputFontName, encoding, BaseFont.EMBEDDED);
   Font font = new Font(bf, fontSize);
   Paragraph par = new Paragraph(fileContent, font);
   document.add(par);
   document.close();
   // let's write the file in memory to a file anyway
   FileOutputStream fos = new FileOutputStream(outputFileName);
   fos.write(baos.toByteArray());
   fos.close();
   System.out.println("Convertion finished, result stored in file '" + outputFileName + "'");
 }
예제 #4
0
  public byte[] generaArcSol(
      final List<VUSolicitud> listSolic, final String titulo, final String firmaDigital)
      throws VUException {

    final Document document = new Document(PageSize.A4, 10, 10, 10, 70);
    final ByteArrayOutputStream bOutput = new ByteArrayOutputStream();
    try {
      final PdfWriter writer = PdfWriter.getInstance(document, bOutput);

      final HeaderFooter event =
          new HeaderFooter(this.footer(), filesBean.getFileSctImg().getURL().getPath(), titulo);
      writer.setPageEvent(event);

      document.open();
      document.add(new Paragraph(" "));
      document.add(this.cuerpoSol(listSolic));

      final PdfPTable tabPDF = getTablaPDF(firmaDigital);
      document.add(tabPDF);
    } catch (Exception expo) {
      LOGVU.error("ERRROR al generar PDF", expo);
    } finally {
      if (null != document) {
        document.close();
      }
    }
    return bOutput.toByteArray();
  }
예제 #5
0
  public static void main(String[] args) {
    try {

      // Step 1: Init document
      Document document = new Document();

      // Step 2: Init pdf file
      String file = "Pdf.pdf"; // Default will 'pdf' project folder
      PdfWriter.getInstance(document, new FileOutputStream(file));

      // Step 3: Open document
      document.open();

      // Step 4: Add connent

      Paragraph paragraph = new Paragraph("This is content");
      document.add(paragraph);

      // ...

      // Step 5: Close document
      document.close();

      System.out.println("OK");

    } catch (Exception e) {

      e.printStackTrace();
    }
  }
예제 #6
0
 /**
  * Creates a PDF document.
  *
  * @param filename the path to the new PDF document
  * @throws DocumentException
  * @throws IOException
  */
 public void createPdf(String filename) throws IOException, DocumentException {
   // step 1
   Document document = new Document(new Rectangle(360, 360));
   // step 2
   PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(filename));
   // step 3
   document.open();
   writer.addJavaScript(Utilities.readFileToString(RESOURCE));
   // step 4
   // add the keys for the digits
   for (int i = 0; i < 10; i++) {
     addPushButton(writer, digits[i], String.valueOf(i), "this.augment(" + i + ")");
   }
   // add the keys for the operators
   addPushButton(writer, plus, "+", "this.register('+')");
   addPushButton(writer, minus, "-", "this.register('-')");
   addPushButton(writer, mult, "x", "this.register('*')");
   addPushButton(writer, div, ":", "this.register('/')");
   addPushButton(writer, equals, "=", "this.calculateResult()");
   // add the other keys
   addPushButton(writer, clearEntry, "CE", "this.reset(false)");
   addPushButton(writer, clear, "C", "this.reset(true)");
   addTextField(writer, result, "result");
   addTextField(writer, move, "move");
   // step 5
   document.close();
 }
예제 #7
0
 public Document createdocument(String filename) throws FileNotFoundException, DocumentException {
   Rectangle pagesize = new Rectangle(1650f, 800f);
   Document document = new Document(pagesize);
   PdfWriter.getInstance(document, new FileOutputStream(filename));
   document.open();
   return document;
 }
예제 #8
0
  public static void main(String[] args) {
    Document document = new Document();
    try {
      PdfWriter.getInstance(document, new FileOutputStream("ImageRotation.pdf"));
      document.open();

      //
      // Rotate image in radian using the setRotation method.
      //
      String filename = "other-sample/src/main/resources/java.gif";
      Image image = Image.getInstance(filename);
      image.setRotation(90f);
      document.add(image);

      //
      // Rotate image in degree using the setRotationDegree method
      //
      String url = "http://localhost/xampp/img/xampp-logo-new.gif";
      image = Image.getInstance(url);
      image.setRotationDegrees(90);
      document.add(image);
    } catch (DocumentException | IOException e) {
      e.printStackTrace();
    } finally {
      document.close();
    }
  }
 private static void concatPDFs(List<String> pdfs, OutputStream outputStream, String tempDiv) {
   ByteArrayOutputStream byteStream = null;
   Document document = new Document();
   try {
     PdfCopy copy = new PdfCopy(document, outputStream);
     document.open();
     for (String pdf : pdfs) {
       String fileLocation = tempDiv + pdf;
       InputStream templateIs = new FileInputStream(fileLocation);
       PdfReader reader = new PdfReader(templateIs);
       byteStream = new ByteArrayOutputStream();
       PdfStamper stamper = new PdfStamper(reader, byteStream);
       stamper.setFreeTextFlattening(true);
       stamper.setFormFlattening(true);
       stamper.close();
       PdfReader pdfReader = new PdfReader(byteStream.toByteArray());
       for (int page = 0; page < pdfReader.getNumberOfPages(); ) {
         copy.addPage(copy.getImportedPage(pdfReader, ++page));
       }
       pdfReader.close();
       reader.close();
     }
     document.close();
     copy.close();
   } catch (Exception e) {
     logger.error(e, e);
   } finally {
     if (document.isOpen()) document.close();
     try {
       if (outputStream != null) outputStream.close();
     } catch (IOException ioe) {
       logger.error(ioe, ioe);
     }
   }
 }
예제 #10
0
  private static void merge(String output, Collection<Path> all) {

    try {
      Document document = new Document();

      PdfCopy copy = new PdfCopy(document, new FileOutputStream(output));
      document.open();

      PdfReader reader;
      int n;

      for (Path pathTemp : all) {

        if (pathTemp.toFile().getAbsolutePath().endsWith(".pdf")) {

          reader = new PdfReader(pathTemp.toFile().getAbsolutePath());

          n = reader.getNumberOfPages();
          for (int page = 0; page < n; ) {
            copy.addPage(copy.getImportedPage(reader, ++page));
          }
          copy.freeReader(reader);
          reader.close();
        }
      }
      document.close();

    } catch (Exception e) {
      System.out.println(e);
    }
  }
예제 #11
0
 public static void main(String[] args) throws IOException, DocumentException {
   Document document = new Document();
   PdfWriter.getInstance(document, new FileOutputStream("results/simple_rowspan_colspan.pdf"));
   document.open();
   PdfPTable table = new PdfPTable(5);
   table.setWidths(new int[] {1, 2, 2, 2, 1});
   PdfPCell cell;
   cell = new PdfPCell(new Phrase("S/N"));
   cell.setRowspan(2);
   table.addCell(cell);
   cell = new PdfPCell(new Phrase("Name"));
   cell.setColspan(3);
   table.addCell(cell);
   cell = new PdfPCell(new Phrase("Age"));
   cell.setRowspan(2);
   table.addCell(cell);
   table.addCell("SURNAME");
   table.addCell("FIRST NAME");
   table.addCell("MIDDLE NAME");
   table.addCell("1");
   table.addCell("James");
   table.addCell("Fish");
   table.addCell("Stone");
   table.addCell("17");
   document.add(table);
   document.close();
 }
예제 #12
0
  /** Generates a PDF with the list of registered members in the event. */
  public void print() {
    FacesContext context = FacesContext.getCurrentInstance();
    HttpServletResponse response = (HttpServletResponse) context.getExternalContext().getResponse();
    response.setContentType("application/pdf");
    response.setHeader("Content-disposition", "inline=filename=file.pdf");

    try {
      Document document = new Document();
      ByteArrayOutputStream baos = new ByteArrayOutputStream();
      PdfWriter.getInstance(document, baos);
      document.open();

      EventAttendeeReport eventAttendeeReport = new EventAttendeeReport(document);
      eventAttendeeReport.printReport(this.attendees);

      document.close();

      response.getOutputStream().write(baos.toByteArray());
      response.getOutputStream().flush();
      response.getOutputStream().close();
      context.responseComplete();
    } catch (IOException | DocumentException e) {
      LOGGER.log(Level.SEVERE, e.getMessage(), e);
    }
  }
예제 #13
0
 /**
  * Method to export charts as PDF files using the defined path.
  *
  * @param path The filename and absolute path.
  * @param chart The JFreeChart object.
  * @param width The width of the PDF file.
  * @param height The height of the PDF file.
  * @param mapper The font mapper for the PDF file.
  * @param title The title of the PDF file.
  * @throws IOException If writing a PDF file fails.
  */
 @SuppressWarnings("deprecation")
 public static void exportPdf(
     String path, JFreeChart chart, int width, int height, FontMapper mapper, String title)
     throws IOException {
   File file = new File(path);
   FileOutputStream pdfStream = new FileOutputStream(file);
   BufferedOutputStream pdfOutput = new BufferedOutputStream(pdfStream);
   Rectangle pagesize = new Rectangle(width, height);
   Document document = new Document();
   document.setPageSize(pagesize);
   document.setMargins(50, 50, 50, 50);
   document.addAuthor("OMSimulationTool");
   document.addSubject(title);
   try {
     PdfWriter pdfWriter = PdfWriter.getInstance(document, pdfOutput);
     document.open();
     PdfContentByte contentByte = pdfWriter.getDirectContent();
     PdfTemplate template = contentByte.createTemplate(width, height);
     Graphics2D g2D = template.createGraphics(width, height, mapper);
     Double r2D = new Rectangle2D.Double(0, 0, width, height);
     chart.draw(g2D, r2D);
     g2D.dispose();
     contentByte.addTemplate(template, 0, 0);
   } catch (DocumentException de) {
     JOptionPane.showMessageDialog(
         null,
         "Failed to write PDF document.\n" + de.getMessage(),
         "Failed",
         JOptionPane.ERROR_MESSAGE);
     de.printStackTrace();
   }
   document.close();
 }
 /**
  * Creates a PDF file: hello_mirrored_margins.pdf
  *
  * @param args no arguments needed
  */
 public static void main(String[] args) throws DocumentException, IOException {
   // step 1
   Document document = new Document();
   // step 2
   PdfWriter.getInstance(document, new FileOutputStream(RESULT));
   // setting page size, margins and mirrered margins
   document.setPageSize(PageSize.A5);
   document.setMargins(36, 72, 108, 180);
   document.setMarginMirroringTopBottom(true);
   // step 3
   document.open();
   // step 4
   document.add(
       new Paragraph(
           "The left margin of this odd page is 36pt (0.5 inch); "
               + "the right margin 72pt (1 inch); "
               + "the top margin 108pt (1.5 inch); "
               + "the bottom margin 180pt (2.5 inch)."));
   Paragraph paragraph = new Paragraph();
   paragraph.setAlignment(Element.ALIGN_JUSTIFIED);
   for (int i = 0; i < 20; i++) {
     paragraph.add(
         "Hello World! Hello People! " + "Hello Sky! Hello Sun! Hello Moon! Hello Stars!");
   }
   document.add(paragraph);
   document.add(new Paragraph("The top margin 180pt (2.5 inch)."));
   // step 5
   document.close();
 }
예제 #15
0
  public static void exportImg() {
    Document document = null;
    try {
      //            BaseFont bfChinese = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H",
      // BaseFont.NOT_EMBEDDED);// 设置中文字体
      //            Font headFont = new Font(bfChinese, 10, Font.NORMAL);// 设置字体大小

      document = new Document();
      PdfWriter.getInstance(document, new FileOutputStream("D:/test/img.pdf"));
      // 设定文档的作者
      document.addAuthor("林计钦"); // 测试无效
      document.open();
      document.add(new Paragraph("你好,Img!"));
      // 读取一个图片
      Image image = Image.getInstance("D:/test/1.jpg");
      // 插入一个图片
      document.add(image);
    } catch (FileNotFoundException e) {
      e.printStackTrace();
    } catch (DocumentException e) {
      e.printStackTrace();
    } catch (MalformedURLException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    } finally {
      if (document != null) {
        document.close();
      }
    }
  }
예제 #16
0
  private static void booklet(String input) throws Exception {
    String output = input.replace(".pdf", "-booklet.pdf");
    PdfReader reader = new PdfReader(input);
    int n = reader.getNumberOfPages();
    Rectangle pageSize = reader.getPageSize(1);

    System.out.println("Input page size: " + pageSize);
    Document doc = new Document(PageSize.A4.rotate(), 0, 0, 0, 0);
    PdfWriter writer = PdfWriter.getInstance(doc, new FileOutputStream(output));
    doc.open();
    splitLine(doc, writer);
    int[] pages = new int[(n + 3) / 4 * 4];
    int x = 1, y = pages.length;
    for (int i = 0; i < pages.length; ) {
      pages[i++] = y--;
      pages[i++] = x++;
      pages[i++] = x++;
      pages[i++] = y--;
    }
    PdfContentByte cb = writer.getDirectContent();
    float bottom = (doc.top() - pageSize.getHeight()) / 2 + kOffset;
    float left = doc.right() / 2 - (pageSize.getWidth() + kTextWidth) / 2 - kMargin;
    float right = doc.right() / 2 - (pageSize.getWidth() - kTextWidth) / 2 + kMargin;

    for (int i = 0; i < pages.length; ) {
      PdfImportedPage page = getPage(writer, reader, pages[i++]);
      if (page != null) cb.addTemplate(page, left, bottom);

      page = getPage(writer, reader, pages[i++]);
      if (page != null) cb.addTemplate(page, right, bottom);

      doc.newPage();
    }
    doc.close();
  }
예제 #17
0
  /**
   * Creates a PDF document.
   *
   * @param filename the path to the new PDF document
   * @throws DocumentException
   * @throws IOException
   */
  public void createPdf(String filename) throws IOException, DocumentException {
    // step 1
    Rectangle rect = new Rectangle(-595, -842, 595, 842);
    Document document = new Document(rect);
    // step 2
    PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(filename));
    // step 3
    document.open();
    // step 4
    // draw the coordinate system
    PdfContentByte canvas = writer.getDirectContent();
    canvas.moveTo(-595, 0);
    canvas.lineTo(595, 0);
    canvas.moveTo(0, -842);
    canvas.lineTo(0, 842);
    canvas.stroke();

    // read the PDF with the logo
    PdfReader reader = new PdfReader(RESOURCE);
    PdfTemplate template = writer.getImportedPage(reader, 1);
    // add it at different positions using different transformations
    canvas.addTemplate(template, 0, 0);
    canvas.addTemplate(template, 0.5f, 0, 0, 0.5f, -595, 0);
    canvas.addTemplate(template, 0.5f, 0, 0, 0.5f, -297.5f, 297.5f);
    canvas.addTemplate(template, 1, 0, 0.4f, 1, -750, -650);
    canvas.addTemplate(template, 0, -1, -1, 0, 650, 0);
    canvas.addTemplate(template, 0, -0.2f, -0.5f, 0, 350, 0);
    // step 5
    document.close();
    reader.close();
  }
예제 #18
0
  @Override
  public byte[] buildReportFromFiche(Fiche fiche) throws DocumentException {

    logger.debug("Début méthode exportation PDF");

    if (fiche.getAdresse() == null) {
      throw new BusinessException(
          "Impossible d'imprimer cette fiche : L'adresse n'est pas remplie.");
    }

    ByteArrayOutputStream bstream = new ByteArrayOutputStream();

    logger.debug("Génération du PDF");

    Document document = new Document();
    PdfWriter.getInstance(document, bstream);
    document = buildMetadata(document, fiche);

    document.open();
    document.add(buildHeader(fiche));
    document.add(buildInfos(fiche));
    document.add(buildSaisine(fiche));
    document.add(buildExpose(fiche));
    document.add(buildPersonnes(fiche));
    document.add(buildProcedures(fiche));

    document.close();

    logger.debug("Fin de génération");

    return bstream.toByteArray();
  }
예제 #19
0
  public static void main(String[] args) throws IOException, DocumentException {
    GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
    String[] fontFamily = ge.getAvailableFontFamilyNames();
    PrintStream out1 = new PrintStream(new FileOutputStream(RESULT1));
    for (int i = 0; i < fontFamily.length; i++) {
      out1.println(fontFamily[i]);
    }
    out1.flush();
    out1.close();

    DefaultFontMapper mapper = new DefaultFontMapper();
    mapper.insertDirectory("c:/windows/fonts/");
    PrintStream out2 = new PrintStream(new FileOutputStream(RESULT2));
    for (Entry<String, BaseFontParameters> entry : mapper.getMapper().entrySet()) {
      out2.println(String.format("%s: %s", entry.getKey(), entry.getValue().fontName));
    }
    out2.flush();
    out2.close();

    float width = 150;
    float height = 150;
    Document document = new Document(new Rectangle(width, height));
    PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(RESULT3));
    document.open();
    PdfContentByte cb = writer.getDirectContent();
    Graphics2D g2d = cb.createGraphics(width, height, mapper);
    for (int i = 0; i < FONTS.length; ) {
      g2d.setFont(FONTS[i++]);
      g2d.drawString("Hello world", 5, 24 * i);
    }
    g2d.dispose();
    document.close();
  }
예제 #20
0
  public static void main(String[] args) throws FileNotFoundException, DocumentException {
    Document document = new Document();
    @SuppressWarnings("unused")
    PdfWriter pdfWriter = PdfWriter.getInstance(document, new FileOutputStream("HelloWorld.pdf"));
    document.open();

    Paragraph paragraph1 = new Paragraph("This is Paragraph 1");
    Paragraph paragraph2 = new Paragraph("This is Paragraph 2");
    paragraph1.setIndentationLeft(80);
    paragraph1.setIndentationRight(80);
    paragraph1.setAlignment(Element.ALIGN_CENTER);
    paragraph1.setSpacingAfter(15);
    paragraph2.setSpacingBefore(15);
    paragraph2.setAlignment(Element.ALIGN_LEFT);
    Phrase phrase = new Phrase("This is a large sentence.");
    for (int count = 0; count < 10; count++) {
      paragraph1.add(phrase);
      paragraph2.add(phrase);
    }

    document.add(paragraph1);
    document.add(paragraph2);

    document.close();
  }
예제 #21
0
  public static ByteArrayOutputStream requestsToPdf(
      String globalTitle, Date generationDate, ScrambleRequest[] scrambleRequests, String password)
      throws DocumentException, IOException {
    Document doc = new Document();
    ByteArrayOutputStream totalPdfOutput = new ByteArrayOutputStream();
    PdfSmartCopy totalPdfWriter = new PdfSmartCopy(doc, totalPdfOutput);
    if (password != null) {
      totalPdfWriter.setEncryption(
          password.getBytes(),
          password.getBytes(),
          PdfWriter.ALLOW_PRINTING,
          PdfWriter.STANDARD_ENCRYPTION_128);
    }

    doc.open();

    PdfContentByte cb = totalPdfWriter.getDirectContent();
    PdfOutline root = cb.getRootOutline();

    HashMap<String, PdfOutline> outlineByPuzzle = new HashMap<String, PdfOutline>();
    boolean expandPuzzleLinks = false;

    int pages = 1;
    for (int i = 0; i < scrambleRequests.length; i++) {
      ScrambleRequest scrambleRequest = scrambleRequests[i];

      String shortName = scrambleRequest.scrambler.getShortName();

      PdfOutline puzzleLink = outlineByPuzzle.get(shortName);
      if (puzzleLink == null) {
        PdfDestination d = new PdfDestination(PdfDestination.FIT);
        puzzleLink =
            new PdfOutline(
                root,
                PdfAction.gotoLocalPage(pages, d, totalPdfWriter),
                scrambleRequest.scrambler.getLongName(),
                expandPuzzleLinks);
        outlineByPuzzle.put(shortName, puzzleLink);
      }

      PdfDestination d = new PdfDestination(PdfDestination.FIT);
      new PdfOutline(
          puzzleLink, PdfAction.gotoLocalPage(pages, d, totalPdfWriter), scrambleRequest.title);

      PdfReader pdfReader = createPdf(globalTitle, generationDate, scrambleRequest);
      for (int j = 0; j < scrambleRequest.copies; j++) {
        for (int pageN = 1; pageN <= pdfReader.getNumberOfPages(); pageN++) {
          PdfImportedPage page = totalPdfWriter.getImportedPage(pdfReader, pageN);
          totalPdfWriter.addPage(page);
          pages++;
        }
      }
    }

    doc.close();
    return totalPdfOutput;
  }
예제 #22
0
  public void print(String filename) throws IOException, DocumentException {
    EventTree tree = app.getTimelines().getCurrentTree();
    if (tree == null || tree.isEmpty()) return;

    ComplexEvent parent = tree.getTopSelectionParent();
    if (parent == null) return;

    // Instantiation of document object
    Document document = new Document(PageSize.A4, 50, 50, 50, 50);

    // Creation of PdfWriter object
    PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(filename));
    document.open();

    // Creation of table
    Paragraph title =
        new Paragraph(
            "A sample output from Zeitline:",
            FontFactory.getFont(FontFactory.TIMES_BOLD, 14, BaseColor.BLUE));
    title.setSpacingAfter(20);
    document.add(title);

    // Setting width rations
    PdfPTable table = new PdfPTable(3);
    float[] tableWidth = {(float) 0.2, (float) 0.12, (float) 0.68};
    table.setWidths(tableWidth);

    // Setting the header
    java.util.List<PdfPCell> headerCells =
        asList(getHeaderCell("Date"), getHeaderCell("MACB"), getHeaderCell("Short Description"));

    for (PdfPCell cell : headerCells) table.addCell(cell);

    // Setting the body
    int max = parent.countChildren();
    for (int i = 0; i < max; i++) {
      AbstractTimeEvent entry = parent.getEventByIndex(i);
      table.addCell(getBodyCell(entry.getStartTime().toString()));

      String name = entry.getName();
      if (name != null && name.length() > 5) {
        String macb = name.substring(0, 4);
        String desc = name.substring(5);

        table.addCell(getBodyCell(macb));
        table.addCell(getBodyCell(desc));
      } else {
        table.addCell("");
        table.addCell("");
      }
    }
    document.add(table);

    // Closure
    document.close();
    writer.close();
  }
예제 #23
0
파일: PDFGen.java 프로젝트: bretanac93/PDF
  public static void PDF(String DirPath, String FileName, String Text, Font fonts)
      throws FileNotFoundException, DocumentException {
    FileOutputStream Dir = new FileOutputStream(DirPath + FileName);
    Document doc = new Document();
    PdfWriter.getInstance(doc, Dir);

    doc.open();
    doc.add(new Paragraph(Text, fonts));
    doc.close();
  }
예제 #24
0
 public void createPdf2(String src) throws IOException, DocumentException {
   // second document (with a link to the first one)
   Document document2 = new Document();
   PdfWriter.getInstance(document2, new FileOutputStream(src));
   document2.open();
   Chunk chunk = new Chunk("Link");
   chunk.setAction(new PdfAction("subdir/abc2.pdf", 6));
   document2.add(chunk);
   document2.close();
 }
  @Override
  protected void buildPdfDocument(
      Map<String, Object> model,
      Document doc,
      PdfWriter writer,
      HttpServletRequest request,
      HttpServletResponse response)
      throws Exception {
    // TODO Auto-generated method stub

    @SuppressWarnings("unchecked")
    ArrayList<ctUsuario> listaUsuario = (ArrayList<ctUsuario>) model.get("listaUsuario");
    // grupo = (String)model.get("grupo");

    PdfPTable tablaPDF = new PdfPTable(11); // 11 columns.
    Font fuenteTabla = new Font(Font.FontFamily.UNDEFINED, 12, Font.BOLD);
    Font fuenteCelda = new Font(Font.FontFamily.UNDEFINED, 11);

    tablaPDF.addCell(new Phrase("Nombre", fuenteTabla));
    tablaPDF.addCell(new Phrase("Apellido", fuenteTabla));
    tablaPDF.addCell(new Phrase("Fecha De Nacimiento", fuenteTabla));
    tablaPDF.addCell(new Phrase("Calle", fuenteTabla));
    tablaPDF.addCell(new Phrase("Num. Ext", fuenteTabla));
    tablaPDF.addCell(new Phrase("Num. Int", fuenteTabla));
    tablaPDF.addCell(new Phrase("Colonia", fuenteTabla));
    tablaPDF.addCell(new Phrase("CP", fuenteTabla));
    tablaPDF.addCell(new Phrase("Municipio", fuenteTabla));
    tablaPDF.addCell(new Phrase("Estado", fuenteTabla));
    tablaPDF.addCell(new Phrase("Telefono", fuenteTabla));

    for (ctUsuario ctUsuario : listaUsuario) {
      tablaPDF.addCell(new Phrase(ctUsuario.getcNombre(), fuenteCelda));
      tablaPDF.addCell(new Phrase(ctUsuario.getcApellidos(), fuenteCelda));
      tablaPDF.addCell(new Phrase(ctUsuario.getDtFechaNac(), fuenteCelda));
      tablaPDF.addCell(new Phrase(ctUsuario.getcCalle(), fuenteCelda));
      tablaPDF.addCell(new Phrase(ctUsuario.getcNumExterior(), fuenteCelda));
      tablaPDF.addCell(new Phrase(ctUsuario.getcNumInterior(), fuenteCelda));
      tablaPDF.addCell(new Phrase(ctUsuario.getcColonia(), fuenteCelda));
      tablaPDF.addCell(new Phrase(ctUsuario.getcCP(), fuenteCelda));
      // tablaPDF.addCell(new Phrase(ctUsuario.getcMunicipio(), fuenteCelda));
      tablaPDF.addCell(new Phrase(ctUsuario.getcEstado(), fuenteCelda));
      // tablaPDF.addCell(new Phrase(ctUsuario.getcTel(), fuenteCelda));
    }

    tablaPDF.setWidthPercentage(100);
    Rectangle rect = new Rectangle(60, 30, 600, 800);
    writer.setBoxSize("art", rect);
    HeaderFooterPageEvent event = new HeaderFooterPageEvent();
    writer.setPageEvent(event);
    doc.setPageSize(PageSize.A4.rotate());
    doc.open();
    doc.add(tablaPDF);
    doc.close();
    pages = 0;
  }
예제 #26
0
  /**
   * @param file
   * @param txId
   * @throws DocumentException
   * @throws IOException
   */
  public void generatePdf(String file, ArrayList<String> docList)
      throws DocumentException, IOException {
    //  getReqdInfo(txId);
    document = new Document(PageSize.A4, 50, 50, 100, 650);
    writer = PdfWriter.getInstance(document, new FileOutputStream(file));
    writer.setPageEvent(agreementPdf);
    document.open();
    getTransactionHeader(docList);

    document.close();
  }
예제 #27
0
  private static void imageToPDF(String folder, Collection<Path> all) {

    for (Path path : all) {

      Document document = new Document();

      String absolutePathInput = path.toFile().getAbsolutePath();
      String absolutePathOutput = folder + "/" + path.getFileName() + ".pdf";

      if (absolutePathInput.endsWith(".gif")
          ||
          //
          absolutePathInput.endsWith(".GIF")
          ||
          //
          absolutePathInput.endsWith(".jpg")
          ||
          //
          absolutePathInput.endsWith(".JPG")
          ||
          //
          absolutePathInput.endsWith(".png")
          ||
          //
          absolutePathInput.endsWith(".PNG")) {

        try {
          FileOutputStream fos = new FileOutputStream(absolutePathOutput);
          PdfWriter writer = PdfWriter.getInstance(document, fos);
          writer.open();
          document.open();

          int indentation = 0;

          Image image = Image.getInstance(absolutePathInput);
          float scaler =
              ((document.getPageSize().getWidth()
                          - document.leftMargin()
                          - document.rightMargin()
                          - indentation)
                      / image.getWidth())
                  * 100;

          image.scalePercent(scaler);

          document.add(image);
          document.close();
          writer.close();
        } catch (Exception e) {
          e.printStackTrace();
        }
      }
    }
  }
 /** @see com.rainbow.billing.mbilling.common.reports.pdf.PDFReport#cretaePDF(java.lang.Object) */
 public InputStream cretaePDF(Object inputForPDFCreation) throws IOException, DocumentException {
   Document document = new Document();
   ByteArrayOutputStream baos = new ByteArrayOutputStream();
   PdfWriter.getInstance(document, baos);
   document.open();
   document.add(new Paragraph("Customer Search Result: genearted at" + new Date().toString()));
   document.add(Chunk.NEWLINE);
   document.add(addResults(inputForPDFCreation));
   document.close();
   InputStream inputStream = new ByteArrayInputStream(baos.toByteArray());
   return inputStream;
 }
 public void guardarUltimoGrafico(File filename, int anchoImagen, int altoImagen)
     throws DocumentException, FileNotFoundException, BadElementException, IOException {
   Document document = new Document();
   PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(filename));
   document.open();
   com.itextpdf.text.Image img =
       com.itextpdf.text.Image.getInstance(
           new ImageIcon(this.lastChart.createBufferedImage(anchoImagen, altoImagen)).getImage(),
           null);
   document.add(img);
   document.close();
 }
예제 #30
0
  /**
   * set values to writer
   *
   * @param writer
   * @throws Exception
   */
  protected void setValues(IExporter<?> exporter, FileOutputStream writer) throws Exception {

    if (exporter != null && writer != null) {

      String encoding = SettingsManager.getInstance().getValue(SettingProperty.ENCODING);
      BaseFont baseFont = BaseFont.createFont(BaseFont.HELVETICA, encoding, BaseFont.NOT_EMBEDDED);
      Font font = new Font(baseFont);

      List<String> properties = exporter.getProperties();
      Document document = new Document(PageSize.A4);

      // step 2
      PdfWriter.getInstance(document, writer);
      // step 3
      document.open();
      PdfPTable table = new PdfPTable(properties.size());

      table.setFooterRows(1);
      table.setWidthPercentage(100f);

      table.getDefaultCell().setColspan(1);

      table.getDefaultCell().setBackgroundColor(BaseColor.LIGHT_GRAY);

      for (String p : properties) {

        table.addCell(new Phrase(p, font));
      }

      //            table.setHeaderRows(1);
      table.getDefaultCell().setBackgroundColor(null);

      List<List<String>> values = ((IExporter<String>) exporter).getValues();

      String pValue;

      for (List<String> value : values) {

        for (String pv : value) {

          pValue = pv;

          if (pValue == null) {
            pValue = "";
          }
          table.addCell(new Phrase(pValue, font));
        }
      }

      document.add(table);
      document.close();
    }
  }