/* (non-Javadoc)
   * @see de.offis.health.icardea.cied.pdf.interfaces.PDFExtractor#getPDFPages(int, int)
   */
  public byte[] getPDFPages(int fromPageNumber, int toPageNumber) {
    ByteArrayOutputStream byteArrayOutputStream = null;
    boolean extractionSuccessful = false;

    if (pdfReader != null) {
      int numberOfPages = getNumberOfPages();

      /*
       * Check if the given page numbers are in the allowed range.
       */
      if (fromPageNumber > 0
          && fromPageNumber <= numberOfPages
          && toPageNumber > 0
          && toPageNumber <= numberOfPages) {
        /*
         * Now check if the given fromPageNumber is smaller
         * as the given toPageNumber. If not swap the numbers.
         */
        if (fromPageNumber > toPageNumber) {
          int tmpPageNumber = toPageNumber;
          toPageNumber = fromPageNumber;
          fromPageNumber = tmpPageNumber;
        }

        Document newDocument = new Document();

        try {
          byteArrayOutputStream = new ByteArrayOutputStream();
          PdfSmartCopy pdfCopy = new PdfSmartCopy(newDocument, byteArrayOutputStream);
          newDocument.open();
          for (int currentPage = fromPageNumber; currentPage <= toPageNumber; currentPage++) {
            pdfCopy.addPage(pdfCopy.getImportedPage(pdfReader, currentPage));
          } // end for
          pdfCopy.flush();
          pdfCopy.close();
          newDocument.close();
          extractionSuccessful = true;
        } catch (DocumentException ex) {
          // TODO: Create an own exception for PDF processing errors.
          logger.error(
              "An exception occurred while extracting " + "pages from the input PDF file.", ex);
        } catch (IOException ex) {
          // TODO: Create an own exception for PDF processing errors.
          logger.error(
              "An exception occurred while extracting " + "pages from the input PDF file.", ex);
        } finally {
          if (!extractionSuccessful) {
            byteArrayOutputStream = null;
          }
        } // end try..catch..finally
      } // end if checking range of given pages
    } // end if (pdfReader != null)

    if (byteArrayOutputStream != null) {
      return byteArrayOutputStream.toByteArray();
    }
    return null;
  }
 /** @param fileName */
 public CompreWord(String fileName) {
   try {
     bfChinese = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
     FontChineseTitle = new Font(bfChinese, 14, Font.BOLD);
     FontChineseRow = new Font(bfChinese, 12, Font.NORMAL);
   } catch (DocumentException e) {
     log.error("", e);
   } catch (IOException e) {
     log.error("", e);
   }
   // step 1: creation of a document-object
   Rectangle pageSize = new Rectangle(PageSize.A4);
   document = new Document(pageSize);
   try {
     // step 2:
     // we create a writer that listens to the document
     // and directs a PDF-stream to a file
     RtfWriter2.getInstance(document, new FileOutputStream(fileName));
     document.open();
   } catch (IOException ioe) {
     log.error("", ioe);
   } catch (Exception e) {
     log.error("", e);
   }
 }
Exemple #3
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();
    }
  }
Exemple #4
0
  public void toPDFGraphicFile(File file, int width, int height) throws IOException {
    // otherwise toolbar appears
    plotToolBar.setVisible(false);

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

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

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

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

    document.close();
    // make it reappear
    plotToolBar.setVisible(true);
  }
  /**
   * 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();
    }
  }
  public void processLogicalPage(final LogicalPageKey key, final LogicalPageBox logicalPage)
      throws DocumentException {

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

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

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

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

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

    graphics.dispose();

    document.newPage();
  }
  public void beginDraw() {
    //    long t0 = System.currentTimeMillis();

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

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

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

      //      System.out.println("beginDraw fonts " + (System.currentTimeMillis() - t));
      g2 = content.createGraphics(width, height, getMapper());
      //      g2 = template.createGraphics(width, height, mapper);
    }
    //    System.out.println("beginDraw " + (System.currentTimeMillis() - t0));
    super.beginDraw();
  }
  @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);
  }
Exemple #9
0
 public static void main(String[] args) throws Exception {
   Document doc = new Document();
   PdfWriter.getInstance(doc, new FileOutputStream("htmlToPdfAuto.pdf"));
   doc.open();
   HtmlParser.parse(
       doc, new InputSource(HtmlToPdfAuto.class.getResourceAsStream("/htmlToPdfSaxAuto.html")));
   doc.close();
 }
  /**
   * 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();
  }
 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();
       }
     }
   }
   // }
 }
 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();
 }
Exemple #13
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();
  }
Exemple #14
0
  /**
   * Creates a document with some goto actions.
   *
   * @param args no arguments needed
   */
  public static void main(String[] args) {

    System.out.println("Destinations");

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

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

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

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

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

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

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

    // step 5: we close the document
    document.close();
  }
  public void preProcessPDF(Object document)
      throws IOException, BadElementException, DocumentException {
    Document pdf = (Document) document;
    pdf.open();
    pdf.setPageSize(PageSize.A4);

    ServletContext servletContext =
        (ServletContext) FacesContext.getCurrentInstance().getExternalContext().getContext();
    // String logo = servletContext.getRealPath("") + File.separator + "resources" + File.separator
    // + "demo" + File.separator + "images" + File.separator + "prime_logo.png";

    // pdf.add(Image.getInstance(logo));
  }
  public AbstractPDFGenerator(final OutputStream out, final String type) {
    this.out = out;
    try {
      if (type != null && "landscape".equalsIgnoreCase(type))
        document = new Document(PageSize.A4.rotate());
      else document = new Document();

      PdfWriter.getInstance(document, out);
      document.open();
    } catch (final Exception e) {
      throw new ApplicationRuntimeException("estimate.pdf.error", e);
    }
  }
