public void parse(File file, int maxPaths, ProgressMonitor monitor) throws Exception {
    monitor.beginTask(tr("Parsing PDF", 1));

    PDDocument document = PDDocument.load(file);

    if (document.isEncrypted()) {
      throw new Exception(tr("Encrypted documents not supported."));
    }

    List<?> allPages = document.getDocumentCatalog().getAllPages();

    if (allPages.size() != 1) {
      throw new Exception(tr("The PDF file must have exactly one page."));
    }

    PDPage page = (PDPage) allPages.get(0);
    PDRectangle pageSize = page.findMediaBox();
    Integer rotationVal = page.getRotation();
    int rotation = 0;
    if (rotationVal != null) {
      rotation = rotationVal.intValue();
    }

    GraphicsProcessor p = new GraphicsProcessor(target, rotation, maxPaths, monitor);
    PageDrawer drawer = new PageDrawer();
    drawer.drawPage(p, page);
    this.target.bounds =
        new Rectangle2D.Double(
            pageSize.getLowerLeftX(),
            pageSize.getLowerLeftY(),
            pageSize.getWidth(),
            pageSize.getHeight());

    monitor.finishTask();
  }
Example #2
0
  /**
   * Returns the given page as an RGB or ARGB image at the given scale.
   *
   * @param pageIndex the zero-based index of the page to be converted
   * @param scale the scaling factor, where 1 = 72 DPI
   * @param imageType the type of image to return
   * @return the rendered page image
   * @throws IOException if the PDF cannot be read
   */
  public BufferedImage renderImage(int pageIndex, float scale, ImageType imageType)
      throws IOException {
    PDPage page = document.getPage(pageIndex);

    PDRectangle cropbBox = page.getCropBox();
    float widthPt = cropbBox.getWidth();
    float heightPt = cropbBox.getHeight();
    int widthPx = Math.round(widthPt * scale);
    int heightPx = Math.round(heightPt * scale);
    int rotationAngle = page.getRotation();

    // swap width and height
    BufferedImage image;
    if (rotationAngle == 90 || rotationAngle == 270) {
      image = new BufferedImage(heightPx, widthPx, imageType.toBufferedImageType());
    } else {
      image = new BufferedImage(widthPx, heightPx, imageType.toBufferedImageType());
    }

    // use a transparent background if the imageType supports alpha
    Graphics2D g = image.createGraphics();
    if (imageType == ImageType.ARGB) {
      g.setBackground(new Color(0, 0, 0, 0));
    } else {
      g.setBackground(Color.WHITE);
    }

    renderPage(page, g, image.getWidth(), image.getHeight(), scale, scale);
    g.dispose();

    return image;
  }
Example #3
0
  /**
   * Creates a style definition used for pages.
   *
   * @return The page style definition.
   */
  protected NodeData createPageStyle() {
    NodeData ret = createBlockStyle();
    TermFactory tf = CSSFactory.getTermFactory();
    ret.push(createDeclaration("position", tf.createIdent("relative")));
    ret.push(createDeclaration("border-width", tf.createLength(1f, Unit.px)));
    ret.push(createDeclaration("border-style", tf.createIdent("solid")));
    ret.push(createDeclaration("border-color", tf.createColor(0, 0, 255)));
    ret.push(createDeclaration("margin", tf.createLength(0.5f, Unit.em)));

    PDRectangle layout = getCurrentMediaBox();
    if (layout != null) {
      float w = layout.getWidth();
      float h = layout.getHeight();
      final int rot = pdpage.findRotation();
      if (rot == 90 || rot == 270) {
        float x = w;
        w = h;
        h = x;
      }

      ret.push(createDeclaration("width", tf.createLength(w, unit)));
      ret.push(createDeclaration("height", tf.createLength(h, unit)));
    } else log.warn("No media box found");

    return ret;
  }
  // renders a page to the given graphics
  public void renderPage(
      PDPage page, Paint paint, Canvas canvas, int width, int height, float scaleX, float scaleY)
      throws IOException {
    canvas.scale(scaleX, scaleY);
    // TODO should we be passing the scale to PageDrawer rather than messing with Graphics?

    PDRectangle cropBox = page.getCropBox();
    int rotationAngle = page.getRotation();

    if (rotationAngle != 0) {
      float translateX = 0;
      float translateY = 0;
      switch (rotationAngle) {
        case 90:
          translateX = cropBox.getHeight();
          break;
        case 270:
          translateY = cropBox.getWidth();
          break;
        case 180:
          translateX = cropBox.getWidth();
          translateY = cropBox.getHeight();
          break;
      }
      canvas.translate(translateX, translateY);
      canvas.rotate((float) Math.toRadians(rotationAngle));
    }

    PageDrawer drawer = new PageDrawer(page);
    drawer.drawPage(paint, canvas, cropBox);
  }
  /**
   * Returns the given page as an RGB image at the given scale.
   *
   * @param pageIndex the zero-based index of the page to be converted
   * @param scale the scaling factor, where 1 = 72 DPI
   * @param config the bitmap config to create
   * @return the rendered page image
   * @throws IOException if the PDF cannot be read
   */
  public Bitmap renderImage(int pageIndex, float scale, Bitmap.Config config) throws IOException {
    PDPage page = document.getPage(pageIndex);

    PDRectangle cropbBox = page.getCropBox();
    float widthPt = cropbBox.getWidth();
    float heightPt = cropbBox.getHeight();
    int widthPx = Math.round(widthPt * scale);
    int heightPx = Math.round(heightPt * scale);
    int rotationAngle = page.getRotation();

    // swap width and height
    Bitmap image;
    if (rotationAngle == 90 || rotationAngle == 270) {
      image = Bitmap.createBitmap(heightPx, widthPx, config);
    } else {
      image = Bitmap.createBitmap(widthPx, heightPx, config);
    }

    // use a transparent background if the imageType supports alpha
    Paint paint = new Paint();
    Canvas canvas = new Canvas(image);
    if (config != Bitmap.Config.ARGB_8888) {
      paint.setColor(Color.WHITE);
      paint.setStyle(Paint.Style.FILL);
      canvas.drawRect(0, 0, image.getWidth(), image.getHeight(), paint);
      paint.reset();
    }

    renderPage(page, paint, canvas, image.getWidth(), image.getHeight(), scale, scale);

    return image;
  }
 private PDRectangle boundingBox(
     final float lowerLeftX,
     final float lowerLeftY,
     final float upperRightX,
     final float upperRightY) {
   final PDRectangle boundingBox = new PDRectangle();
   boundingBox.setLowerLeftX(lowerLeftX);
   boundingBox.setLowerLeftY(lowerLeftY);
   boundingBox.setUpperRightX(upperRightX);
   boundingBox.setUpperRightY(upperRightY);
   return boundingBox;
 }
