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

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

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

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

    cb.restoreState();
  }
Example #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();
    }
  }
  @Override
  public Document create(Map<String, Object> model, Document doc) throws DocumentException {
    doc.newPage();

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

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

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

      createContentDateRange(paragraph, awal, akhir);
    }

    createContent(paragraph, list);

    doc.add(paragraph);

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

    return doc;
  }
Example #5
0
  public void toPDFGraphicFile(File file, int width, int height) throws IOException {
    // otherwise toolbar appears
    plotToolBar.setVisible(false);

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

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

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

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

    document.close();
    // make it reappear
    plotToolBar.setVisible(true);
  }
  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();
  }
 private void addMetaData(Document document) {
   document.addTitle("Expense Report");
   document.addSubject("Expense Report");
   document.addKeywords("Java, PDF, iText");
   document.addAuthor("www.Ihalkhata.com");
   document.addCreator("www.Ihalkhata.com");
 }
Example #8
0
  public void print(
      PdfWriter pdfWriter, GroupingContainer groupingContainer, Document document, Locale locale)
      throws DocumentException {
    if (notPrintOperationAtFirstPage()) {
      document.newPage();
    }

    ListMultimap<String, OrderOperationComponent> titleToOperationComponent =
        groupingContainer.getTitleToOperationComponent();
    for (String title : titleToOperationComponent.keySet()) {
      operationSectionHeader.print(document, title);
      int count = 0;
      for (OrderOperationComponent orderOperationComponent :
          groupingContainer.getTitleToOperationComponent().get(title)) {
        count++;
        operationOrderSection.print(
            pdfWriter,
            groupingContainer,
            orderOperationComponent.getOrder(),
            orderOperationComponent.getOperationComponent(),
            document,
            locale);
        if (count != titleToOperationComponent.get(title).size()) {
          if (notPrintOperationAtFirstPage()) {
            document.add(Chunk.NEXTPAGE);
          }
        }
      }
    }
  }
Example #9
0
  @Test
  public void testNoBreakSpace() throws Exception {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    Document document = new Document();

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

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

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

    List<?> bookmarks = SimpleBookmark.getBookmark(r);
    assertEquals("bookmark size", 1, bookmarks.size());
    @SuppressWarnings("unchecked")
    HashMap<String, Object> b = (HashMap<String, Object>) bookmarks.get(0);
    String title = (String) b.get("Title");
    assertEquals("bookmark title", TITLE, title);
  }
Example #10
0
 private static void addMetaData(Document document) {
   document.addTitle("Report Eventi");
   document.addSubject("Report Eventi selezionati nella console Govpay");
   document.addKeywords("Report, Eventi, Govpay");
   document.addAuthor("Govpay");
   document.addCreator("Govpay");
 }
Example #11
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();
 }
 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();
 }
  /**
   * This function is used to draw very thin white borders over the outer edge of the raster map.
   * It's necessary because the map edge "bleeds" into the adjacent pixels, and we need to cover
   * that.
   *
   * <p>I think this quirky behaviour is possibly an iText bug
   */
  private void addWhiteMapBorder(Image img, Document doc) {

    try {

      Color color = Color.white;
      int borderWidth = 1;

      BufferedImage bufferedTop =
          new BufferedImage((int) img.getScaledWidth(), borderWidth, BufferedImage.TYPE_INT_RGB);
      Graphics2D g1 = bufferedTop.createGraphics();
      g1.setBackground(color);
      g1.clearRect(0, 0, bufferedTop.getWidth(), bufferedTop.getHeight());
      Image top = Image.getInstance(bufferedImage2ByteArray(bufferedTop));
      top.setAbsolutePosition(
          img.getAbsoluteX(),
          img.getAbsoluteY() + img.getScaledHeight() - bufferedTop.getHeight() / 2);

      BufferedImage bufferedBottom =
          new BufferedImage((int) img.getScaledWidth(), borderWidth, BufferedImage.TYPE_INT_RGB);
      Graphics2D g2 = bufferedBottom.createGraphics();
      g2.setBackground(color);
      g2.clearRect(0, 0, bufferedBottom.getWidth(), bufferedBottom.getHeight());
      Image bottom = Image.getInstance(bufferedImage2ByteArray(bufferedBottom));
      bottom.setAbsolutePosition(
          img.getAbsoluteX(), img.getAbsoluteY() - bufferedTop.getHeight() / 2);

      BufferedImage bufferedLeft =
          new BufferedImage(borderWidth, (int) img.getScaledHeight(), BufferedImage.TYPE_INT_RGB);
      Graphics2D g3 = bufferedLeft.createGraphics();
      g3.setBackground(color);
      g3.clearRect(0, 0, bufferedLeft.getWidth(), bufferedLeft.getHeight());
      Image left = Image.getInstance(bufferedImage2ByteArray(bufferedLeft));
      left.setAbsolutePosition(
          img.getAbsoluteX() - bufferedLeft.getWidth() / 2, img.getAbsoluteY());

      BufferedImage bufferedRight =
          new BufferedImage(borderWidth, (int) img.getScaledHeight(), BufferedImage.TYPE_INT_RGB);
      Graphics2D g4 = bufferedRight.createGraphics();
      g4.setBackground(color);
      g4.clearRect(0, 0, bufferedRight.getWidth(), bufferedRight.getHeight());
      Image right = Image.getInstance(bufferedImage2ByteArray(bufferedRight));
      right.setAbsolutePosition(
          img.getAbsoluteX() + img.getScaledWidth() - bufferedRight.getWidth() / 2,
          img.getAbsoluteY());

      doc.add(top);
      doc.add(bottom);
      doc.add(left);
      doc.add(right);
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
Example #15
0
  /**
   * Creates a document with some goto actions.
   *
   * @param args no arguments needed
   */
  public static void main(String[] args) {

    System.out.println("Destinations");

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

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

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

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

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

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

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

    // step 5: we close the document
    document.close();
  }
Example #16
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);
    }
  }