Exemple #17
0
  /**
   * Creates a document.
   *
   * @param outputStream The output stream to write the document content.
   * @param pageSize the page size.
   * @return A Document.
   */
  public static Document openDocument(OutputStream outputStream, Rectangle pageSize) {
    try {
      Document document = new Document(pageSize);

      PdfWriter.getInstance(document, outputStream);

      document.open();

      return document;
    } catch (DocumentException ex) {
      throw new RuntimeException("Failed to open PDF document", ex);
    }
  }
  public void processPhysicalPage(
      final PageGrid pageGrid,
      final LogicalPageBox logicalPage,
      final int row,
      final int col,
      final PhysicalPageKey pageKey)
      throws DocumentException {
    final PhysicalPageBox page = pageGrid.getPage(row, col);
    if (page == null) {
      return;
    }

    final float width = (float) StrictGeomUtility.toExternalValue(page.getWidth());
    final float height = (float) StrictGeomUtility.toExternalValue(page.getHeight());

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

    final float marginLeft = (float) StrictGeomUtility.toExternalValue(page.getImageableX());
    final float marginRight =
        (float)
            StrictGeomUtility.toExternalValue(
                page.getWidth() - page.getImageableWidth() - page.getImageableX());
    final float marginTop = (float) StrictGeomUtility.toExternalValue(page.getImageableY());
    final float marginBottom =
        (float)
            StrictGeomUtility.toExternalValue(
                page.getHeight() - page.getImageableHeight() - page.getImageableY());

    final Document document = getDocument();
    document.setPageSize(pageSize);
    document.setMargins(marginLeft, marginRight, marginTop, marginBottom);

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

    final PdfContentByte directContent = writer.getDirectContent();
    final Graphics2D graphics = new PdfGraphics2D(directContent, width, height, metaData);
    final PdfLogicalPageDrawable logicalPageDrawable =
        new PdfLogicalPageDrawable(
            logicalPage, metaData, writer, page, resourceManager, imageCache, version);
    final PhysicalPageDrawable drawable = new PhysicalPageDrawable(logicalPageDrawable, page);
    drawable.draw(graphics, new Rectangle2D.Double(0, 0, width, height));

    graphics.dispose();

    document.newPage();
  }
Exemple #19
0
 /**
  * Opens the copier using the given reader and the given output version.
  *
  * @param reader
  * @param outputStream the output stream to write to.
  * @param version version for the created pdf copy, if null the version number is taken from the
  *     input {@link PdfReader}
  */
 void open(PdfReader reader, OutputStream outputStream, PdfVersion version) throws TaskException {
   try {
     pdfDocument = new Document(reader.getPageSizeWithRotation(1));
     pdfCopy = new PdfSmartCopy(pdfDocument, outputStream);
     if (version == null) {
       pdfCopy.setPdfVersion(reader.getPdfVersion());
     } else {
       pdfCopy.setPdfVersion(version.getVersionAsCharacter());
     }
     pdfDocument.addCreator(Sejda.CREATOR);
     pdfDocument.open();
   } catch (DocumentException e) {
     throw new TaskException("An error occurred opening the PdfSmartCopy.", e);
   }
 }