Example #7
0
 /**
  * Renders a given page to an AWT Graphics2D instance.
  *
  * @param pageIndex the zero-based index of the page to be converted
  * @param graphics the Graphics2D on which to draw the page
  * @param scale the scale to draw the page at
  * @throws IOException if the PDF cannot be read
  */
 public void renderPageToGraphics(int pageIndex, Graphics2D graphics, float scale)
     throws IOException {
   PDPage page = document.getPage(pageIndex);
   // TODO need width/wight calculations? should these be in PageDrawer?
   PDRectangle adjustedCropBox = page.getCropBox();
   renderPage(
       page,
       graphics,
       (int) adjustedCropBox.getWidth(),
       (int) adjustedCropBox.getHeight(),
       scale,
       scale);
 }
 /**
  * Set the fonts bounding box.
  *
  * @param rect The new bouding box.
  */
 public void setFontBoundingBox(PDRectangle rect) {
   COSArray array = null;
   if (rect != null) {
     array = rect.getCOSArray();
   }
   dic.setItem(COSName.FONT_BBOX, array);
 }
Example #9
0
 /**
  * This will set the BBox (bounding box) for this form.
  *
  * @param bbox The new BBox for this form.
  */
 public void setBBox(PDRectangle bbox) {
   if (bbox == null) {
     getCOSStream().removeItem(COSName.BBOX);
   } else {
     getCOSStream().setItem(COSName.BBOX, bbox.getCOSArray());
   }
 }
  private boolean markupMatch(Color color, PDPageContentStream contentStream, Match markingMatch)
      throws IOException {
    final List<PDRectangle> textBoundingBoxes = getTextBoundingBoxes(markingMatch.positions);

    if (textBoundingBoxes.size() > 0) {
      contentStream.appendRawCommands("/highlights gs\n");
      contentStream.setNonStrokingColor(color);
      for (PDRectangle textBoundingBox : textBoundingBoxes) {
        contentStream.fillRect(
            textBoundingBox.getLowerLeftX(),
            textBoundingBox.getLowerLeftY(),
            Math.max(
                Math.abs(textBoundingBox.getUpperRightX() - textBoundingBox.getLowerLeftX()), 10),
            10);
      }
      return true;
    }
    return false;
  }
Example #11
0
 /**
  * This will get the font height for a character.
  *
  * @param c The character code to get the width for.
  * @param offset The offset into the array.
  * @param length The length of the data.
  * @return The width is in 1000 unit of text space, ie 333 or 777
  * @throws IOException If an error occurs while parsing.
  */
 public float getFontHeight(byte[] c, int offset, int length) throws IOException {
   // maybe there is already a precalculated value
   if (avgFontHeight > 0) {
     return avgFontHeight;
   }
   float retval = 0;
   FontMetric metric = getAFM();
   if (metric != null) {
     int code = getCodeFromArray(c, offset, length);
     Encoding encoding = getFontEncoding();
     String characterName = encoding.getName(code);
     retval = metric.getCharacterHeight(characterName);
   } else {
     PDFontDescriptor desc = getFontDescriptor();
     if (desc != null) {
       // the following values are all more or less accurate
       // at least all are average values. Maybe we'll find
       // another way to get those value for every single glyph
       // in the future if needed
       PDRectangle fontBBox = desc.getFontBoundingBox();
       if (fontBBox != null) {
         retval = fontBBox.getHeight() / 2;
       }
       if (retval == 0) {
         retval = desc.getCapHeight();
       }
       if (retval == 0) {
         retval = desc.getAscent();
       }
       if (retval == 0) {
         retval = desc.getXHeight();
         if (retval > 0) {
           retval -= desc.getDescent();
         }
       }
       avgFontHeight = retval;
     }
   }
   return retval;
 }
 private PDPageContentStream addPageToDoc(PDDocument doc) throws IOException {
   PDPage page = new PDPage();
   page.setMediaBox(PAGE_SIZE);
   page.setRotation(IS_LANDSCAPE ? 90 : 0);
   doc.addPage(page);
   PDPageContentStream contentStream = new PDPageContentStream(doc, page, false, false);
   // User transformation matrix to change the reference when drawing.
   // This is necessary for the landscape position to draw correctly
   if (IS_LANDSCAPE) {
     contentStream.transform(new Matrix(0f, 1f, -1f, 0f, PAGE_SIZE.getWidth(), 0f));
   }
   contentStream.setFont(TEXT_FONT, FONT_SIZE);
   contentStream.setLineWidth(0.25f);
   return contentStream;
 }
