Avatar billede ihtezaz Praktikant
20. oktober 2003 - 17:53 Der er 16 kommentarer

Kan nogen vis mig hvordan jeg laver en Udskrift funktion i java

Kan nogen vis mig hvordan jeg laver en Udskrift funktion i java, i må meget gerne giv eksempler. 80 points hvis det noget der virker.
Avatar billede ihtezaz Praktikant
20. oktober 2003 - 17:55 #1
altså udskrift til en printer.
Avatar billede popsy Novice
20. oktober 2003 - 17:57 #2
Avatar billede popsy Novice
20. oktober 2003 - 17:57 #3
<Input type="button" name="kanp" value="Udskriv" onClick="Print();">

<Script language="JavaScript">
function Print()
{
window.print();
}
</Script>
Avatar billede arne_v Ekspert
20. oktober 2003 - 17:57 #4
Meget simpelt eksempel:

package test;

import java.awt.*;
import java.awt.print.*;

class PrinTest {

    public static void main(String[] args) {
        PrinterJob job = PrinterJob.getPrinterJob();
        Book bk = new Book();
        bk.append(new Printable() {
            public int print(Graphics g, PageFormat page, int index) {
                page.setOrientation(PageFormat.LANDSCAPE);
                g.drawString("Dette er en test", 100, 100);
                return 0;

            }
        }, job.defaultPage());
        job.setPageable(bk);
        if (job.printDialog()) {
            try {
                job.print();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

    }

}
Avatar billede arne_v Ekspert
20. oktober 2003 - 17:58 #5
popsy>

Har du bemærket kategorien ?
Avatar billede popsy Novice
20. oktober 2003 - 17:59 #6
åh for f*****

Sorry, går sq tidligt i seng endnu engang :(
Avatar billede magoo20000 Nybegynder
21. oktober 2003 - 16:06 #7
Lidt mere her:

import java.awt.*;
import java.awt.print.*;
import java.io.*;
import java.net.*;
import java.util.ArrayList;
import java.util.List;

public class TextPrinter implements Pageable, Printable, Serializable {

    private String defaultFontFamily = "Monospaced";
    private int defaultFontStyle = Font.PLAIN;
    private int defaultFontSize = 10;
    private float lineSpaceFactor = 1.2f;
    private int lineSpacing;
    private int linesPerPage;
    private int numberOfPages;
    private int baseline = -1;
    private PageFormat pageFormat;
    private Font font;
    private List lines;

    public TextPrinter( String text, PageFormat pageFormat ) throws IOException {
    this( new StringReader( text ), pageFormat );
    } // constructor

    public TextPrinter( File file, PageFormat pageFormat ) throws IOException {
    this( new FileReader( file ), pageFormat );
    } // constructor

    public TextPrinter( Reader reader, PageFormat pageFormat ) throws IOException {
    this.pageFormat = pageFormat;
    BufferedReader breader = new BufferedReader( reader );
    lines = new ArrayList();
    String line;
    while ( ( line = breader.readLine() ) != null ) {
        lines.add( line );
    } // while
    breader.close();
        setFont( new Font( defaultFontFamily, defaultFontStyle, defaultFontSize ) );
    } // constructor

    public void setFont( Font font ) {
    this.font = font;
    lineSpacing = (int)( font.getSize() * lineSpaceFactor );
    linesPerPage = (int)Math.floor( pageFormat.getImageableHeight() / lineSpacing );
    numberOfPages = ( lines.size() - 1 ) / linesPerPage + 1;
    } // setFont

    ////////////////////////////////
    // implementation of Pageable //
    ////////////////////////////////

    public int getNumberOfPages() {
    return numberOfPages;
    } // getNumberOfPages

    public PageFormat getPageFormat( int pageNumber ) {
    return pageFormat;
    } // getPageFormat

    public Printable getPrintable( int pageNumber ) {
    return this;
    } // getPrintable

    /////////////////////////////////
    // implementation of Printable //
    /////////////////////////////////

    public int print( Graphics g, PageFormat pageFormat, int pageNumber ) {
    if ( pageNumber < 0 || pageNumber >= numberOfPages )
        return NO_SUCH_PAGE;
    if ( baseline == -1 ) {
        FontMetrics fm = g.getFontMetrics( font );
        baseline = fm.getAscent();
    } // if
    g.setColor( Color.white );
    g.fillRect( (int)pageFormat.getImageableX(), (int)pageFormat.getImageableY(),
            (int)pageFormat.getImageableWidth(), (int)pageFormat.getImageableHeight() );
    g.setFont( font );
    g.setColor( Color.black );
    int startLine = pageNumber * linesPerPage;
    int endLine = startLine + linesPerPage - 1;
    if ( endLine >= lines.size() ) {
        endLine = lines.size() - 1;
    } // if
    int x0 = (int)pageFormat.getImageableX();
    int y0 = (int)pageFormat.getImageableY();
    y0 += lineSpacing;
    for (int i = startLine; i <= endLine; i++) {
        String line = (String)lines.get( i );
        int index;
        while ( ( index = line.indexOf( "\t" ) ) >= 0 ) {
        line = line.substring( 0, index ) + "    " + line.substring( index + 1 );
        } // while
        if ( line.length() > 0 ) {
        g.drawString( line, x0, y0 );
        } // if
        y0 += lineSpacing;
    } // for
    return PAGE_EXISTS;
    } // print
   
} // TextPrinter

Eller

import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Rectangle;
import java.awt.Shape;
import java.awt.print.PageFormat;
import java.awt.print.Printable;
import java.awt.print.PrinterException;
import java.awt.print.PrinterJob;
import javax.swing.JEditorPane;
import javax.swing.text.Document;
import javax.swing.text.PlainDocument;
import javax.swing.text.View;
import javax.swing.text.html.HTMLDocument;

public class DocumentRenderer implements Printable {

  protected int currentPage = -1;              //Used to keep track of when
                                                //the page to print changes.

  protected JEditorPane jeditorPane;            //Container to hold the
                                                //Document. This object will
                                                //be used to lay out the
                                                //Document for printing.

  protected double pageEndY = 0;                //Location of the current page
                                                //end.

  protected double pageStartY = 0;              //Location of the current page
                                                //start.

  protected boolean scaleWidthToFit = true;    //boolean to allow control over
                                                //whether pages too wide to fit
                                                //on a page will be scaled.

  protected PageFormat pFormat;
  protected PrinterJob pJob;

/*  The constructor initializes the pFormat and PJob variables.
*/
  public DocumentRenderer() {
    pFormat = new PageFormat();
    pJob = PrinterJob.getPrinterJob();
  }

/*  Method to get the current Document
*/
  public Document getDocument() {
    if (jeditorPane != null) return jeditorPane.getDocument();
    else return null;
  }

/*  Method to get the current choice the width scaling option.
*/
  public boolean getScaleWidthToFit() {
    return scaleWidthToFit;
  }

/*  pageDialog() displays a page setup dialog.
*/
  public void pageDialog() {
    pFormat = pJob.pageDialog(pFormat);
  }


  public int print(Graphics graphics, PageFormat pageFormat, int pageIndex) {
    double scale = 1.0;
    Graphics2D graphics2D;
    View rootView;
//  I
    graphics2D = (Graphics2D) graphics;
//  II
    jeditorPane.setSize((int) pageFormat.getImageableWidth(),Integer.MAX_VALUE);
    jeditorPane.validate();
//  III
    rootView = jeditorPane.getUI().getRootView(jeditorPane);
//  IV
    if ((scaleWidthToFit) && (jeditorPane.getMinimumSize().getWidth() >
    pageFormat.getImageableWidth())) {
      scale = pageFormat.getImageableWidth()/
      jeditorPane.getMinimumSize().getWidth();
      graphics2D.scale(scale,scale);
    }
//  V
    graphics2D.setClip((int) (pageFormat.getImageableX()/scale),
    (int) (pageFormat.getImageableY()/scale),
    (int) (pageFormat.getImageableWidth()/scale),
    (int) (pageFormat.getImageableHeight()/scale));
//  VI
    if (pageIndex > currentPage) {
      currentPage = pageIndex;
      pageStartY += pageEndY;
      pageEndY = graphics2D.getClipBounds().getHeight();
    }
//  VII
    graphics2D.translate(graphics2D.getClipBounds().getX(),
    graphics2D.getClipBounds().getY());
//  VIII
    Rectangle allocation = new Rectangle(0,
    (int) -pageStartY,
    (int) (jeditorPane.getMinimumSize().getWidth()),
    (int) (jeditorPane.getPreferredSize().getHeight()));
//  X
    if (printView(graphics2D,allocation,rootView)) {
      return Printable.PAGE_EXISTS;
    }
    else {
      pageStartY = 0;
      pageEndY = 0;
      currentPage = -1;
      return Printable.NO_SUCH_PAGE;
    }
  }

/*  print(HTMLDocument) is called to set an HTMLDocument for printing.
*/
  public void print(HTMLDocument htmlDocument) {
    setDocument(htmlDocument);
    printDialog();
  }

/*  print(JEditorPane) prints a Document contained within a JEDitorPane.
*/
  public void print(JEditorPane jedPane) {
    setDocument(jedPane);
    printDialog();
  }

/*  print(PlainDocument) is called to set a PlainDocument for printing.
*/
  public void print(PlainDocument plainDocument) {
    setDocument(plainDocument);
    printDialog();
  }

/*  A protected method, printDialog(), displays the print dialog and initiates
    printing in response to user input.
*/
  protected void printDialog() {
    if (pJob.printDialog()) {
      pJob.setPrintable(this,pFormat);
      try {
        pJob.print();
      }
      catch (PrinterException printerException) {
        pageStartY = 0;
        pageEndY = 0;
        currentPage = -1;
        System.out.println("Error Printing Document");
      }
    }
  }

  protected boolean printView(Graphics2D graphics2D, Shape allocation,
  View view) {
    boolean pageExists = false;
    Rectangle clipRectangle = graphics2D.getClipBounds();
    Shape childAllocation;
    View childView;

    if (view.getViewCount() > 0) {
      for (int i = 0; i < view.getViewCount(); i++) {
        childAllocation = view.getChildAllocation(i,allocation);
        if (childAllocation != null) {
          childView = view.getView(i);
          if (printView(graphics2D,childAllocation,childView)) {
            pageExists = true;
          }
        }
      }
    } else {
//  I
      if (allocation.getBounds().getMaxY() >= clipRectangle.getY()) {
        pageExists = true;
//  II
        if ((allocation.getBounds().getHeight() > clipRectangle.getHeight()) &&
        (allocation.intersects(clipRectangle))) {
          view.paint(graphics2D,allocation);
        } else {
//  III
          if (allocation.getBounds().getY() >= clipRectangle.getY()) {
            if (allocation.getBounds().getMaxY() <= clipRectangle.getMaxY()) {
              view.paint(graphics2D,allocation);
            } else {
//  IV
              if (allocation.getBounds().getY() < pageEndY) {
                pageEndY = allocation.getBounds().getY();
              }
            }
          }
        }
      }
    }
    return pageExists;
  }

/*  Method to set the content type the JEditorPane.
*/
  protected void setContentType(String type) {
    jeditorPane.setContentType(type);
  }

/*  Method to set an HTMLDocument as the Document to print.
*/
  public void setDocument(HTMLDocument htmlDocument) {
    jeditorPane = new JEditorPane();
    setDocument("text/html",htmlDocument);
  }

  public void setDocument(JEditorPane jedPane) {
    jeditorPane = new JEditorPane();
    setDocument(jedPane.getContentType(),jedPane.getDocument());
  }

/*  Method to set a PlainDocument as the Document to print.
*/
  public void setDocument(PlainDocument plainDocument) {
    jeditorPane = new JEditorPane();
    setDocument("text/plain",plainDocument);
  }

/*  Method to set the content type and document of the JEditorPane.
*/
  protected void setDocument(String type, Document document) {
    setContentType(type);
    jeditorPane.setDocument(document);
  }

/*  Method to set the current choice of the width scaling option.
*/
  public void setScaleWidthToFit(boolean scaleWidth) {
    scaleWidthToFit = scaleWidth;
  }
}
     
Herefter kan du benytte klassen ved f.eks.

DocumentRenderer DocumentRenderer = new DocumentRenderer();
DocumentRenderer.print(xxxxx);

Men hvad er det du vil printe ud?
Avatar billede ihtezaz Praktikant
21. oktober 2003 - 22:44 #8
hej mangoo20000
I forbindelse med min hovedopgave er jeg ved at lave en lille distribuerede system til dette skal jeg lave en funktion der printer en dagrapport ud for en asfaltbelægnings hold. En dagrapport er opdelt i objekter, dvs. at info om medarbejdernes og deres arbejdstid er en klasse, info om formanden og hans arbejdstid er en klasse. Men disse skal kunne printes ud som hel dagrapport for dagens arbejde.
Avatar billede ihtezaz Praktikant
22. oktober 2003 - 13:23 #9
arne_v, hvad skal jeg gøre for at kunne printe på flere linie ?
For når jeg printer en lang tekst, printer den ikke hele linien ud.
Avatar billede arne_v Ekspert
22. oktober 2003 - 15:00 #10
I mit eksemple angiver man jo x og y koordinater. Så jeg forstår ikke helt ...
Avatar billede ihtezaz Praktikant
22. oktober 2003 - 18:35 #11
ja men hvad gøre jeg hvis jeg har en sætning på 5 linier jeg vil hav skrevet ud på printeren. for x og y kordinaterne kan så vidt jeg har erfaret kun bruges til den ene og samme linie.
Avatar billede arne_v Ekspert
22. oktober 2003 - 18:38 #12
Øh.

Forskellige drawString med forskellige y værdier bliver vel til forskellige
linier ?
Avatar billede ihtezaz Praktikant
22. oktober 2003 - 18:45 #13
Ok, sorry det logisk, jeg tror jeg er lidt træt i hovedet. Dog er det en lidt besværlig måde, selv at sørg for linieskift.
Avatar billede arne_v Ekspert
22. oktober 2003 - 18:55 #14
Ja.

Udover java.awt.print er der også en anden package javax.print, men
den kender jeg slet ikke noget til.
Avatar billede ihtezaz Praktikant
22. oktober 2003 - 18:58 #15
ok, med tak for din hjælp, jeg husker dig ved point uddelingen.
Avatar billede arne_v Ekspert
22. oktober 2003 - 19:02 #16
Avatar billede Ny bruger Nybegynder

Din løsning...

Tilladte BB-code-tags: [b]fed[/b] [i]kursiv[/i] [u]understreget[/u] Web- og emailadresser omdannes automatisk til links. Der sættes "nofollow" på alle links.

Loading billede Opret Preview
Kategori
Kurser inden for grundlæggende programmering

Log ind eller opret profil

Hov!

For at kunne deltage på Computerworld Eksperten skal du være logget ind.

Det er heldigvis nemt at oprette en bruger: Det tager to minutter og du kan vælge at bruge enten e-mail, Facebook eller Google som login.

Du kan også logge ind via nedenstående tjenester