Exemple #20
0
 public void exportGraphic(Picture picture, OutputStream out) throws IOException {
   int width = picture.getPictureWidth();
   int height = picture.getPictureHeight();
   Document doc = new Document(new com.lowagie.text.Rectangle(width, height));
   try {
     PdfWriter pWriter = PdfWriter.getInstance(doc, out);
     doc.open();
     Graphics2D g = pWriter.getDirectContent().createGraphics(width, height);
     picture.paintPicture(g);
     g.dispose();
     doc.close();
   } catch (DocumentException e) {
     throw (IOException) new IOException(e.getMessage()).initCause(e);
   }
 }
  /**
   * 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();
    }
  }
 public void manipulatePdf(String src, String dest, int pow)
     throws IOException, DocumentException {
   PdfReader reader = new PdfReader(src);
   Rectangle pageSize = reader.getPageSize(1);
   Rectangle newSize =
       (pow % 2) == 0
           ? new Rectangle(pageSize.getWidth(), pageSize.getHeight())
           : new Rectangle(pageSize.getHeight(), pageSize.getWidth());
   Rectangle unitSize = new Rectangle(pageSize.getWidth(), pageSize.getHeight());
   for (int i = 0; i < pow; i++) {
     unitSize = new Rectangle(unitSize.getHeight() / 2, unitSize.getWidth());
   }
   int n = (int) Math.pow(2, pow);
   int r = (int) Math.pow(2, pow / 2);
   int c = n / r;
   Document document = new Document(newSize, 0, 0, 0, 0);
   PdfWriter writer =
       PdfWriter.getInstance(document, new FileOutputStream(String.format(dest, n)));
   document.open();
   PdfContentByte cb = writer.getDirectContent();
   PdfImportedPage page;
   Rectangle currentSize;
   float offsetX, offsetY, factor;
   int total = reader.getNumberOfPages();
   for (int i = 0; i < total; ) {
     if (i % n == 0) {
       document.newPage();
     }
     currentSize = reader.getPageSize(++i);
     factor =
         Math.min(
             unitSize.getWidth() / currentSize.getWidth(),
             unitSize.getHeight() / currentSize.getHeight());
     offsetX =
         unitSize.getWidth() * ((i % n) % c)
             + (unitSize.getWidth() - (currentSize.getWidth() * factor)) / 2f;
     offsetY =
         newSize.getHeight()
             - (unitSize.getHeight() * (((i % n) / c) + 1))
             + (unitSize.getHeight() - (currentSize.getHeight() * factor)) / 2f;
     page = writer.getImportedPage(reader, i);
     cb.addTemplate(page, factor, 0, 0, factor, offsetX, offsetY);
   }
   document.close();
 }
  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));
  }
Exemple #24
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);
 }
  @Before
  public void setUp() throws Exception {
    super.setUp();

    // Create some sample DataExplanationChunk data
    context = ExplanationChunk.ERROR;
    group = "group 1";
    rule = "rule 1";
    tags = new String[2];
    tags[0] = "tag1";
    tags[1] = "tag2";

    sdata = new SingleData(new Dimension("money", "EUR"), new Double(1700));

    ArrayList<Object> data = new ArrayList<Object>();
    data.add(new Double(1700));
    odata = new OneDimData(new Dimension("money", "EUR"), data);

    ArrayList<Tuple> data2 = new ArrayList<Tuple>();
    data2.add(new Tuple("1700", "1300"));
    twdata = new TwoDimData(new Dimension("money", "USD"), new Dimension("profit", "EUR"), data2);

    ArrayList<Triple> data3 = new ArrayList<Triple>();
    data3.add(new Triple("1700", "1300", "Male"));
    thdata =
        new ThreeDimData(
            new Dimension("money", "EUR"),
            new Dimension("profit", "USD"),
            new Dimension("gender"),
            data3);

    // Initialize a DataExplanationChunk with SingleData
    dchunk = new DataExplanationChunk(context, group, rule, tags, sdata);

    // Create an empty document instance, open it and attach a dummy document
    // event listener to it.
    doc = new Document();
    doc.open();
    docListener = new DummyDocListener();
    doc.addDocListener(docListener);

    // Initialize the builder
    instance = new PDFDataChunkBuilder();
  }
 private ByteArrayOutputStream getPdfData(
     JSONArray data, JSONArray res, HttpServletRequest request) throws ServiceException {
   ByteArrayOutputStream baos = new ByteArrayOutputStream();
   try {
     String[] colHeader = getColHeader();
     String[] colIndex = getColIndexes();
     String[] val = getColValues(colHeader, data);
     String[] resources = getResourcesColHeader(res, data);
     String[] mainHeader = {"Dates", "Duration", "Work", "Cost", "Tasks", "Resources"};
     Document document = null;
     if (landscape) {
       Rectangle recPage = new Rectangle(PageSize.A4.rotate());
       recPage.setBackgroundColor(new java.awt.Color(255, 255, 255));
       document = new Document(recPage, 15, 15, 30, 30);
     } else {
       Rectangle recPage = new Rectangle(PageSize.A4);
       recPage.setBackgroundColor(new java.awt.Color(255, 255, 255));
       document = new Document(recPage, 15, 15, 30, 30);
     }
     PdfWriter writer = PdfWriter.getInstance(document, baos);
     writer.setPageEvent(new EndPage());
     document.open();
     if (showLogo) {
       getCompanyDetails(request);
       addComponyLogo(document, request);
     }
     addTitleSubtitle(document);
     addTable(data, resources, colIndex, colHeader, mainHeader, val, document);
     document.close();
     writer.close();
     baos.close();
   } catch (ConfigurationException ex) {
     throw ServiceException.FAILURE("ExportProjectReport.getPdfData", ex);
   } catch (DocumentException ex) {
     throw ServiceException.FAILURE("ExportProjectReport.getPdfData", ex);
   } catch (JSONException e) {
     throw ServiceException.FAILURE("ExportProjectReport.getPdfData", e);
   } catch (IOException e) {
     throw ServiceException.FAILURE("ExportProjectReport.getPdfData", e);
   } catch (Exception e) {
     throw ServiceException.FAILURE("ExportProjectReport.getPdfData", e);
   }
   return baos;
 }
  public void 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);
  }
 /**
  * Writing vertical text.
  *
  * @param args no arguments needed
  */
 public static void main(String[] args) {
   Document document = new Document(PageSize.A4, 50, 50, 50, 50);
   try {
     texts[3] = convertCid(texts[0]);
     texts[4] = convertCid(texts[1]);
     texts[5] = convertCid(texts[2]);
     PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream("vertical.pdf"));
     int idx = 0;
     document.open();
     PdfContentByte cb = writer.getDirectContent();
     for (int j = 0; j < 2; ++j) {
       BaseFont bf = BaseFont.createFont("KozMinPro-Regular", encs[j], false);
       cb.setRGBColorStroke(255, 0, 0);
       cb.setLineWidth(0);
       float x = 400;
       float y = 700;
       float height = 400;
       float leading = 30;
       int maxLines = 6;
       for (int k = 0; k < maxLines; ++k) {
         cb.moveTo(x - k * leading, y);
         cb.lineTo(x - k * leading, y - height);
       }
       cb.rectangle(x, y, -leading * (maxLines - 1), -height);
       cb.stroke();
       int status;
       VerticalText vt = new VerticalText(cb);
       vt.setVerticalLayout(x, y, height, maxLines, leading);
       vt.addText(new Chunk(texts[idx++], new Font(bf, 20)));
       vt.addText(new Chunk(texts[idx++], new Font(bf, 20, 0, Color.blue)));
       status = vt.go();
       System.out.println(status);
       vt.setAlignment(Element.ALIGN_RIGHT);
       vt.addText(new Chunk(texts[idx++], new Font(bf, 20, 0, Color.orange)));
       status = vt.go();
       System.out.println(status);
       document.newPage();
     }
     document.close();
   } catch (Exception de) {
     de.printStackTrace();
   }
 }
  /** @see com.lowagie.toolbox.AbstractTool#execute() */
  public void execute() {
    try {
      if (getValue("odd") == null)
        throw new InstantiationException("You need to choose a sourcefile for the odd pages");
      File odd_file = (File) getValue("odd");
      if (getValue("even") == null)
        throw new InstantiationException("You need to choose a sourcefile for the even pages");
      File even_file = (File) getValue("even");
      if (getValue("destfile") == null)
        throw new InstantiationException("You need to choose a destination file");
      File pdf_file = (File) getValue("destfile");
      RandomAccessFileOrArray odd = new RandomAccessFileOrArray(odd_file.getAbsolutePath());
      RandomAccessFileOrArray even = new RandomAccessFileOrArray(even_file.getAbsolutePath());
      Image img = TiffImage.getTiffImage(odd, 1);
      Document document = new Document(new Rectangle(img.getScaledWidth(), img.getScaledHeight()));
      PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(pdf_file));
      document.open();
      PdfContentByte cb = writer.getDirectContent();
      int count = Math.max(TiffImage.getNumberOfPages(odd), TiffImage.getNumberOfPages(even));
      for (int c = 0; c < count; ++c) {
        try {
          Image imgOdd = TiffImage.getTiffImage(odd, c + 1);
          Image imgEven = TiffImage.getTiffImage(even, count - c);
          document.setPageSize(new Rectangle(imgOdd.getScaledWidth(), imgOdd.getScaledHeight()));
          document.newPage();
          imgOdd.setAbsolutePosition(0, 0);
          cb.addImage(imgOdd);
          document.setPageSize(new Rectangle(imgEven.getScaledWidth(), imgEven.getScaledHeight()));
          document.newPage();
          imgEven.setAbsolutePosition(0, 0);
          cb.addImage(imgEven);

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