Example #13
0
  private static Rectangle2D.Float getRectangle(PDPage page, PDRectangle rect) {

    float x = rect.getLowerLeftX() - 1;
    float y = rect.getUpperRightY() - 1;
    float width = rect.getWidth() + 2;
    float height = rect.getHeight() + rect.getHeight() / 4;
    int rotation = page.findRotation();
    if (rotation == 0) {
      PDRectangle pageSize = page.findMediaBox();
      y = pageSize.getHeight() - y;
    }
    Rectangle2D.Float awtRect = new Rectangle2D.Float(x, y, width, height);

    return awtRect;
  }
public class PDFBoxGeneratorSimple {
  private static Column[] columns = new Column[6];
  private static float[] rightEdgePos = new float[6];

  static {
    columns[0] = new Column("EmpNo", 50, ColumnAlignment.RIGHT);
    columns[1] = new Column("BirthDate", 70);
    columns[2] = new Column("FirstName", 75, ColumnAlignment.RIGHT);
    columns[3] = new Column("LastName", 150);
    columns[4] = new Column("Gender", 50);
    columns[5] = new Column("HireDate", 70);
    float crtEdge = 0f;
    for (int i = 0; i < 6; i++) {
      crtEdge += columns[i].getWidth();
      rightEdgePos[i] = crtEdge;
    }
  }

  // Page configuration
  private static final PDRectangle PAGE_SIZE = PDRectangle.A4;
  private static final boolean IS_LANDSCAPE = false;
  private static final float MARGIN = 20;
  private static final float tableTopY =
      IS_LANDSCAPE ? PAGE_SIZE.getWidth() - MARGIN : PAGE_SIZE.getHeight() - MARGIN;
  // Font configuration
  private static final PDFont TEXT_FONT = PDType1Font.HELVETICA;
  private static final float FONT_SIZE = 10;
  private static final float TEXT_LINE_HEIGHT =
      TEXT_FONT.getFontDescriptor().getFontBoundingBox().getHeight() / 1000 * FONT_SIZE;
  // Table configuration
  private static final float ROW_HEIGHT = 15;
  private static final float CELL_MARGIN = 2;

  public ByteArrayOutputStream generateReport(
      final int lineCount, final int columnCount, List<String[]> tableContent) throws IOException {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();

    // Calculate center alignment for text in cell considering font height
    final float startTextY = tableTopY - (ROW_HEIGHT / 2) - (TEXT_LINE_HEIGHT / 4);
    PDDocument doc = new PDDocument();
    PDPageContentStream pageStream = addPageToDoc(doc);
    float crtLineY = tableTopY;
    float crtTextY = startTextY;
    // draw the header
    float rowHeight = drawTableHeader(pageStream, columnCount, crtTextY, crtLineY);
    crtLineY -= rowHeight;
    crtTextY -= rowHeight;

    // draw the lines
    for (String[] crtLine : tableContent) {
      if (crtTextY <= MARGIN) {
        drawVerticalLines(pageStream, columnCount, crtLineY);
        pageStream.close();
        // start new Page
        pageStream = addPageToDoc(doc);
        crtLineY = tableTopY;
        crtTextY = startTextY;
        rowHeight = drawTableHeader(pageStream, columnCount, crtTextY, crtLineY);
        crtLineY -= rowHeight;
        crtTextY -= rowHeight;
      }
      rowHeight = drawTableRow(pageStream, crtLine, columnCount, crtTextY, crtLineY);
      crtLineY -= rowHeight;
      crtTextY -= rowHeight;
    }

    drawVerticalLines(pageStream, columnCount, crtLineY);
    pageStream.close();
    doc.save(baos);
    doc.close();
    return baos;
  }

  /**
   * Draw vertical separator lines between cells.
   *
   * @throws IOException
   */
  private void drawVerticalLines(PDPageContentStream pageStream, int columnCount, float crtLineY)
      throws IOException {
    pageStream.addLine(MARGIN, tableTopY, MARGIN, crtLineY);
    for (int i = 0; i < columnCount; i++) {
      float crtY = MARGIN + rightEdgePos[i];
      pageStream.addLine(crtY, tableTopY, crtY, crtLineY);
    }
    pageStream.closeAndStroke();
  }

