![]() |
drucken eines textes in java hallo ich möchte einen text oder eine textdatei in java mit einem druckdialog ausdrucken. hätte da jemand einen beispielcode? danke. |
AW: drucken eines textes in java Um nicht einen neuen Thread zu öffnen :-D: Ich will auch von einer Java Applikation aus drucken. Genauer gesagt: Ich hab ne Textarea "[b]taContent[/b]" mit einem mehrzeiligen Text. Wie kann ich diesen nun ausdrucken. Hab es schon über die Klasse DocPrint versucht, indem ich als PrintObject einen String übergeben habe, in dem der ganze Text drinsteht. Hat aber nicht geklappt. Er kompiliert zwar alles ohne Fehler, aber wenn ich Auf den Button "Drucken" drücke, dann tut sich nix. Hier der Code: [CODE] String content = taContent.getText(); try { PrintService service = PrintServiceLookup.lookupDefaultPrintService(); DocPrintJob job = service.createPrintJob(); DocFlavor flavor = DocFlavor.STRING.TEXT_PLAIN; Doc doc = new SimpleDoc(content, flavor, null); job.print(doc,null); } catch(PrintException e) {}[/CODE] Auch über die Klasse Print hab ich es versucht. Hier hat er sogar den Inhalt gedruckt, allerdings ohne Leerzeichen und ohne Absätze, also alle Zeichen zusammenhängend. Hier der Code: [CODE]Toolkit tk = Toolkit.getDefaultToolkit(); PrintJob pj = tk.getPrintJob( new Frame(), "", null ); pj.getPageDimension(); pj.getPageResolution(); Graphics printContent = pj.getGraphics(); printContent.drawString(content,30,40); printContent.dispose();[/CODE] Hat jemand eine Idee wie man den Text in der Textarea ausdrucken kann? |
AW: drucken eines textes in java Moin, die Files im Paket javax.print sehen dazu ganz interessant aus. Hier eine kleine Beschreibung vom Interface PrintService: [CODE] DocFlavor flavor = DocFlavor.INPUT_STREAM.POSTSCRIPT; PrintRequestAttributeSet aset = new HashPrintRequestHashAttributeSet(); aset.add(MediaSizeName.ISO_A4); PrintService[] pservices = PrintServiceLookup.lookupPrintServices(flavor, aset); if (pservices.length > 0) { DocPrintJob pj = pservices[0].createPrintJob(); // InputStreamDoc is an implementation of the Doc interface // Doc doc = new InputStreamDoc("test.ps", flavor); try { pj.print(doc, aset); } catch (PrintException e) { } }[/CODE] Die Frage wäre demnach, ob es einfacher ist, das Ding erst als Postscript zu verpacken, oder dem PrintService beizubringen, das der plain text druckt. Wie kompliziert sieht den deine "textfile" aus - sicher nur plain text, oder? edit: Code samples scheinen hier auch zu finden zu sein: [url]http://tech-www.informatik.uni-hamburg.de/personal/hendrich/java-fuer-fortgeschrittene/[/url] [url]http://www.galileocomputing.de/openbook/javainsel3/javainsel_140016.htm#Rxxjavainsel_140016256Drucken[/url] |
AW: drucken eines textes in java [QUOTE=tele] Wie kompliziert sieht den deine "textfile" aus - sicher nur plain text, oder?[/QUOTE] Jap, so ist es :) Danke für den Code. Werde es gleich mal checken. |
AW: drucken eines textes in java Stopp! Das erste mal das ich einen groben FEhler in der Java Doc finde es heißt natürlich nicht PrintRequestAttributeSet aset = new HashPrintRequestHashAttributeSet(); sondern PrintRequestAttributeSet aset = new HashPrintRequestAttributeSet(); |
AW: drucken eines textes in java Ich habe es vor paar Jahren, zu meinen Java-Zeiten, auch mal versucht... ein Krampf, Text & Bilder schickt formatiert zu drucken. :kotzi: |
AW: drucken eines textes in java So, also der Code von Dir, tele, hat mir sehr geholfen. Zwar kann ich noch nicht drucken, aber ich denke mit deinem Code bin ich viel näher dran als vorher. Hab nur ein/zwei Konstanten geändert. ([b]tele & co können jetzt unten weiterlesen[/b]):mrgreen: [b] ------------------------------------------------------------------------------------------------------[/b] Für die anderen Leute die in diesem Thread noch nach ner Anleitung suchen geb ich mal meinen Zwischenstand an: Also erstmal die diversen import Anweisungen: [CODE]import javax.print.*; import javax.print.DocFlavor.STRING; import javax.print.attribute.*; import javax.print.attribute.standard.*;[/CODE] Dann meine Methode printJob(): [CODE]public void printJob() throws PrinterException { String content = taContent.getText(); DocFlavor flavor = DocFlavor.INPUT_STREAM.TEXT_PLAIN_US_ASCII; PrintRequestAttributeSet aset = new HashPrintRequestAttributeSet(); aset.add(MediaSizeName.ISO_A4); PrintService[] pservices = PrintServiceLookup.lookupPrintServices(flavor, aset); if (pservices.length > 0) { DocPrintJob pj = pservices[0].createPrintJob(); // InputStreamDoc is an implementation of the Doc interface // Doc doc = new InputStreamDoc(content, flavor); try { pj.print(doc, aset); } catch (PrintException e) { } } }[/CODE] Und dann noch meine neue Klasse inputStreamDoc: [CODE]import javax.print.*; import javax.print.DocFlavor.STRING; import javax.print.attribute.*; import javax.print.attribute.standard.*; import java.io.*; class InputStreamDoc implements Doc { private String filename; private DocFlavor docFlavor; private InputStream stream; public InputStreamDoc(String name, DocFlavor flavor) { filename = name; docFlavor = flavor; } public DocFlavor getDocFlavor() { return docFlavor; } /* No attributes attached to this Doc - mainly useful for MultiDoc */ public DocAttributeSet getAttributes() { return null; } /* Since the data is to be supplied as an InputStream delegate to * getStreamForBytes(). */ public Object getPrintData() throws IOException { return getStreamForBytes(); } /* Not possible to return a GIF as text */ public Reader getReaderForText() throws UnsupportedEncodingException, IOException { return null; } /* Return the print data as an InputStream. * Always return the same instance. */ public InputStream getStreamForBytes() throws IOException { synchronized(this) { if (stream == null) { stream = new FileInputStream(filename); } return stream; } } }[/CODE] Wie gesagt, es funktioniert noch nicht, aber ich denke es müsste schon ungefähr so laufen *hoff*;) ------------------------------------------------------------------------------------------------------ Aber noch ne Frage (sorry falls die dumm klingt): In der Methode printJob() hab ich folgende Zeile: [CODE]Doc doc = new InputStreamDoc(content, flavor);[/CODE] Die Variable content ist ja der String der den Text enthält. Aber der ist doch da falsch stimmts? Ich denke ich kann da keinen String übergeben. tele macht es ja mit einer Datei "test.ps". Frage: Ich muss also den Text aus der Textarea erst in einem neuen File (z.B. "printTemp.txt") abspeichern und dann dieses File in der Anweisung angeben, oder? |
AW: drucken eines textes in java Hm, hab das Problem gefunden, aber nicht gelöst :mrgreen:: Es heißt ja: [CODE]PrintService[] pservices = PrintServiceLookup.lookupPrintServices(flavor, aset); if (pservices.length > 0) {[/CODE] Wenn ich mir dann mal pservices.length ausgeben lasse: [CODE]System.out.println(pservices.length);[/CODE] dann ist das Ergebnis 0. Tja klar dass er dann nicht anfängt zu drucken. Dann wollen wir mal schaun wie sich das Prob lösen lässt:cool:. Achja, in der API steht dazu folgendes: [CODE] [b] lookupPrintServices[/b] public static final [url="file:///C:/Programme/Java/API/docs/api/javax/print/PrintService.html"]PrintService[/url][] [b]lookupPrintServices[/b]([url="file:///C:/Programme/Java/API/docs/api/javax/print/DocFlavor.html"]DocFlavor[/url] flavor, [url="file:///C:/Programme/Java/API/docs/api/javax/print/attribute/AttributeSet.html"]AttributeSet[/url] attributes) Locates print services capable of printing the specified [url="file:///C:/Programme/Java/API/docs/api/javax/print/DocFlavor.html"]DocFlavor[/url]. [b]Parameters:[/b][list][*]flavor - the flavor to print. If null, this constraint is not used.[*]attributes - attributes that the print service must support. If null this constraint is not used.[/list][b] Returns:[/b] array of matching PrintService objects representing print services that support the specified flavor attributes. If no services match, the array is zero-length. [/CODE] |
AW: drucken eines textes in java Ah mein alter Thread ;-) Da war damals ein Murks. Eventuell hilft das: [code]import java.*; import java.awt.*; import java.awt.GraphicsEnvironment; import java.io.*; import java.io.File; import javax.swing.*; import javax.swing.filechooser.FileFilter; import javax.print.*; import javax.print.attribute.*; import javax.print.attribute.standard.*; import javax.print.attribute.*; import javax.print.event.*; import javax.print.event.PrintJobListener; import javax.print.event.PrintJobEvent; public class Ergebnis { // Drucken des Ergebnisses static void drucken (PrintJob pjob, Graphics pg, String s) { int pageNum = 1; int linesForThisPage = 0; int linesForThisJob = 0; // Note: String is immutable so won't change while printing. if (!(pg instanceof PrintGraphics)) { throw new IllegalArgumentException ("Graphics context not PrintGraphics"); } StringReader sr = new StringReader (s); LineNumberReader lnr = new LineNumberReader (sr); String nextLine; int pageHeight = pjob.getPageDimension().height; int pageWidth = pjob.getPageDimension().width; Font helv = new Font("Helvetica", Font.PLAIN, 9); //have to set the font to get any output pg.setFont (helv); FontMetrics fm = pg.getFontMetrics(helv); int fontHeight = fm.getHeight(); int fontDescent = fm.getDescent(); int curHeight = 40; try { do { nextLine = lnr.readLine(); if (nextLine != null) { if ((curHeight + fontHeight) > (pageHeight-30)) { // New Page Eventlog.add ("" + linesForThisPage + " lines printed for page " + pageNum +"\n"); pageNum++; linesForThisPage = 0; pg.dispose(); pg = pjob.getGraphics(); if (pg != null) { pg.setFont (helv); } curHeight = 40; } curHeight += fontHeight; if (pg != null) { String prefix=""; while (fm.stringWidth(nextLine)>(pageWidth-100)) { while (nextLine.indexOf("\t")!=-1) { nextLine=nextLine.replaceFirst("\t"," "); prefix+=" "; } String templine=nextLine; while(fm.stringWidth(templine)>(pageWidth-100)) { if (templine.lastIndexOf(' ')!=-1) { templine=templine.substring(0,templine.lastIndexOf(' ')); } else { templine=templine.substring(0,templine.length()-1); } } pg.drawString (templine, 40, curHeight - fontDescent); nextLine=prefix + " " + nextLine.substring(templine.length()); linesForThisPage++; linesForThisJob++; curHeight += fontHeight; } pg.drawString (nextLine.replaceAll("\t"," "), 40, curHeight - fontDescent); linesForThisPage++; linesForThisJob++; } else { Eventlog.add ("pg null" +"\n"); } } } while (nextLine != null); } catch (EOFException eof) {Eventlog.add(eof.toString() +"\n");} catch (Throwable t) {Eventlog.add(t.toString() +"\n");} Eventlog.add ("" + linesForThisPage + " lines printed for page " + pageNum +"\n"); Eventlog.add ("pages printed: " + pageNum +"\n"); Eventlog.add ("total lines printed: " + linesForThisJob +"\n"); } }[/code] |
AW: drucken eines textes in java Hi Guys! Also erstmal danke nochmal für eure Hilfe und die supi Codebeispiele :respekt:. @ Smash: Ich hab deinen Code grad mal eingebunden und durchrattern lassen --> Ergebnis:[list=1][*]Compiler hat nicht gemeckert[*]Programm wurde ordnungsgemäß ausgeführt.[*]Als ich dann auf den Drucken Button geklickt habe, kam der bekannte Druckerauswahl-Dialog. Dann geh ich auf "OK" und es passiert sogar was: Es wird ein Druckauftrag erstellt, allerdings mit dem Status "In Warteschlange". Und dabei bleibt es auch. Er wird nicht ausgedruckt.[/list]Aber immerhin, das ist auch schon was. Bin echt happy, denn vor paar Tagen kam ich nicht mal halb so weit. Ich bleib dran und such weiter nach ner Lösung. Falls ihr das Prob kennt, dann könnt ihr ja 1 oder 2 Zeilen schreiben :jump:. |
AW: drucken eines textes in java Versuche grad den Fehler zu finden. Hab dabei ein Verständnisproblem bei "Eventlog". Es ist anscheinend eine Möglichkeit Exceptions auszugeben, allerdings meckert mich der Compiler an und sagt: "Eventlog cannot be resolved". Ich muss es also irgendwie noch einbinden. Finde aber keine Möglichkeit wie: Google sagt: [url="http://publib.boulder.ibm.com/iseries/v5r1/ic2924/info/rzahh/javadoc/com/ibm/as400/access/EventLog.html"]KLICK[/url] Um den Code zu testen hab ich es mal auskommentiert. Ich brauch doch Eventlog auch nicht zwingend oder? [b]@ Smash:[/b] Konntest du mit diesem Code drucken und wenn ja, wie sieht Dein Aufruf der Methode "static void drucken (PrintJob pjob, Graphics pg, String s)" aus? |
AW: drucken eines textes in java Hihi, das hatte ich nicht bedacht ;-) Eventlog ist ne Eigenimplementierung. Ne ganz billige Klasse, die nur Strings speichert. [code] import java.io.*; import java.io.File; /** * Diese Klasse fängt alle Exceptions und sonstige Ausgaben auf und * schreibt sie am Ende des Programms in ein Event-Log. * Sie speichert außerdem den Fortschritt des Parse-Vorgangs. * * @author _Smash_ */ public class Eventlog { public static StringBuffer fehler = new StringBuffer(); public static StringBuffer log = new StringBuffer(); // Hinzufügen eines Events public static void add(String string) { fehler.append(string); } // Hinzufügen eines Logs public static void addlog(String string) { log.append(string); System.out.print(string); } // Erzeugen der Log-Datei public static void print() { try { PrintWriter w = new PrintWriter(new FileWriter("eventlog.txt")); w.print(fehler.toString().replaceAll("\n",System.getProperty("line.separator"))); w.flush(); w.close(); } catch (IOException ioe) {;} // Kein Handling, da es selber die Exceptions abspeichert } } [/code] Ja das hat tatsächlich mal gedruckt. Hab hier auch den aufrufenden Code [code] import java.lang.Object.*; import javax.swing.*; import javax.swing.filechooser.FileFilter; import java.io.*; import java.io.File; import java.awt.*; import java.awt.print.*; import java.awt.event.*; import java.util.*; import java.util.Properties; Properties props = new Properties(); PrintJob pjob = getToolkit().getPrintJob(this, "Cool Stuff", props); if (pjob != null) { Graphics pg = pjob.getGraphics(); if (pg != null) { String s = buffer.toString(); Ergebnis.drucken (pjob, pg, s); pg.dispose(); } pjob.end(); } [/code] Die Imports wirst du nicht alle brauchen. Sorry, daß ich nicht gleich alles dabei hatte, aber das ist immerhin 2 Jahre her und das stammt auch nicht von mir (von nem Kommilitonen mit dem ich das gemacht habe) ;-) Versuchs jetzt mal ;-) |
AW: drucken eines textes in java kann das sein, das das untere "leicht" unvollständig ist? ;) |
AW: drucken eines textes in java Was soll da fehlen? Klar ist da die Funktion aus der es aufgerufen wird nicht dabei, aber das ist das eigentlich. Na guuuuut. [code] private void jButton3MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jButton3MouseClicked // Drucken des Ergebnisses // Erzeugen des PrintJob und Übergabe der Parameter an die Druck.Methode PrintJob pjob = getToolkit().getPrintJob(this, "Cool Stuff", props); if (pjob != null) { Graphics pg = pjob.getGraphics(); if (pg != null) { String s = buffer.toString(); Ergebnis.drucken (pjob, pg, s); pg.dispose(); } pjob.end(); } }//GEN-LAST:event_jButton3MouseClicked [/code] Aber dadurch wird das auch nicht besser ;-) Die Includes und das props Ding halt da noch rein. |
AW: drucken eines textes in java Für alle die an Smashs Schnipseln verzweifeln hier mal ne Tech-Demo: [code] /* * Created on 17.02.2006 */ package printTest; import java.awt.Font; import java.awt.FontMetrics; import java.awt.Graphics; import java.awt.PrintGraphics; import java.awt.PrintJob; import java.awt.Toolkit; import java.io.EOFException; import java.io.FileWriter; import java.io.IOException; import java.io.LineNumberReader; import java.io.PrintWriter; import java.io.StringReader; import java.util.Properties; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.JTextArea; import java.awt.BorderLayout; /** * @author tele * @version 1 */ public class PrintTestWithGui extends JFrame { private static final long serialVersionUID = -8464163353847080220L; private JPanel jPanel = null; private JButton jButton = null; private JButton smashPrintButton = null; private JTextArea jTextArea = null; private Eventlog logger = null; /** * This method initializes */ public PrintTestWithGui() { super(); initializeEventLog(); initialize(); } private void initializeEventLog() { logger = new Eventlog(); } /** * This method initializes this */ private void initialize() { this.setSize(new java.awt.Dimension(297,273)); this.setContentPane(getJPanel()); this.setDefaultCloseOperation(javax.swing.JFrame.EXIT_ON_CLOSE); this.setTitle("Print Tester with GUI"); this.setVisible(true); } // --------------------------------------- GUI Getters -------------------------- protected JFrame getJFrame() { return this; } /** * This method initializes jPanel * @return javax.swing.JPanel */ private JPanel getJPanel() { if (jPanel == null) { jPanel = new JPanel(); jPanel.setLayout(new BorderLayout()); jPanel.add(getJButton(), java.awt.BorderLayout.NORTH); jPanel.add(getSmashPrintButton(), java.awt.BorderLayout.SOUTH); jPanel.add(getJTextArea(), java.awt.BorderLayout.CENTER); } return jPanel; } /** * This method initializes jButton * @return javax.swing.JButton */ private JButton getJButton() { if (jButton == null) { jButton = new JButton(); jButton.setText("Print JFrame"); jButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent e) { action(); } }); } return jButton; } /** * This method initializes smashPrintButton * * @return javax.swing.JButton */ protected JButton getSmashPrintButton() { if (smashPrintButton == null) { smashPrintButton = new JButton(); smashPrintButton.setText("Smash's Text Print"); smashPrintButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent e) { doSmashPrint(); } }); } return smashPrintButton; } /** * This method initializes jTextArea * @return javax.swing.JTextArea */ protected JTextArea getJTextArea() { if (jTextArea == null) { jTextArea = new JTextArea(); } return jTextArea; } // --------------------------------- druck Methoden --------------------------- /** * this method prints the curren JFrame * @return */ public boolean action() { Toolkit toolKit = Toolkit.getDefaultToolkit(); Properties properties = new Properties(); PrintJob printJob = toolKit.getPrintJob( this, "Print", properties ); if (printJob != null) { System.out.println( "Auflösung des Druckers: " + printJob.getPageResolution() + " dpi, Seitengröße " + printJob.getPageDimension().width + " " + printJob.getPageDimension().height + " DruckerName: " + properties.getProperty( "awt.print.printer" )); System.out.println( "Properties: " ); properties.list( System.out ); System.getProperties().list( System.out ); Graphics pg = printJob.getGraphics(); if (pg != null) { printAll(pg); pg.dispose(); } printJob.end(); return true; } return false; } /** * Smash's Print Stuff */ protected void doSmashPrint(){ System.out.println("actionPerformed()"); StringBuffer buffer = new StringBuffer(getJTextArea().getText()); Properties props = new Properties(); PrintJob pjob = getSmashPrintButton().getToolkit().getPrintJob(getJFrame(), "Cool Stuff", props); if (pjob != null) { Graphics pg = pjob.getGraphics(); if (pg != null) { String s = buffer.toString(); drucken(pjob, pg, s); pg.dispose(); } pjob.end(); } } /** * eigentliche druck funktion für den text * @param pjob * @param pg * @param s */ protected void drucken(PrintJob pjob, Graphics pg, String s) { int pageNum = 1; int linesForThisPage = 0; int linesForThisJob = 0; // Note: String is immutable so won't change while printing. if (!(pg instanceof PrintGraphics)) { throw new IllegalArgumentException("Graphics context not PrintGraphics"); } StringReader sr = new StringReader(s); LineNumberReader lnr = new LineNumberReader(sr); String nextLine; int pageHeight = pjob.getPageDimension().height; int pageWidth = pjob.getPageDimension().width; Font helv = new Font("Helvetica", Font.PLAIN, 9); // have to set the font to get any output pg.setFont(helv); FontMetrics fm = pg.getFontMetrics(helv); int fontHeight = fm.getHeight(); int fontDescent = fm.getDescent(); int curHeight = 40; try { do { nextLine = lnr.readLine(); if (nextLine != null) { if ((curHeight + fontHeight) > (pageHeight - 30)) { // New Page // Eventlog.add ("" + linesForThisPage + " lines // printed for page " + pageNum +"\n"); pageNum++; linesForThisPage = 0; pg.dispose(); pg = pjob.getGraphics(); if (pg != null) { pg.setFont(helv); } curHeight = 40; } curHeight += fontHeight; if (pg != null) { String prefix = ""; while (fm.stringWidth(nextLine) > (pageWidth - 100)) { while (nextLine.indexOf("\t") != -1) { nextLine = nextLine.replaceFirst("\t", " "); prefix += " "; } String templine = nextLine; while (fm.stringWidth(templine) > (pageWidth - 100)) { if (templine.lastIndexOf(' ') != -1) { templine = templine.substring(0, templine.lastIndexOf(' ')); } else { templine = templine.substring(0, templine.length() - 1); } } pg.drawString(templine, 40, curHeight - fontDescent); nextLine = prefix + " " + nextLine.substring(templine.length()); linesForThisPage++; linesForThisJob++; curHeight += fontHeight; } pg.drawString(nextLine.replaceAll("\t", " "), 40, curHeight - fontDescent); linesForThisPage++; linesForThisJob++; } else { logger.add("pg null" + "\n"); } } } while (nextLine != null); } catch (EOFException eof) { logger.add(eof.toString() + "\n"); } catch (Throwable t) { logger.add(t.toString() + "\n"); } logger.add("" + linesForThisPage + " lines printed for page " + pageNum + "\n"); logger.add("pages printed: " + pageNum + "\n"); logger.add("total lines printed: " + linesForThisJob + "\n"); } // ---------------------------------------------- static Methods ------------------ /** * @param args */ public static void main(String[] args) { new PrintTestWithGui(); } } /** * Eventlog * @author _Smash_ * @version 1 */ class Eventlog { public static StringBuffer fehler = new StringBuffer(); public static StringBuffer log = new StringBuffer(); // Hinzufügen eines Events public void add(String string) { fehler.append(string); } // Hinzufügen eines Logs public void addlog(String string) { log.append(string); System.out.print(string); } // Erzeugen der Log-Datei public void print() { try { PrintWriter w = new PrintWriter(new FileWriter("eventlog.txt")); w.print(fehler.toString().replaceAll("\n", System.getProperty("line.separator"))); w.flush(); w.close(); } catch (IOException ioe) { ; } // Kein Handling, da es selber die Exceptions abspeichert } } [/code] |
AW: drucken eines textes in java Danke für eure Hilfe. Das Drucken klappt jetzt, allerdings mit einer Einschränkung. Wenn ich über die DIN A4 Seitenbreite hinauskomme, dann hängt sich das Programm beim drucken auf. Also horizontal klappts nicht, aber mehrere Seiten druckt er ohne Probleme. :denker: Ich hab jetzt mal versucht die JTextArea auf DIN A4 zu verkleinern, so dass er automatisch eine neue Zeile beginnt, wenn er an den Rand von DIN A4 kommt. Allerdings hab ich bis jetzt nur den Weg über den Konstruktor der JTextArea gefunden. [CODE] public [b]JTextArea[/b](int rows, int columns) Constructs a new empty TextArea with the specified number of rows and columns. A default model is created, and the initial string is null.[/CODE] Hat aber leider nicht funktioniert. Weder das Drucken noch die Begrenzung im Programm selbst. -------------------------------- EDIT: @ tele: Ich würd dich ja auch gerne pos. bewerten, aber ich "muss leider erst einige andere Benutzer bewerten, bevor ich dich wieder bewerten kann".:cool: |
AW: drucken eines textes in java Hast du in deinem jetztigen Programm eine Zeile ähnlich derer: [code] // kompletter Code siehe erste Seite/Thread aset.add(MediaSizeName.ISO_A4);[/code] drin? ÜBer die JTextArea wird das nicht gehen, da die ja nicht dafür da ist - die ist ein Gui Element und hat eigentlich nur über das Toolkit eine Verbindung zur Druckfunktionalität vielleicht mal in den links stöbern, die ich zu Beginn gepostet hatte, da war eine Preview demo dabei - die könnte helfen |
AW: drucken eines textes in java Hm, jo, habs versucht, aber das Prob ist, dass ich ja die Klassen Graphics und PrintJob (nicht mit PrinterJob verwechseln) verwende. Ich kann also aset meines Erachtens nach nicht übergeben, da die 2 Klassen keine Möglichkeit anbieten, Attribute wie aset zu "akzeptieren". Aber ich versuchs natürlich weiter. PS: Im Code wird die Seitenbreite ja auch abgefragt [CODE]int pageWidth = pjob.getPageDimension().width;[/CODE] Aber das gibt die Breite nur in Pixeln an, was wohl zu dem Fehler führen könnte. Später im Code steht dann: [CODE]while (fm.stringWidth(nextLine) > (pageWidth - 100)) {...[/CODE] Ich hab mal den Wert 100 auf 200 hochgesetzt, und dann hat er sogar gedruckt. Allerdings hat er keine neue Zeile angefangen, sondern quasi den Rest einfach abgeschnitten. ;) |
AW: drucken eines textes in java Ach sorry- hatte auf der ersten Seite überhaupt nicht das verlinkt was ich meinte. Guck dir mal das [URL=http://www.java.de/article/articleview/117/1/1]hier[/URL] an - vielleicht hilfts ja. |
AW: drucken eines textes in java Hallo, habe das Problem gelöst. Vielen Dank an Smash & tele für die super Hilfe. ;) Geholfen hat mir folgendes Tutorial: [url="http://www.javaworld.com/javaworld/jw-10-2000/jw-1020-print.html"]LINK[/url] Wer es nicht durcharbeiten will, der kann es ja mit meiner Lösung versuchen. Diese ist aus diesem Tutorial (Listing 4), wobei ich den Code an mein Programm angepasst habe. -------------------------------------------------------------------------------- [b]Lösung[/b] Um einen Text zu drucken, könnt ihr folgendes tun: 1. Implementiert die Klasse "Print" in euer Projekt: [CODE] /** * @author Jean-Pierre Dube <jpdube@videotron.ca> * @version 1.0 * @since 1.0 */ import java.awt.*; import java.awt.font.*; import java.awt.geom.*; import java.awt.print.*; import java.text.*; public class Print { //--- Private instances declarations private final static int POINTS_PER_INCH = 72; private static String text = new String(); /** * Constructor * */ public Print(String content) { //--- String content includes the Text, which should be printed text = content; //--- Create a new PrinterJob object PrinterJob printJob = PrinterJob.getPrinterJob (); //--- Create a new book to add pages to Book book = new Book (); //--- Add the document page using a landscape page format PageFormat documentPageFormat = new PageFormat (); documentPageFormat.setOrientation (PageFormat.PORTRAIT); book.append (new Document (), documentPageFormat); //--- Tell the printJob to use the book as the pageable object printJob.setPageable (book); //--- Show the print dialog box. If the user click the //--- print button we then proceed to print else we cancel //--- the process. if (printJob.printDialog()) { try { printJob.print(); } catch (Exception PrintException) { PrintException.printStackTrace(); } } } private class Document implements Printable { /** * Method: print <p> * * @param g a value of type Graphics * @param pageFormat a value of type PageFormat * @param page a value of type int * @return a value of type int */ public int print (Graphics g, PageFormat pageFormat, int page) { //--- Create the Graphics2D object Graphics2D g2d = (Graphics2D) g; //--- Translate the origin to 0,0 for the top left corner g2d.translate (pageFormat.getImageableX (), pageFormat.getImageableY ()); //--- Set the drawing color to black g2d.setPaint (Color.black); //--- Create a point object to set the top left corner of the TextLayout object Point2D.Double pen = new Point2D.Double (0.25 * POINTS_PER_INCH, 0.25 * POINTS_PER_INCH); //--- Set the width of the TextLayout box double width = 6.0 * POINTS_PER_INCH; //--- Create an attributed string from the text string. We are creating an //--- attributed string because the LineBreakMeasurer needs an Iterator as //--- parameter. AttributedString paragraphText = new AttributedString (text); //--- Set the font for this text paragraphText.addAttribute (TextAttribute.FONT, new Font ("serif", Font.PLAIN, 12)); //--- Create a LineBreakMeasurer to wrap the text for the TextLayout object //--- Note the second parameter, the FontRendereContext. I have set the second //--- parameter antiAlised to true and the third parameter useFractionalMetrics //--- to true to get the best possible output LineBreakMeasurer lineBreaker = new LineBreakMeasurer (paragraphText.getIterator(), new FontRenderContext (null, true, true)); //--- Create the TextLayout object TextLayout layout; //--- LineBreakMeasurer will wrap each line to correct length and //--- return it as a TextLayout object while ((layout = lineBreaker.nextLayout ((float) width)) != null) { //--- Align the Y pen to the ascend of the font, remember that //--- the ascend is origin (0, 0) of a font. Refer to figure 1 pen.y += layout.getAscent (); //--- Draw the line of text layout.draw (g2d, (float) pen.x, (float) pen.y); //--- Move the pen to the next position adding the descent and //--- the leading of the font pen.y += layout.getDescent () + layout.getLeading (); } //--- Validate the page return (PAGE_EXISTS); } } } // Print[/CODE] 2. Nun noch die aufrufende Methode in euer Programm einbinden Meine sieht so aus: [CODE]public void printJob() { // content wird der Text der JTextArea "taContent" zugewiesen String content = taContent.getText(); //Nun wird dieser String an die Klasse "Print" übergeben, die diesen ausdruckt Print printdoc = new Print(content); }[/CODE] So, dass wars. Viel Spaß beim drucken. |
| Alle Zeitangaben in WEZ +1. Es ist jetzt 08:57 Uhr. |
Powered by vBulletin® Version 3.8.10 (Deutsch)
Copyright ©2000 - 2026, vBulletin Solutions, Inc.
SEO by vBSEO 3.5.2 ©2010, Crawlability, Inc.