Example #17
0
  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));
  }
    @Override
    public void onEndPage(PdfWriter writer, Document document) {
      try {
        Rectangle page = document.getPageSize();

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

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

        // Add page border

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

      } catch (JSONException e) {
        Logger.getLogger(ExportProjectReportServlet.class.getName()).log(Level.SEVERE, null, e);
        throw new ExceptionConverter(e);
      }
    }
  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();
  }
Example #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);
   }
 }
Example #21
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);
   }
 }
Example #22
0
  public void beginDraw() {
    //    long t0 = System.currentTimeMillis();

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

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

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

      //      System.out.println("beginDraw fonts " + (System.currentTimeMillis() - t));
      g2 = content.createGraphics(width, height, getMapper());
      //      g2 = template.createGraphics(width, height, mapper);
    }
    //    System.out.println("beginDraw " + (System.currentTimeMillis() - t0));
    super.beginDraw();
  }
Example #23
0
 /** @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);
   }
 }
Example #24
0
 /**
  * Adds a table to a document.
  *
  * @param document The document to add the table to.
  * @param table The table to add to the document.
  */
 public static void addTableToDocument(Document document, PdfPTable table) {
   try {
     document.add(table);
   } catch (DocumentException ex) {
     throw new RuntimeException("Failed to add table to document", ex);
   }
 }
Example #25
0
 public void dispose() {
   if (document != null) {
     g2.dispose();
     document.close(); // can't be done in finalize, not always called
     document = null;
   }
   // new Exception().printStackTrace(System.out);
 }
Example #26
0
 public void manipulatePdf(String src, String dest, int pow)
     throws IOException, DocumentException {
   PdfReader reader = new PdfReader(src);
   Rectangle pageSize = reader.getPageSize(1);
   Rectangle newSize =
       (pow % 2) == 0
           ? new Rectangle(pageSize.getWidth(), pageSize.getHeight())
           : new Rectangle(pageSize.getHeight(), pageSize.getWidth());
   Rectangle unitSize = new Rectangle(pageSize.getWidth(), pageSize.getHeight());
   for (int i = 0; i < pow; i++) {
     unitSize = new Rectangle(unitSize.getHeight() / 2, unitSize.getWidth());
   }
   int n = (int) Math.pow(2, pow);
   int r = (int) Math.pow(2, pow / 2);
   int c = n / r;
   Document document = new Document(newSize, 0, 0, 0, 0);
   PdfWriter writer =
       PdfWriter.getInstance(document, new FileOutputStream(String.format(dest, n)));
   document.open();
   PdfContentByte cb = writer.getDirectContent();
   PdfImportedPage page;
   Rectangle currentSize;
   float offsetX, offsetY, factor;
   int total = reader.getNumberOfPages();
   for (int i = 0; i < total; ) {
     if (i % n == 0) {
       document.newPage();
     }
     currentSize = reader.getPageSize(++i);
     factor =
         Math.min(
             unitSize.getWidth() / currentSize.getWidth(),
             unitSize.getHeight() / currentSize.getHeight());
     offsetX =
         unitSize.getWidth() * ((i % n) % c)
             + (unitSize.getWidth() - (currentSize.getWidth() * factor)) / 2f;
     offsetY =
         newSize.getHeight()
             - (unitSize.getHeight() * (((i % n) / c) + 1))
             + (unitSize.getHeight() - (currentSize.getHeight() * factor)) / 2f;
     page = writer.getImportedPage(reader, i);
     cb.addTemplate(page, factor, 0, 0, factor, offsetX, offsetY);
   }
   document.close();
 }
  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));
  }
Example #28
0
 protected void newPage() throws DocumentException {
   while (iLineNo < sNrLines) {
     out("");
     iLineNo++;
   }
   printFooter();
   iDoc.newPage();
   printHeader();
 }
Example #29
0
 public void close() {
   if (pdfDocument != null) {
     pdfDocument.close();
   }
   if (pdfCopy != null) {
     pdfCopy.close();
   }
   closed = true;
 }
Example #30
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);
 }