  /**
   * Draw the Table header.
   *
   * @param crtLineY
   * @return
   */
  private float drawTableHeader(
      PDPageContentStream pageStream, int columnCount, float startTextY, float crtLineY)
      throws IOException {
    // Position cursor to start drawing content
    float crtX = MARGIN + CELL_MARGIN;
    float maxHeight = 0;

    pageStream.drawLine(MARGIN, crtLineY, MARGIN + rightEdgePos[columnCount - 1], crtLineY);

    for (int i = 0; i < columnCount; i++) {
      String text = columns[i].getName();
      float cellHeight = writeCellContent(i, text, pageStream, crtX, startTextY);
      if (cellHeight > maxHeight) {
        maxHeight = cellHeight;
      }
      crtX += columns[i].getWidth();
    }

    pageStream.drawLine(
        MARGIN, crtLineY - maxHeight, MARGIN + rightEdgePos[columnCount - 1], crtLineY - maxHeight);
    return maxHeight;
  }

  /**
   * Draw the Line content.
   *
   * @param crtLineY
   * @return
   */
  private float drawTableRow(
      PDPageContentStream pageStream,
      String[] lineContent,
      int columnCount,
      float startTextY,
      float crtLineY)
      throws IOException {
    float crtX = MARGIN + CELL_MARGIN;
    float maxHeight = 0;

    for (int i = 0; i < columnCount; i++) {
      float cellHeight = writeCellContent(i, lineContent[i], pageStream, crtX, startTextY);
      if (cellHeight > maxHeight) {
        maxHeight = cellHeight;
      }
      crtX += columns[i].getWidth();
    }
    pageStream.drawLine(
        MARGIN, crtLineY - maxHeight, MARGIN + rightEdgePos[columnCount - 1], crtLineY - maxHeight);
    return maxHeight;
  }

  private float writeCellContent(
      int colIndex, String text, PDPageContentStream pageStream, float crtX, float startTextY)
      throws IOException {
    float cellHeight = ROW_HEIGHT;
    float cellInnerWidth = columns[colIndex].getWidth() - 2 * CELL_MARGIN;
    float textWidth = TEXT_FONT.getStringWidth(text) / 1000 * FONT_SIZE;
    if (textWidth <= cellInnerWidth) { // line fits in cell
      pageStream.beginText();
      if (columns[colIndex].getAlignment() == ColumnAlignment.LEFT) {
        pageStream.newLineAtOffset(crtX, startTextY);
      } else {
        float textLeftPos = crtX + cellInnerWidth - textWidth;
        pageStream.newLineAtOffset(textLeftPos, startTextY);
      }
      pageStream.showText(text != null ? text : "");
      pageStream.endText();
    } else { // line must be wrapped

      int start = 0;
      int end = 0;
      float crtCellY = startTextY;
      String currentToken = "";
      for (int i : possibleWrapPoints(text)) {
        float width = TEXT_FONT.getStringWidth(text.substring(start, i)) / 1000 * FONT_SIZE;
        if (start < end && width > cellInnerWidth) {
          currentToken = text.substring(start, end);
          // Draw partial text and increase height
          pageStream.beginText();
          if (columns[colIndex].getAlignment() == ColumnAlignment.LEFT) {
            pageStream.newLineAtOffset(crtX, crtCellY);
          } else {
            float currentTokenWidth = TEXT_FONT.getStringWidth(currentToken) / 1000 * FONT_SIZE;
            float textLeftPos = crtX + cellInnerWidth - currentTokenWidth;
            pageStream.newLineAtOffset(textLeftPos, crtCellY);
          }
          pageStream.showText(currentToken);
          pageStream.endText();
          crtCellY -= TEXT_LINE_HEIGHT;
          start = end;
          cellHeight += TEXT_LINE_HEIGHT;
        }
        end = i;
      }
      // Last piece of text
      pageStream.beginText();
      currentToken = text.substring(start);
      if (columns[colIndex].getAlignment() == ColumnAlignment.LEFT) {
        pageStream.newLineAtOffset(crtX, crtCellY);
      } else {
        float currentTokenWidth = TEXT_FONT.getStringWidth(currentToken) / 1000 * FONT_SIZE;
        float textLeftPos = crtX + cellInnerWidth - currentTokenWidth;
        pageStream.newLineAtOffset(textLeftPos, crtCellY);
      }
      pageStream.showText(currentToken);
      pageStream.endText();
    }

    return cellHeight;
  }

  int[] possibleWrapPoints(String text) {
    String[] split = text.split("(?<=\\W)");
    int[] ret = new int[split.length];
    ret[0] = split[0].length();
    for (int i = 1; i < split.length; i++) ret[i] = ret[i - 1] + split[i].length();
    return ret;
  }

