tutorials.de Buch-Aktion 05/2012
Like Tree1Danke
  • 1 Beitrag von flashray
ERLEDIGT
NEIN
ANTWORTEN
1
ZUGRIFFE
3776
EMPFEHLEN
  • An Twitter übertragen
  • An Facebook übertragen
AUF DIESES THEMA
ANTWORTEN
  1. #1
    flashray flashray ist offline Mitglied Rubin
    Registriert seit
    Sep 2005
    Ort
    Mannheim
    Beiträge
    1.325
    Hallo Freunde,

    habe es nun nach intensiver Schwerstarbeit geschafft, eine Klasse zu schreiben die einen beliebigen String inklusive aller Formatierungsmöglichkeiten die ein JTextArea erlaubt mehrseitig auszudrucken, auch ist die Druckqualität akzeptabel.

    Wenn sich auch schon jemand mit dem Thema auseinandergesetzt hat, würde ich gerne die eine oder andere Erfahrung hören. Was würdet ihr beispielsweise anders implementieren?

    Für Leute die bisher zu diesem Thema keine Lösung gefunden haben, wäre das ein möglicher Ansatz .


    Code java:
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    131
    132
    133
    134
    135
    136
    137
    138
    139
    140
    141
    142
    143
    144
    145
    146
    147
    148
    149
    150
    151
    152
    153
    154
    155
    156
    157
    158
    159
    160
    161
    162
    163
    164
    165
    166
    167
    168
    169
    170
    171
    172
    173
    174
    175
    176
    177
    178
    179
    180
    181
    182
    183
    184
    185
    186
    187
    188
    189
    190
    191
    192
    193
    194
    195
    196
    197
    198
    199
    200
    201
    202
    203
    204
    205
    206
    207
    208
    209
    210
    211
    212
    213
    214
    215
    216
    217
    218
    219
    220
    221
    222
    223
    224
    225
    226
    227
    228
    229
    230
    231
    232
    233
    234
    235
    236
    237
    238
    239
    240
    241
    242
    243
    244
    245
    246
    247
    248
    249
    250
    251
    252
    253
    254
    255
    256
    257
    258
    259
    260
    261
    262
    263
    264
    265
    266
    267
    268
    269
    270
    271
    272
    273
    274
    275
    276
    277
    278
    279
    
    import java.awt.*;
    import java.awt.image.BufferedImage;
    import java.awt.print.*;
    import java.io.PrintStream;
    import java.util.ArrayList;
    import java.util.List;
     
    import javax.swing.*;
    import javax.swing.text.*;
     
    public class PrintTool implements Printable {
     
        // Help //
     
        private PrintStream o = System.out;
     
        // - //
     
        private String textTotal;
     
        private PageFormat pageFormat;
     
        private Font fontForPrint;
     
        private String textPassage;
     
        private List<String> textPassages = new ArrayList<String>();
     
        // - //
     
        private JWindow windowForPrint = new JWindow();
     
        private JTextArea textareaForPrint = new JTextArea();
     
        private FontMetrics fontMetrics;
     
        private Dimension pageDim;
     
        private BufferedImage bufferedImage;
     
        // - //
     
        private static final int CONS = 2;
     
        private int linesTotal = 0;
     
        private int linesMaxOnPage = 0;
     
        private int numberOfPages = 0;
     
        private int pageBorders[][] = new int[999][2];
     
        // - //
     
        private PrinterJob printerJob = PrinterJob.getPrinterJob();
     
        // - //
     
        public PrintTool(String textToPrint, PageFormat pageFormat, Font font) {
            // Initialize parameters
            this.textTotal = textToPrint;
            this.pageFormat = pageFormat;
            this.fontForPrint = font;
     
            if (textTotal == null)
                textTotal = textForTestpage;
     
            if (this.pageFormat == null)
                this.pageFormat = new PageFormat();
     
            if (fontForPrint == null)
                fontForPrint = new Font("Arial", Font.PLAIN, 16 * CONS);
            else
                fontForPrint = new Font(font.getFamily(), font.getStyle(), font
                        .getSize()
                        * CONS);
            pageDim = new Dimension(
                    ((int) this.pageFormat.getImageableWidth() - 10) * CONS,
                    ((int) this.pageFormat.getImageableHeight()) * CONS);
     
            // Prepare textarea for Print and Preview
            textareaForPrint.setFont(fontForPrint);
            textareaForPrint.putClientProperty(
                    com.sun.java.swing.SwingUtilities2.AA_TEXT_PROPERTY_KEY,
                    Boolean.TRUE);
            fontMetrics = textareaForPrint.getFontMetrics(fontForPrint);
            textareaForPrint.setLineWrap(true);
            textareaForPrint.setWrapStyleWord(true);
            textareaForPrint.setPreferredSize(pageDim);
            textareaForPrint.setTabSize(4);
            textareaForPrint.setText(textTotal);
     
            // Add on JWindow
            windowForPrint.add(textareaForPrint);
            windowForPrint.pack();
     
            // Wrapp text and give to TextArea
            textareaForPrint.setText(this.getWrappedText(textareaForPrint));
            pageDim = new Dimension((int) this.pageFormat.getImageableWidth()
                    * CONS, (int) this.pageFormat.getImageableHeight() * CONS);
            textareaForPrint.setPreferredSize(pageDim);
            windowForPrint.pack();
     
            // Calculate specifications of TextArea
            linesMaxOnPage = this.getMaxLines();
            linesTotal = textareaForPrint.getLineCount();
            numberOfPages = this.getNumberOfPages();
     
            // Calculate Start and End of the pages and store in pageBorders
            // And split text in passages and store in textPassages
            try {
                for (int i = 0; i < numberOfPages; i++)
                    pageBorders[i][0] = textareaForPrint.getLineStartOffset(i
                            * linesMaxOnPage);
                for (int i = 0; i < numberOfPages - 1; i++)
                    pageBorders[i][1] = pageBorders[i + 1][0] - 1;
                pageBorders[numberOfPages - 1][1] = textareaForPrint
                        .getLineEndOffset(linesTotal - 1);
                for (int i = 0; i < numberOfPages; i++)
                    textPassages.add(textareaForPrint.getText(pageBorders[i][0],
                            pageBorders[i][1] - pageBorders[i][0]));
            } catch (BadLocationException e) {
                e.printStackTrace();
            }
        }
     
        public boolean printPage(int page) {
            if (page < 0 | page > numberOfPages - 1)
                return false;
            printerJob.setPrintable(this, pageFormat);
            textPassage = textPassages.get(page);
            try {
                printerJob.print();
            } catch (PrinterException e) {
                e.printStackTrace();
                return false;
            }
            return true;
        }
     
        public void printAllPages() {
            printerJob.setPrintable(this, pageFormat);
            for (int i = 0; i < numberOfPages; i++)
                printPage(i);
        }
     
        public int print(Graphics g, PageFormat pFormat, int pageIndex)
                throws PrinterException {
            if (pageIndex > 0)
                return Printable.NO_SUCH_PAGE;
     
            Graphics2D g2 = (Graphics2D) g;
     
            g2.translate((int) pFormat.getImageableX(), (int) pFormat
                    .getImageableY());
            g2.scale(1.0 / CONS, 1.0 / CONS);
     
            textareaForPrint.setText(textPassage);
            bufferedImage = null;
            bufferedImage = new BufferedImage(pageDim.width, pageDim.height,
                    BufferedImage.TYPE_BYTE_GRAY);
            textareaForPrint.paint(bufferedImage.getGraphics());
     
            g2.drawImage(bufferedImage, 0, 0, textareaForPrint);
            g2.dispose();
     
            return Printable.PAGE_EXISTS;
        }
     
        public BufferedImage getPreviewOfPage(int pageI) {
            textareaForPrint.setText(textPassages.get(pageI));
     
            bufferedImage = null;
            bufferedImage = new BufferedImage(pageDim.width, pageDim.height,
                    BufferedImage.TYPE_BYTE_GRAY);
            textareaForPrint.paint(bufferedImage.getGraphics());
     
            try {
                return bufferedImage;
            } finally {
                bufferedImage = null;
            }
        }
     
        private String getWrappedText(JTextComponent c) {
            int len = c.getDocument().getLength();
            int offset = 0;
            StringBuffer buf = new StringBuffer((int) (len * 1.30));
            String s = "";
            try {
                while (offset < len) {
                    int end = Utilities.getRowEnd(c, offset);
                    if (end < 0) {
                        break;
                    }
                    end = Math.min(end + 1, len);
                    s = c.getDocument().getText(offset, end - offset);
                    buf.append(s);
                    if (!s.endsWith("\n")) {
                        buf.append('\n');
                    }
                    offset = end;
                }
            } catch (BadLocationException e) {
                e.printStackTrace();
            }
            try {
                return buf.toString();
            } finally {
                buf = null;
                s = null;
            }
        }
     
        public int getNumberOfPages() {
            int max = this.getMaxLines();
            int total = textareaForPrint.getLineCount();
            int pages = (int) Math.ceil((double) total / (double) max);
            return pages;
        }
        
        private int getMaxLines() {
            return textareaForPrint.getHeight() / fontMetrics.getHeight();
        }
     
        public static void main(String[] args) {
            // Test PrintTool - Print a TestPage
     
            PrintTool pt = new PrintTool(null, null,null);
            pt.printAllPages();
            
            System.exit(0);
        }
     
        private static final String textForTestpage = "Habe nun, ach! Philosophie,"
                + "Juristerei und Medizin,\n" + "Und leider auch Theologie\n"
                + "Durchaus studiert, mit heißem Bemühn.\n"
                + "Da steh ich nun, ich armer Tor!\n"
                + "Und bin so klug als wie zuvor;\n"
                + "Heiße Magister, heiße Doktor gar\n"
                + "Und ziehe schon an die zehen Jahr\n"
                + "Herauf, herab und quer und krumm\n"
                + "Meine Schüler an der Nase herum-\n"
                + "Und sehe, daß wir nichts wissen können!\n"
                + "Das will mir schier das Herz verbrennen.\n"
                + "Zwar bin ich gescheiter als all die Laffen,\n"
                + "Doktoren, Magister, Schreiber und Pfaffen;\n"
                + "Mich plagen keine Skrupel noch Zweifel,\n"
                + "Fürchte mich weder vor Hölle noch Teufel-\n"
                + "Dafür ist mir auch alle Freud entrissen,\n"
                + "Bilde mir nicht ein, was Rechts zu wissen,\n"
                + "Bilde mir nicht ein, ich könnte was lehren,\n"
                + "Die Menschen zu bessern und zu bekehren.\n"
                + "Auch hab ich weder Gut noch Geld,\n"
                + "Noch Ehr und Herrlichkeit der Welt;\n"
                + "Es möchte kein Hund so länger leben!\n"
                + "Drum hab ich mich der Magie ergeben,\n"
                + "Ob mir durch Geistes Kraft und Mund\n"
                + "Nicht manch Geheimnis würde kund;\n"
                + "Daß ich nicht mehr mit saurem Schweiß\n"
                + "Zu sagen brauche, was ich nicht weiß;\n"
                + "Daß ich erkenne, was die Welt\n"
                + "Im Innersten zusammenhält,\n"
                + "Schau alle Wirkenskraft und Samen,\n"
                + "Und tu nicht mehr in Worten kramen.\n\n"
                + "O sähst du, voller Mondenschein,\n"
                + "Zum letzenmal auf meine Pein,\n"
                + "Den ich so manche Mitternacht\n"
                + "An diesem Pult herangewacht:\n"
                + "Dann über Büchern und Papier,\n"
                + "Trübsel'ger Freund, erschienst du mir!\n"
                + "Ach! könnt ich doch auf Bergeshöhn\n"
                + "In deinem lieben Lichte gehn,\n"
                + "Um Bergeshöhle mit Geistern schweben,\n"
                + "Auf Wiesen in deinem Dämmer weben,\n"
                + "Von allem Wissensqualm entladen,\n"
                + "In deinem Tau gesund mich baden!";
     
    }


    Vg Erdal
    The_Answer1985 bedankt sich. 

  2. #2
    Lyphos Lyphos ist offline Rookie
    Registriert seit
    May 2008
    Beiträge
    5
    Hallo

    Die Arbeit find ich klasse, hab lange sowas gesucht, wollte mich schon daran machen sowas zu schreiben. Wie gesagt klasse Arbeit

    Mit freundlichen Grüßen
    Lyphos