Пример #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 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();
  }
  /**
   * 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();
  }
 /**
  * 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();
 }
Пример #5
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();
  }
Пример #6
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();
  }
Пример #7
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();
      }
    }
  }
Пример #8
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();
  }
Пример #9
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();
    }
  }
Пример #10
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);
    }
  }
Пример #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
 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;
 }
Пример #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();
 }
Пример #14
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 + "'");
 }
Пример #15
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();
  }
Пример #16
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();
    }
  }
Пример #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
   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();
 }
Пример #18
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();
  }
Пример #19
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();
 }
Пример #20
0
  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();
  }
Пример #21
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();
        }
      }
    }
  }
Пример #22
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();
  }
Пример #23
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();
    }
  }
 /** @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();
 }
Пример #26
0
  public boolean convertToPDF() throws MalformedURLException, IOException {
    JFileChooser filechooser = new JFileChooser();
    FileNameExtensionFilter filter = new FileNameExtensionFilter(".pdf", "pdf");
    filechooser.setFileFilter(filter);
    int result = filechooser.showSaveDialog(this);
    if (result == JFileChooser.APPROVE_OPTION) {
      File saveFile = filechooser.getSelectedFile();
      Document pdfDocument = new Document();
      PdfPTable table = new PdfPTable(1);
      com.itextpdf.text.Rectangle r = new com.itextpdf.text.Rectangle(780, 580);
      Image slideImage = null;
      PdfWriter pdfWriter;
      try {
        pdfWriter =
            PdfWriter.getInstance(
                pdfDocument, new FileOutputStream(saveFile.getAbsolutePath() + ".pdf"));
        pdfWriter.open();
        pdfDocument.open();
        // pdfDocument.setPageSize(r);
        for (int i = 0; i < canvas.length; i++) {

          BufferedImage tempimg = new BufferedImage(720, 540, BufferedImage.TYPE_INT_ARGB);
          Graphics2D temgraphics = (Graphics2D) tempimg.getGraphics();
          temgraphics.setRenderingHint(
              RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
          temgraphics.drawImage(img[i], 0, 0, 720, 540, null);
          temgraphics.drawImage(canvas[i], 0, 0, 720, 540, null);
          // slideImage = Image.getInstance(img[i], null);
          slideImage = com.itextpdf.text.Image.getInstance(tempimg, null);
          // table.addCell(new PdfPCell(slideImage, true));
          // Image imagex = com.itextpdf.text.Image.getInstance("");
          pdfDocument.setPageSize(r);
          pdfDocument.newPage();
          pdfDocument.add(slideImage);
        }
        pdfDocument.close();
        pdfWriter.close();
        System.out.println("Powerpoint file converted to PDF successfully");
        return true;
      } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      } catch (DocumentException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      }

    } else {
      return false;
    }
    return false;
  }
Пример #27
0
 public void createPdf(String dest) throws IOException, DocumentException {
   Document document = new Document();
   PdfWriter.getInstance(document, new FileOutputStream(dest));
   document.open();
   Paragraph p = new Paragraph();
   String s =
       "all text is written in red, except the letters b and g; they are written in blue and green.";
   for (int i = 0; i < s.length(); i++) {
     p.add(returnCorrectColor(s.charAt(i)));
   }
   document.add(p);
   document.close();
 }
Пример #28
0
  public void generarPDFComprobante(Comprobante c) throws DocumentException, FileNotFoundException {
    Document documento = new Document();

    FileOutputStream archivoPDF;

    Calendar cal;
    cal = Calendar.getInstance();
    cal.setTime(c.getFecha());
    SimpleDateFormat d = new SimpleDateFormat("dd-MM-yyyy");
    String fecha = d.format(c.getFecha());

    String nombre =
        "./impresiones/comprobantes/comp" + c.getClaseLicencia().getNombre() + "_" + fecha + ".PDF";

    archivoPDF = new FileOutputStream(nombre);

    PdfWriter.getInstance(documento, archivoPDF).setInitialLeading(20);

    documento.open();

    PdfPTable tabla = new PdfPTable(2);

    tabla.getDefaultCell().setBorder(Rectangle.NO_BORDER);

    PdfPCell celda1 =
        new PdfPCell(
            new Phrase(
                "Nombre: "
                    + c.getTitular().getIdUsuario().getNombre()
                    + " "
                    + c.getTitular().getIdUsuario().getApellido()));
    celda1.setBorder(Rectangle.LEFT | Rectangle.TOP);

    PdfPCell celda2 = new PdfPCell(new Phrase("Clase: " + c.getClaseLicencia().getNombre()));
    celda2.setBorder(Rectangle.RIGHT | Rectangle.TOP);

    PdfPCell celda3 = new PdfPCell(new Phrase("Monto: $" + c.getMontoAbonado()));
    celda3.setBorder(Rectangle.LEFT | Rectangle.BOTTOM);

    PdfPCell celda4 = new PdfPCell(new Phrase("Fecha: " + fecha));
    celda4.setBorder(Rectangle.RIGHT | Rectangle.BOTTOM);

    tabla.addCell(celda1);
    tabla.addCell(celda2);
    tabla.addCell(celda3);
    tabla.addCell(celda4);

    documento.add(tabla);

    documento.close();
  }
Пример #29
0
 public void createPdf(String dest) throws IOException, DocumentException {
   Document document = new Document();
   PdfWriter.getInstance(document, new FileOutputStream(dest));
   document.open();
   PdfPTable table = new PdfPTable(8);
   PdfPCell cell = new PdfPCell(new Phrase("hi"));
   cell.setRowspan(2);
   table.addCell(cell);
   for (int aw = 0; aw < 14; aw++) {
     table.addCell("hi");
   }
   document.add(table);
   document.close();
 }
Пример #30
0
  private void generar(String nombreArchivo) {
    Document documento = new Document();
    try {
      PdfWriter.getInstance(documento, new FileOutputStream(nombreArchivo));
      documento.open();
      documento.add(new Paragraph(cabecera + mensaje));

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