  private PDPageContentStream addPageToDoc(PDDocument doc) throws IOException {
    PDPage page = new PDPage();
    page.setMediaBox(PAGE_SIZE);
    page.setRotation(IS_LANDSCAPE ? 90 : 0);
    doc.addPage(page);
    PDPageContentStream contentStream = new PDPageContentStream(doc, page, false, false);
    // User transformation matrix to change the reference when drawing.
    // This is necessary for the landscape position to draw correctly
    if (IS_LANDSCAPE) {
      contentStream.transform(new Matrix(0f, 1f, -1f, 0f, PAGE_SIZE.getWidth(), 0f));
    }
    contentStream.setFont(TEXT_FONT, FONT_SIZE);
    contentStream.setLineWidth(0.25f);
    return contentStream;
  }
}
Example #15
0
  /**
   * @param args
   * @throws Exception
   */
  public static void main(String[] args) throws Exception {

    // Create a document and add a page to it
    PDDocument document = new PDDocument();
    PDPage page1 = new PDPage(PDPage.PAGE_SIZE_A4);
    // PDPage.PAGE_SIZE_LETTER is also possible
    PDRectangle rect = page1.getMediaBox();
    // rect can be used to get the page width and height
    document.addPage(page1);

    // Create a new font object selecting one of the PDF base fonts
    PDFont fontPlain = PDType1Font.HELVETICA;
    PDFont fontBold = PDType1Font.HELVETICA_BOLD;
    PDFont fontItalic = PDType1Font.HELVETICA_OBLIQUE;
    PDFont fontMono = PDType1Font.COURIER;

    // Start a new content stream which will "hold" the to be created content
    PDPageContentStream cos = new PDPageContentStream(document, page1);

    int line = 1;

    // Define a text content stream using the selected font, move the cursor and draw some text
    cos.beginText();

    cos.setFont(fontPlain, 12);
    cos.setNonStrokingColor(Color.RED);
    // width is 100; height is 20 lines down everytime
    cos.moveTextPositionByAmount(100, rect.getHeight() - 20 * (++line));
    cos.drawString("eeey boy");
    cos.endText();

    cos.beginText();
    cos.setFont(fontItalic, 12);
    cos.setNonStrokingColor(Color.GREEN);
    cos.moveTextPositionByAmount(100, rect.getHeight() - 20 * (++line));
    cos.drawString("How do you do?");
    cos.endText();

    cos.beginText();
    cos.setFont(fontBold, 12);
    cos.setNonStrokingColor(Color.BLACK);
    cos.moveTextPositionByAmount(100, rect.getHeight() - 20 * (++line));
    cos.drawString("Dit duurde veel langer dan nodig");
    cos.endText();

    cos.beginText();
    cos.setFont(fontMono, 12);
    cos.setNonStrokingColor(Color.BLACK);
    cos.moveTextPositionByAmount(100, rect.getHeight() - 20 * (++line));
    cos.drawString("maar ik was wat dingentjes aan t uitzoeken.");
    cos.endText();

    // Add some gucci into this place
    try {
      BufferedImage awtImage = ImageIO.read(new File("Gucci.jpg"));
      PDXObjectImage ximage = new PDPixelMap(document, awtImage);
      float scale = 0.5f; // alter this value to set the image size
      cos.drawXObject(ximage, 100, 400, ximage.getWidth() * scale, ximage.getHeight() * scale);
    } catch (IIOException Fnfex) {
      System.out.println("No image for you");
    }

    // Make sure that the content stream is closed:
    cos.close();
    // New page
    PDPage page2 = new PDPage(PDPage.PAGE_SIZE_A4);
    document.addPage(page2);
    cos = new PDPageContentStream(document, page2);

    // draw a red box in the lower left hand corner
    cos.setNonStrokingColor(Color.RED);
    cos.fillRect(10, 10, 100, 100);

    // add two lines of different widths
    cos.setLineWidth(1);
    cos.addLine(200, 250, 400, 250);
    cos.closeAndStroke();
    cos.setLineWidth(5);
    cos.addLine(200, 300, 400, 300);
    cos.closeAndStroke();

    // close the content stream for page 2
    cos.close();

    // Save the results and ensure that the document is properly closed:
    document.save("GUCCI.pdf");
    document.close();
  }
  @SuppressWarnings("deprecation")
  @Override
  public void generateReport() throws ReportException {
    int pageNum = 1;
    // log.info("Report creation started");
    // declare data variables
    List<WarehousePart> records = null;
    try {
      records = gateway.fetchWarehouseAndParts();
    } catch (GatewayException e) {
      throw new ReportException("Error in report generation: " + e.getMessage());
    }

    // prep the report page 1
    doc = new PDDocument();
    PDPage page1 = new PDPage();
    PDRectangle rect = page1.getMediaBox();
    doc.addPage(page1);

    PDPage page2 = new PDPage();
    PDRectangle rect2 = page2.getMediaBox();
    doc.addPage(page2);
    // get content stream for page 1
    PDPageContentStream content = null;

    PDFont fontPlain = PDType1Font.HELVETICA;
    PDFont fontBold = PDType1Font.HELVETICA_BOLD;
    PDFont fontItalic = PDType1Font.HELVETICA_OBLIQUE;
    PDFont fontMono = PDType1Font.COURIER;
    PDFont fontMonoBold = PDType1Font.COURIER_BOLD;

    page1.setRotation(90);

    float margin = 20;

    try {
      content = new PDPageContentStream(doc, page1);

      // print header of page 1
      content.concatenate2CTM(0, 1, -1, 0, 718, 0);
      content.setNonStrokingColor(Color.CYAN);
      content.setStrokingColor(Color.BLACK);

      float bottomY = rect.getHeight() - margin - 100;
      float headerEndX = rect.getWidth() - margin * 2;

      content.addRect(margin, bottomY, headerEndX, 100);
      content.fillAndStroke();

      content.setNonStrokingColor(Color.BLACK);

      // print report title
      content.setFont(fontBold, 24);
      content.beginText();
      content.newLineAtOffset(margin + 15, bottomY + 15);
      content.showText("Warehouse Inventory Summary");
      content.endText();

      // page Number
      content.setFont(fontBold, 12);
      content.beginText();
      content.newLineAtOffset(710, 150);
      content.showText("Page " + pageNum);
      content.endText();

      // Date
      Date date = new Date();
      content.setFont(fontBold, 12);
      content.beginText();
      content.newLineAtOffset(30, 150);
      content.showText(date.toString());
      content.endText();

      content.setFont(fontMonoBold, 12);
      float dataY = 610;

      // colum layout, this might require tweaking
      // warehouse Name    Part #     Part Name            Quantity      Unit
      float colX_0 = margin + 15; // warehouse name
      float colX_1 = colX_0 + 180; // Part number
      float colX_2 = colX_1 + 100; // Part Name
      float colX_3 = colX_2 + 180; // quantity
      float colX_4 = colX_3 + 100; // unit

      // print the colum texts
      content.beginText();
      content.newLineAtOffset(colX_0, dataY);
      content.showText("Warehouse Name");
      content.endText();
      content.beginText();
      content.newLineAtOffset(colX_1, dataY);
      content.showText("Part Number");
      content.endText();
      content.beginText();
      content.newLineAtOffset(colX_2, dataY);
      content.showText("Part Name");
      content.endText();
      content.beginText();
      content.newLineAtOffset(colX_3, dataY);
      content.showText("Quantity");
      content.endText();
      content.beginText();
      content.newLineAtOffset(colX_4, dataY);
      content.showText("Unit");
      content.endText();

      // print the report rows
      content.setFont(fontMono, 12);

      int counter = 1;

      for (WarehousePart wp : records) {
        // the offset for the current row
        float offset = dataY - (counter * (fontMono.getHeight(12) + 15));

        Warehouse w = wp.getOwner();
        Part p = wp.getPart();

        content.beginText();
        content.newLineAtOffset(colX_0, offset);
        content.showText(w.getWarehouseName());
        content.endText();
        content.beginText();
        content.newLineAtOffset(colX_1, offset);
        content.showText("" + p.getPartNumber());
        content.endText();
        content.beginText();
        content.newLineAtOffset(colX_2, offset);
        content.showText("" + p.getPartName());
        content.endText();
        content.beginText();
        content.newLineAtOffset(colX_3, offset);
        content.showText("" + wp.getQuantity());
        content.endText();
        content.beginText();
        content.newLineAtOffset(colX_4, offset);
        content.showText("" + p.getUnitQuanitity());
        content.endText();

        counter++;
        if (counter > 25) {
          content.close();
          break;
        }
      }

      content = new PDPageContentStream(doc, page2);
      content.concatenate2CTM(0, 1, -1, 0, 718, 0);
      content.setFont(fontMono, 12);
      page2.setRotation(90);
      pageNum = 2;
      int counter2 = 1;

      // page Number
      content.setFont(fontBold, 12);
      content.beginText();
      content.newLineAtOffset(710, 150);
      content.showText("Page " + pageNum);
      content.endText();

      // Date

      content.setFont(fontBold, 12);
      content.beginText();
      content.newLineAtOffset(30, 150);
      content.showText(date.toString());
      content.endText();

      content.setFont(fontMono, 12);

      for (WarehousePart wp : records.subList(25, records.size())) {
        // the offset for the current row
        float offset = dataY - (counter2 * (fontMono.getHeight(12) + 15));

        Warehouse w = wp.getOwner();
        Part p = wp.getPart();

        content.beginText();
        content.newLineAtOffset(colX_0, offset);
        content.showText(w.getWarehouseName());
        content.endText();
        content.beginText();
        content.newLineAtOffset(colX_1, offset);
        content.showText("" + p.getPartNumber());
        content.endText();
        content.beginText();
        content.newLineAtOffset(colX_2, offset);
        content.showText("" + p.getPartName());
        content.endText();
        content.beginText();
        content.newLineAtOffset(colX_3, offset);
        content.showText("" + wp.getQuantity());
        content.endText();
        content.beginText();
        content.newLineAtOffset(colX_4, offset);
        content.showText("" + p.getUnitQuanitity());
        content.endText();

        counter2++;
      }

    } catch (IOException e) {
      throw new ReportException("Error in report generation: " + e.getMessage());
    } finally {

      try {
        content.close();
      } catch (IOException e) {
        e.printStackTrace();
      }
    }
  }
