Пример #1
0
  public int print(Graphics g, PageFormat pf, int page) throws PrinterException {
    if (context instanceof TextWindow) {
      TextWindow tw = (TextWindow) context;
      if (page == 0) {
        allStrings = tw.convertToStrings();
        printFont = new Font("Helvetica", Font.PLAIN, 10);
        FontMetrics fm = g.getFontMetrics(printFont);
        pageHeight = (int) pf.getImageableHeight();
        fontHeight = fm.getHeight();
        yOffset = fm.getAscent();
        linesPerPage = pageHeight / fontHeight;
        startLine = startChar = 0;
        startPageNumber = 0;
        startLineAtPage = startLine;
        startCharAtPage = startChar;
        frc = new FontRenderContext(null, true, true);
      }
      if (page == startPageNumber) {
        startLine = startLineAtPage;
        startChar = startCharAtPage;
      } else {
        startPageNumber = page;
        startLineAtPage = startLine;
        startCharAtPage = startChar;
      }
      if (startLine < allStrings.length) {
        g.setColor(Color.WHITE);
        g.fillRect(
            (int) pf.getImageableX(),
            (int) pf.getImageableY(),
            (int) pf.getImageableWidth(),
            (int) pf.getImageableHeight());
        g.setFont(printFont);
        g.setColor(Color.BLACK);
        for (int i = 0; i < linesPerPage; i++) {
          if (startLine >= allStrings.length) break;
          String fullLine = allStrings[startLine];

          // figure bounding box of text
          int endChar = fullLine.length();
          String theLine = null;
          for (; ; ) {
            theLine = fullLine.substring(startChar, endChar);
            GlyphVector gv = printFont.createGlyphVector(frc, theLine);
            Rectangle2D rasRect = gv.getLogicalBounds();
            if (rasRect.getWidth() <= pf.getImageableWidth()) break;
            endChar--;
            if (endChar <= startChar) break;
          }

          g.drawString(
              theLine,
              (int) pf.getImageableX(),
              (int) pf.getImageableY() + yOffset + (i * fontHeight));
          if (endChar < fullLine.length()) {
            // only did partial line
            startChar = endChar;
          } else {
            // completed the line
            startLine++;
            startChar = 0;
          }
        }
        return Printable.PAGE_EXISTS;
      }
    } else if (context instanceof EditWindow) {
      // only 1 page
      if (page == 0) {
        graphics = g;
        pageFormat = pf;
        if (context.getPrintImage(this) != null) return Printable.PAGE_EXISTS;
      }
    }
    return Printable.NO_SUCH_PAGE;
  }