Example #17
0
  private static Table createContent() {
    // Total size of columns must not be greater than table width.
    List<Column> columns = new ArrayList<Column>();
    columns.add(new Column("FirstName", 90));
    columns.add(new Column("LastName", 90));
    columns.add(new Column("Email", 230));
    columns.add(new Column("ZipCode", 43));
    columns.add(new Column("MailOptIn", 50));
    columns.add(new Column("Code", 80));
    columns.add(new Column("Branch", 39));
    columns.add(new Column("Product", 300));
    columns.add(new Column("Date", 120));
    columns.add(new Column("Channel", 43));

    String[][] content = {
      {
        "FirstName",
        "LastName",
        "*****@*****.**",
        "12345",
        "yes",
        "XH4234FSD",
        "4334",
        "yFone 5 XS",
        "31/05/2013 07:15 am",
        "WEB"
      },
      {
        "FirstName",
        "LastName",
        "*****@*****.**",
        "12345",
        "yes",
        "XH4234FSD",
        "4334",
        "yFone 5 XS",
        "31/05/2013 07:15 am",
        "WEB"
      },
      {
        "FirstName",
        "LastName",
        "*****@*****.**",
        "12345",
        "yes",
        "XH4234FSD",
        "4334",
        "yFone 5 XS",
        "31/05/2013 07:15 am",
        "WEB"
      },
      {
        "FirstName",
        "LastName",
        "*****@*****.**",
        "12345",
        "yes",
        "XH4234FSD",
        "4334",
        "yFone 5 XS",
        "31/05/2013 07:15 am",
        "WEB"
      },
      {
        "FirstName",
        "LastName",
        "*****@*****.**",
        "12345",
        "yes",
        "XH4234FSD",
        "4334",
        "yFone 5 XS",
        "31/05/2013 07:15 am",
        "WEB"
      },
      {
        "FirstName",
        "LastName",
        "*****@*****.**",
        "12345",
        "yes",
        "XH4234FSD",
        "4334",
        "yFone 5 XS",
        "31/05/2013 07:15 am",
        "WEB"
      },
      {
        "FirstName",
        "LastName",
        "*****@*****.**",
        "12345",
        "yes",
        "XH4234FSD",
        "4334",
        "yFone 5 XS",
        "31/05/2013 07:15 am",
        "WEB"
      },
      {
        "FirstName",
        "LastName",
        "*****@*****.**",
        "12345",
        "yes",
        "XH4234FSD",
        "4334",
        "yFone 5 XS",
        "31/05/2013 07:15 am",
        "WEB"
      },
      {
        "FirstName",
        "LastName",
        "*****@*****.**",
        "12345",
        "yes",
        "XH4234FSD",
        "4334",
        "yFone 5 XS",
        "31/05/2013 07:15 am",
        "WEB"
      },
      {
        "FirstName",
        "LastName",
        "*****@*****.**",
        "12345",
        "yes",
        "XH4234FSD",
        "4334",
        "yFone 5 XS",
        "31/05/2013 07:15 am",
        "WEB"
      },
      {
        "FirstName",
        "LastName",
        "*****@*****.**",
        "12345",
        "yes",
        "XH4234FSD",
        "4334",
        "yFone 5 XS",
        "31/05/2013 07:15 am",
        "WEB"
      },
      {
        "FirstName",
        "LastName",
        "*****@*****.**",
        "12345",
        "yes",
        "XH4234FSD",
        "4334",
        "yFone 5 XS",
        "31/05/2013 07:15 am",
        "WEB"
      },
      {
        "FirstName",
        "LastName",
        "*****@*****.**",
        "12345",
        "yes",
        "XH4234FSD",
        "4334",
        "yFone 5 XS",
        "31/05/2013 07:15 am",
        "WEB"
      },
      {
        "FirstName",
        "LastName",
        "*****@*****.**",
        "12345",
        "yes",
        "XH4234FSD",
        "4334",
        "yFone 5 XS",
        "31/05/2013 07:15 am",
        "WEB"
      },
      {
        "FirstName",
        "LastName",
        "*****@*****.**",
        "12345",
        "yes",
        "XH4234FSD",
        "4334",
        "yFone 5 XS",
        "31/05/2013 07:15 am",
        "WEB"
      },
      {
        "FirstName",
        "LastName",
        "*****@*****.**",
        "12345",
        "yes",
        "XH4234FSD",
        "4334",
        "yFone 5 XS",
        "31/05/2013 07:15 am",
        "WEB"
      },
      {
        "FirstName",
        "LastName",
        "*****@*****.**",
        "12345",
        "yes",
        "XH4234FSD",
        "4334",
        "yFone 5 XS",
        "31/05/2013 07:15 am",
        "WEB"
      },
      {
        "FirstName",
        "LastName",
        "*****@*****.**",
        "12345",
        "yes",
        "XH4234FSD",
        "4334",
        "yFone 5 XS",
        "31/05/2013 07:15 am",
        "WEB"
      },
      {
        "FirstName",
        "LastName",
        "*****@*****.**",
        "12345",
        "yes",
        "XH4234FSD",
        "4334",
        "yFone 5 XS",
        "31/05/2013 07:15 am",
        "WEB"
      },
      {
        "FirstName",
        "LastName",
        "*****@*****.**",
        "12345",
        "yes",
        "XH4234FSD",
        "4334",
        "yFone 5 XS",
        "31/05/2013 07:15 am",
        "WEB"
      },
      {
        "FirstName",
        "LastName",
        "*****@*****.**",
        "12345",
        "yes",
        "XH4234FSD",
        "4334",
        "yFone 5 XS",
        "31/05/2013 07:15 am",
        "WEB"
      },
      {
        "FirstName",
        "LastName",
        "*****@*****.**",
        "12345",
        "yes",
        "XH4234FSD",
        "4334",
        "yFone 5 XS",
        "31/05/2013 07:15 am",
        "WEB"
      },
      {
        "FirstName",
        "LastName",
        "*****@*****.**",
        "12345",
        "yes",
        "XH4234FSD",
        "4334",
        "yFone 5 XS",
        "31/05/2013 07:15 am",
        "WEB"
      },
      {
        "FirstName",
        "LastName",
        "*****@*****.**",
        "12345",
        "yes",
        "XH4234FSD",
        "4334",
        "yFone 5 XS",
        "31/05/2013 07:15 am",
        "WEB"
      },
      {
        "FirstName",
        "LastName",
        "*****@*****.**",
        "12345",
        "yes",
        "XH4234FSD",
        "4334",
        "yFone 5 XS",
        "31/05/2013 07:15 am",
        "WEB"
      },
      {
        "FirstName",
        "LastName",
        "*****@*****.**",
        "12345",
        "yes",
        "XH4234FSD",
        "4334",
        "yFone 5 XS",
        "31/05/2013 07:15 am",
        "WEB"
      },
      {
        "FirstName",
        "LastName",
        "*****@*****.**",
        "12345",
        "yes",
        "XH4234FSD",
        "4334",
        "yFone 5 XS",
        "31/05/2013 07:15 am",
        "WEB"
      },
      {
        "FirstName",
        "LastName",
        "*****@*****.**",
        "12345",
        "yes",
        "XH4234FSD",
        "4334",
        "yFone 5 XS",
        "31/05/2013 07:15 am",
        "WEB"
      },
      {
        "FirstName",
        "LastName",
        "*****@*****.**",
        "12345",
        "yes",
        "XH4234FSD",
        "4334",
        "yFone 5 XS",
        "31/05/2013 07:15 am",
        "WEB"
      },
      {
        "FirstName",
        "LastName",
        "*****@*****.**",
        "12345",
        "yes",
        "XH4234FSD",
        "4334",
        "yFone 5 XS",
        "31/05/2013 07:15 am",
        "WEB"
      },
      {
        "FirstName",
        "LastName",
        "*****@*****.**",
        "12345",
        "yes",
        "XH4234FSD",
        "4334",
        "yFone 5 XS",
        "31/05/2013 07:15 am",
        "WEB"
      },
      {
        "LastItem",
        "LastName",
        "*****@*****.**",
        "12345",
        "yes",
        "XH4234FSD",
        "4334",
        "yFone 5 XS",
        "31/05/2013 07:15 am",
        "WEB"
      }
    };

    float tableHeight =
        IS_LANDSCAPE ? PAGE_SIZE.getWidth() - (2 * MARGIN) : PAGE_SIZE.getHeight() - (2 * MARGIN);

    Table table =
        new TableBuilder()
            .setCellMargin(CELL_MARGIN)
            .setColumns(columns)
            .setContent(content)
            .setHeight(tableHeight)
            .setNumberOfRows(content.length)
            .setRowHeight(ROW_HEIGHT)
            .setMargin(MARGIN)
            .setPageSize(PAGE_SIZE)
            .setLandscape(IS_LANDSCAPE)
            .setTextFont(TEXT_FONT)
            .setFontSize(FONT_SIZE)
            .build();
    return table;
  }
Example #18
0
 /**
  * Transforms the given rectangle using the CTM and then intersects it with the current clipping
  * area.
  */
 private void clipToRect(PDRectangle rectangle) {
   if (rectangle != null) {
     GeneralPath clip = rectangle.transform(getGraphicsState().getCurrentTransformationMatrix());
     getGraphicsState().intersectClippingPath(clip);
   }
 }
Example #19
-1
  // renders a page to the given graphics
  private void renderPage(
      PDPage page, Graphics2D graphics, int width, int height, float scaleX, float scaleY)
      throws IOException {
    graphics.clearRect(0, 0, width, height);

    graphics.scale(scaleX, scaleY);
    // TODO should we be passing the scale to PageDrawer rather than messing with Graphics?

    PDRectangle cropBox = page.getCropBox();
    int rotationAngle = page.getRotation();

    if (rotationAngle != 0) {
      float translateX = 0;
      float translateY = 0;
      switch (rotationAngle) {
        case 90:
          translateX = cropBox.getHeight();
          break;
        case 270:
          translateY = cropBox.getWidth();
          break;
        case 180:
          translateX = cropBox.getWidth();
          translateY = cropBox.getHeight();
          break;
      }
      graphics.translate(translateX, translateY);
      graphics.rotate((float) Math.toRadians(rotationAngle));
    }

    // the end-user may provide a custom PageDrawer
    PageDrawerParameters parameters = new PageDrawerParameters(this, page);
    PageDrawer drawer = createPageDrawer(parameters);
    drawer.drawPage(graphics, cropBox);
  }