Questions About Printing

Hi, i am currently having problems with using java print .
What i need is selecting the printer without using a popup dialog by parsing in a string hardcoded which i would implement a registry reader that would take in the printer name and use that specific printer to read, however i am clueless to edit the codes i had done, by using JobAttributes? or others . please help :=) thankx
belows are my current codes
package javaapplication1;
import java.awt.*;
import java.awt.event.*;
import java.awt.print.*;
import java.io.*;
import java.util.*;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.*;
import javax.swing.filechooser.*;
import javax.print.*;
import java.awt.JobAttributes.*;
public class PrintSample  implements Printable {
   static JTextArea textarea = new JTextArea(10,40);
   static JFrame   window = new JFrame("Fax Services");
   String filename;
  public static  void main(String args[])   {
     final JFileChooser fc;
     fc = new JFileChooser();
     JButton openButton = new JButton("Open");
    final Container cp = window.getContentPane();
    JButton buttonPJ = new JButton("Use Printable");
    LayoutManager lm = new FlowLayout(FlowLayout.CENTER, 20,20);
    // fill in text to display (and later print)
    textarea.setEditable(false);
     // set up layout and fill in sample
     cp.setLayout(lm);
     cp.add(new JScrollPane(textarea));
     cp.add(buttonPJ);
     cp.add(openButton);
     //fc.showOpenDialog(cp);
     // add the button press response for buttons
openButton.addActionListener(new ActionListener(){
     public void actionPerformed(ActionEvent e){
       int ret=fc.showOpenDialog(cp);
    if(ret==fc.APPROVE_OPTION){
       FileInputStream filein = null;
                    try {
                        java.io.File file = fc.getSelectedFile();
                        //textarea.append(file.getName());
                        filein = new java.io.FileInputStream(file);
                        int x = filein.available();
                        byte b[]=new byte[x];
                        filein.read(b);
                        String content = new String(b);
                        textarea.append(content);
                    } catch (FileNotFoundException ex) {
                        Logger.getLogger("global").log(Level.SEVERE, null, ex);
                    } catch(IOException ex2){
                        Logger.getLogger("global").log(Level.SEVERE, null, ex2);
                    }finally {
                        try {
                            filein.close();
                        } catch (IOException ex) {
                            Logger.getLogger("global").log(Level.SEVERE, null, ex);
    }else{
           textarea.append("Errors Occur");
     buttonPJ.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
           printPrinterJob();
     // set up WindowListener to close the program
     window.addWindowListener(new WindowAdapter() {
            @Override
public void windowClosing(WindowEvent e) {
         System.exit(0);
    window.setSize(475,300);
    window.setVisible(true);                  // frame starts out invisible
   // PrinterJob implementation
   static void printPrinterJob() {
      PrinterJob printerjob = PrinterJob.getPrinterJob();
      // set the characteristics of
      // the job to be printed - use setPageable and book if
      // outputing a document. Use setPrintable for "simple" printing - all pages formatted the same
      printerjob.setPrintable(new PrintSample());
      try {
          //JobAttributes j = new JobAttributes();
         printerjob.print();            // print the page(s)  (this method with call the page painters)
      } catch (PrinterException exception) {
         System.err.println("Printing error: " + exception);
   // print  - draw the page
   // Parameters:    graphics - context in which to draw the page
   //                pageFormat - size and orientation of page being drawn
   //               pageIndex - zero-based index position of the  page in the print job
   public int print(Graphics graphics, PageFormat pageFormat, int pageIndex)
      throws PrinterException {
       String strText =null;    // text string to output
      int lineStart;           // start index of line in textarea
       int lineEnd;             // end index of line in textarea
       int lineNumber;          // current line in textarea
       int lineCount;           // total number of lines in textarea
       if (pageIndex >= 1 ) return Printable.NO_SUCH_PAGE;
       // move the drawing origin to the imageable area ( makes sure its drawn where the printer can )
       graphics.translate((int)(pageFormat.getImageableX()), (int)(pageFormat.getImageableY()));
       graphics.setColor(Color.black);
       // get the text from the textarea one line at a time
       lineNumber = 0;
       lineCount = textarea.getLineCount();
       strText = textarea.getText();
       while (lineNumber < lineCount) {
          try {
             lineStart = textarea.getLineStartOffset(lineNumber);
             lineEnd = textarea.getLineEndOffset(lineNumber);
             strText = textarea.getText(lineStart, lineEnd-lineStart);
          } catch( Exception exception) {
             System.out.println("Printing error:" + exception);                  // have to catch BadLocationException
          // determine drawing location of each successive line
          graphics.drawString(strText,0,(lineNumber + 1) *20);
          lineNumber = lineNumber + 1;
        return Printable.PAGE_EXISTS;                      // page was drawn successfully (return NO_SUCH_PAGE if not)
}

Since JTextArea is a descendant of JTextComponent all you need is :
java.text.MessageFormat header = null; // header to print null or text
java.text.MessageFormat footer = null; // footer to print null or text
boolean showPrintDialog = true; // display the print dialog true || false
javax.print.PrintService service = javax.print.PrintServiceLookup.lookupDefaultPrintService();
javax.print.attribute.PrintRequestAttributeSet attributes = null;
boolean interactive = true;
jTextComponent.print(header, footer, showPrintDialog, service, attributes, interactive);
you can put this into a separate thread so it doesn't stall the application
or inside your printPrinterJob method, discard the overwritten print method
and let JTextComponent do the print handling for you.
(print method is inherited for most swing components such as JTextArea etc, look in the API)

Similar Messages

  • Question about printing by page count

    Hi
    I'm new to this and I have a question about printing our invoices by page count.
    We generate our invoice using Crystal 2008 we have invoices that can range from a single page to as many as 6 pages. I would like Crystal to preview/print the reports in order of how many pages are in the report. Example: print all single page invoices first then all invoices that are 2 pages and so on. Is this possible?
    Thank you in advance

    Hi Ido,
    Thanks for your input. This is more or less what Carl was suggesting yesterday and I gave it a lot of thinking. The problem here is that I cannot go with "good enough resolution" - I need perfect resolution.
    The reason for this apparently silly requirement (why would one sort a bunch of invoices by number of pages instead of Customer Number, as long as they end up in an envelope anyway?) is the proposed purchase of a folding/stuffing machine which could do very fast what now takes one person 4 days to achieve.
    One type of machine comes with three settings - fold/stuff 1, 2 or 3-page statements. You need to have three stacks with all the statements that have 1, 2 and 3 pages. The ones with more pages will have to be folded manually, but there are only about two dozen clients that give us that much business. You feed the machine one stack at a time and set it to process the respective number of pages. Any statement that falls accidentally in the other stack will either cause the whole rest of the stack to be mixed up, which is very bad, or cause one customer to receive his invoice and someone else's, which is just embarrassing. I cannot afford any of these scenarios.
    Given that the statement contains variable-length (and depth) messages that vary by month and by profit center, and it could also contain one or more groups of details, each with its own header, it is very risky to try to come up with magic numbers attempting to estimate the number of pages based on the number of detail lines. Someone will still have to eyeball very carefully the initial stack of statements in the areas where the number of pages increases by one and make sure that ordering by number of detail lines did not mix, for example, one report with two pages among two reports with one page. Of course, this increased scrutiny will be necessary only around the areas where the page number transitions from 1->2, 2->3 and 3->4, which is much better than trying to order by number of pages all 1500 statements, but still depends on one's manual intervention and focus and, as a result, makes me pretty uncomfortable.
    I have taken a look at the "Group Sort Expert". If you select the "All" option (all groups) and you had some kind of summary value then you could sort the report by that value. The idea was to create a hidden Average field over the TotalPageCount runtime variable (which will always equal the TotalPageCount for that customer, since it's the same for all the pages in that group) and use that summary field in the "Group Sort Expert", which would have solved the problem elegantly. Unfortunately, there is no way to create a summary field over a runtime variable. I even created a formula that just returns the TotalPageCount, but that formula did not show up in the list of fields available for summarization (while other formulas did).
    It looks like the reporting engine does not allow this type of "late-sorting". I wonder if it is possible at all, because in effect this would require the engine to execute an additional pass: first it should somehow generate the whole report grouped by Customer Number so it knows how many pages are in each group, then it should sort by the number of pages and only after that it could render the report. I'm not sure the engine can do this additional pass.
    I would be very curious to hear about the other (more complex) ideas you mentioned. For example, I have seen (in Crystal 2008) a checkbox allowing "sorting by a formula". I don't know how to write a formula used in sorting, but the basic question in the paragraph above still stands: does the engine even support such a feature?
    Thanks again.

  • Question about "Print Size"

    I am confused and puzzled about "Print Size." First I select the Zoom Tool, then I click "Print Size" in the upper bar. I also have chosen View > Rulers.
    What I don't understand is that one inch in the horizontal ruler actually is considerably longer than one inch on the vertical ruler.  I think this is distorting the appearance on my photos in the monitor as compared with the actual prints. The monitor version of my portrait, for example, looks fatter than the printed version. Why is this and why isn't a horizontal inch equal to a verical inch for viewing purposes.
    Thank you very much for any help on this.
    Bob

    Thank you very much. I changed my monitor to its native resolution and I think this solved the problem.  Bob
    J Maloney <[email protected]> wrote:
    Change the screen resolution setting in your PS prefs to your display resolution. Then print size will work as expected.
    http://en.wikipedia.org/wiki/List_of_displays_by_pixel_density
    More about the print size feature:
    http://help.adobe.com/en_US/Photoshop/11.0/WSfd1234e1c4b69f30ea53e41001031ab64-7935a.html
    >

  • Question about printing and resolution

    Hello
    I am trying out a trial version of PE13 and am attempting to come to terms with printing and resolution.
    I have also read this informative tutorial here:
    How Image Resolution Affects Print Quality - Photoshop Tutorial
    This is the image I would like to print:
    In the tutorial referred to above, the author states that when printing, 300 resolution is best and not the 79.3 px/inch that I have. When I change that 79.3 to 300, the image of Marilyn becomes tiny, so my question is how can I have an image that would neatly fit onto A4 photo paper maybe with a 1" white border around it (meaning the image size would be 8" x 6") while retaining a 300 resolution?
    Am I going about this the right way, aren't I?
    Many thanks.
    Steve

    Steve,
    The most important thing about resolution is the dimension in pixels.
    Your original is 433 x  653 pixels. Just good enough to display on a normal laptop.
    With A4 format at 300 ppi, you'd need:
    21 / 2.54 * 300 = 2480 pixels wide
    29.7 / 2.54 * 300 = 3507 pixel high.
    Any image editor won't be able to add the missing resolution, but the solution is to let the editor guess the missing pixels by interpolation methods.
    You won't get more details than those present in the original file, but you'll get a smoother, non 'pixelated' image.
    In the Elements editor, you have to check the 'resample' checkbox to be able to keep the outpur size while increasing the ppi to 300.

  • Question about printing an image/control Using Report Generator

    The attached VI is an example of creating a report from a control or image. My problem is that when the control (xy graph) gets too large in the vertical direction it clips the image but, the horizontal is scaled to the width of the report. 
    First question is why does it scale in the horizontal and not the vertical? See the Test.pdf for what I am talking about. 
    Second, is it possible to control this behavior (edit/create an alternate for the Append Control Image to report or the Report VI's)?
    I have found many work around but ultimately it comes back to; why automatically scale one direction but not the other?
    For this application I don't mind that the graph is scaled down in the horizontal I just wish it would do the same thing in the vertical axis (I don't even want it to be a 1 to 1 zoom ratio, just fill the avalible report space).
    Thoughts?
    Attachments:
    Print XY Graph TEST.vi ‏55 KB
    Test.pdf ‏217 KB

    I agree all of the workarounds have limitations. One workaround, that I'm not sure if you have tried yet is change the numeric constant from 50 to 20 (I attached a picture showing which constant I am talking about). This seems to fix the issue just because the image never becomes larger than the report page itself.
    Let me know if that option creates any problems for you as well.
    Kevin S
    Applications Engineer
    National Instruments
    Attachments:
    Block Diagram.PNG ‏29 KB

  • Question about printing and sorting files

    What I'm trying to do is read in a file of names (about a thousand) sort them using a sort alorithim then print out the sorted file of names, as well a separate chart with the number of compares and swaps . My Sort class has different sorting algorithims, like insertion, bubble etc. Everything I have now works fine. But the way its set up now I have to pick one algorithim at a time, then it sorts then prints the results like this:
    Bubble Sort
    Compares : 2016
    Swaps : 1052.
    Now if I want to choose anothert algorithim, I'll have to manualy do that then run Main again then apend the results to the output file. But I would like run Main once opening the file that needs to be sorted then run one algorithim, calc the results, then do that again for another algorithim calc the results, then when I'm finished with all the algorithims, print all the results at once to the output chart. This so the output will look better, and the user won't have repeatedly run the program to see and compare the results.
    Is this even possible, and if so, any ideas how?
    This is the main console, which put the names in a array list, then sorts
    them
    public class SortyFile {
         public static void main(String[] args) throws IOException{
               BufferedReader r = new BufferedReader(new FileReader("C:/Documents and Settings/Cougar/" +
                   "Desktop/names.txt"));
               PrintWriter Output_Chart
                    = new PrintWriter(new BufferedWriter(new FileWriter("C:/Documents and Settings/Cougar/" +
                      "Desktop/Output Chart2.txt" , true)));
               PrintWriter Output_Sorted_File
                    = new PrintWriter(new BufferedWriter(new FileWriter("C:/Documents and Settings/Cougar/" +
                           "Desktop/Sorted File2.txt")));
               ArrayList a = new ArrayList();
               String line = null;
               while ((line = r.readLine()) != null)
                    a.add(line);
                    Sort.bubbleSort(a);
                  Output_Chart.println("");
                  Output_Chart.println(Sort.algoname);
                  Output_Chart.println("");
                  Output_Chart.println("Compares :" + "   " + Sort.compares);
                  Output_Chart.println("Swaps :" + "      "  + Sort.swaps);
                  Output_Chart.println("");
                  for (int i=0; i<a.size(); i++){
                       Output_Sorted_File.println(a.get(i));
                       System.out.println(a.get(i));
               Output_Chart.close();
               Output_Sorted_File.close();
    This is the class with different sorting algorithims, the variable algoname is use for printing the header on the output chart.
    public class Sort {
        static int swaps = 0;
        static int compares = 0;
        static String algoname;  // name for the algorithim
        public static void swap(List data, int least, int i) {
              Object tmp = data.get(least);
              data.set(least, data.get(i));
              data.set(i, tmp);
         public static void bubbleSort(List data)
            for (int i = 0; i < data.size(); i++)
                for(int j = i+1; j < data.size(); j++)
                    Comparable current = (Comparable) data.get(j);
                    Comparable previous = (Comparable) data.get(i);
                    compares++;
                    if (current.compareTo(previous) < 0)
                        data.set(j, previous);
                        data.set(i, current);
                        swaps++;
            algoname = "Bubble Sort"; 
          public static void selectionSort (List data)
               int i,j, least;
               final int size = data.size();
               for (i = 0; i < size - 1; i++)
                  for (j = i+1, least = i; j < size; j++)
                       compares++;     
                 if (((((Comparable) (data.get(j))).compareTo(data.get(least)))) < 0)
                      least = j;
                      swap(data,least,i);
                      swaps++;
               algoname = "Selection Sort";
          public static void insertionSort (List data)
                 Comparable tmp;
              int i, j;
                 for(i = 1; i < data.size(); i++)
                      tmp =  (Comparable)data.get(i);
                       for(j = i; (j > 0) && (tmp.compareTo(data.get(j - 1)) < 0) ; j--){
                       compares++;
                       data.set(j, data.get(j - 1))  ;
                       data.set(j, tmp)  ;
                      swaps++;
                 algoname = "Insertion Sort";
    }

    Maybe Im misunderstanding your question, but couldnt
    you just run the bubbleSort() method, then the
    insertionSort() method, and so on? You would do this
    in your main method.Yeah I tried that but for odd reason I get this for the results
    Bubble Sort
    Compares : 2016
    Swaps : 1052
    Selection Sort
    Compares : 2016
    Swaps : 1052
    The results for both algorthims are exactly the same.

  • Questions About Printing in Java

    Alright, I've been looking at the Java printing API. I like it, it's nice. I've got a drag-and-drop workspace that the user wants to print, so I just use m_workspace.paint(Graphics) on the print Graphics object to paint the workspace onto the page. Very nice.
    Here's the issue. I want to fit as many workspaces on a page as is possible. Now, with a Graphics2D object, I can call a couple of methods to get its height and width. I need to be able to determine the height and width of the Graphics object that the printer hands me. Here are the questions as best as I can describe them:
    * Is it possible to find the height and width of a Graphics object? How else can you determine a Graphics object's coordinate range?
    * When the Printable interface is given a Graphics object on which to print, does the Graphcis object represent the whole page or just the printable area of the page?
    * The PageFormat class provides methods for determining the height and width as well as the printable height and width of a page in 72nds of an inch. How does one determine the intended printing resolution (dpi) of the print job? If this cannot be done, how is it possible to determine the size of the page in pixels?
    I'd really appreciate help with this as fast as it can be mustered. This program needs to be completed by Friday morning and I'm clueless as to the Java printing interface.
    Thanks for any time you've spent reading this and the time you may spend answering it. :) Best wishes!

    After perusing the many books of one of my coworkers, I think I have good reason to believe the following:
    * Printing with the Printable interface is always at a resolution of 72dpi (1 pixel per point).
    * The Graphics object passed to print(...) represents a pixel space equal to the number of points of each dimension of the imageable area of the page.
    Can anyone with experience with Java printing confirm these conclusions?

  • Question about Print to Video

    I am using a Sony HC1 HDV camera. I captured some HDV video (using the camera to downconvert) in DV. I edited the sequence and now I want to output a copy of my finished version onto tape in standard definition. The camera is connected via firewire.
    I tried to do this playing with the video/audio settings and could not get it to work. I am using Print to Video. I seem to have no problem when I print to video in HDV, but I can't get it to work in DV. Does anyone have any suggestions about settings or anything else that would make this work?

    I thought I put the camera in the correct mode, but if I hear you accurately you are saying that you think it is one of my camera settings that is incorrect not my settings within FCP?
    Just to verfiy what should all of my Audio/Video settings for Print to Video be for outputting DV to the camcorder? (Both video and audio)
    Thanks Jerry-

  • Question about printing in lightroom

    I have a new canon ip 6700d printer and was wondering if when I print from a raw photo in lightroom am I printing in the pro photo rgb color space? Bob

    >I let lightroom manage my printing and my question was..Does lightroom print my raw photo in pro photo rgb color space or another color space?????? Bob
    No. It only sends prophotoRGB to the driver when you select "managed by printer" The printer driver should then translate to its own icc profile. If you set draft mode printing, Lightroom sends adobeRGB data. But most importantly, if you let Lightroom manage color by selecting a profile, it sends data in the printing profile. The latter is the preferred method for the best output, but some printer drivers on some OS/printer combinations choke on that, so be aware.

  • Really quick question about printing a book

    hello,
    always asking questions... but you people on these forums are super nice and smart....
    if i should upload the pictures to iphoto to print a book should i export the pictures as AdobeRGB 1998 or ProPhotoRGB .jpegs????
    the website only says jpegs..... what would my best choice be.....????
    answers are appreciated and thank you in advance

    Yes - do not use Adobe RGB - sRGB is correct
    and test a few photos - some people have had problems importing Lightroom edited photos into iPhoto
    LN

  • Question about print button

    Good morning everyone,
    Quick question for you this morning, im playing around with the print button and so far i get it to do what i want. Which is basically print in "FIT" mode like this:
    xfa.host.print(1, "0", (xfa.host.numPages -1).toString(), 0, 1, 0, 0, 0);
    now this takes care of people who press my custom print button, but i dont have control over the folks that might activate that from the print icon or from the print menu options.
    Now for this i know that using PRE:PRINT would solve it for sure, but i dont know how to write the code in there so it works.
    What i did at first is copy the print code above in that section, but if i press my Print button where the same code is, i create a endless loop.
    Im just trying to cover my self and make sure that what ever one of the 3 print choices they choose, i will be able to execute the code above and without any infinite loops
    Any ideas how i could set this up?
    Thank you very much again!!!

    Hi,
    you can disallow printing form the menu items or key combination with a bit of scripting.
    But first you need a variable you add under the form properties with a default value like 0.
    Lets name it "usedPrintButton".
    Ok, now the scripting part.
    There are 3 scripts in 3 different events neccassary. You can use all those events of your print button.
    1. click event
    // Modify the variable to imply user has started printing from this button
    usedPrintButton.value = "1";
    xfa.host.print(1, "0", (xfa.host.numPages -1).toString(), 0, 1, 0, 0, 0);
    2. prePrint event
    // Check the variable and cancel printing when it's 0
    if (usedPrintButton.value == "0") {
              xfa.event.cancelAction = true;
    3. postPrint event
    // Set the variable back to 0
    usedPrintButton.value = "0";
    Hope this helps.

  • Question about printing before I buy an iMac

    I have a Dell 3010N network color laser printer in my PC network. There are no Mac drivers for this laser printer. I was thinking about switching over from PC to Apple. However, I need to know if there is a way for me to print to the Dell laser printer from the new iMac's? If that's not possible, could I connect the laser printer directly to one of the PC's and print via peer-to-peer as in the PC world?

    Since Dell does not offer Mac drivers, you won't be able to print even if you did hook it to a PC and share it from there.
    However Dell usually just re-brands printers from other makers (HP, LexMark, etc...), so if you can find out which mechanism is actually in the printer, you could probably download Mac drivers (if available) from them. Otherwise, you're probably out of luck.

  • Question about printer setting of PO

    Hi there:
    I encountered an issue that purchase order was printing once I changed PO and save it, is there a way to cancel its setting?

    Hello,
    Go to T-code NACE
    Select application EF-Purchase order
    Go to output type select NEU as your output
    Go to details tab and remove the multiple issuing tick.
    This will avoid priting of purchase order when you make changes in purchase order.
    Still, if you want you can then take print manually.
    Br,
    Tushar

  • Question about printer

    Hello there:
    I have a printer from my office that works great. It is a HP Laserjet 1000 and it has worked with my Sony Vaio for five years without problem.
    But the office has modernized. So long Viao.
    I've brought the printer home in the hopes that I can hook it up to my PowerBook G4 17" computer that I got last year.
    But I can't seem to find driver software anywhere. Not on HP's site, not on Apple's site. Am I SOL? Is this just incompatable hardware? or is there a way to hook these up?
    Thanks a lot.
    Mark

    Download and use this driver with your printer. To print a PDF with this driver installed, use Preview; it does not support Adobe Reader.
    (11938)

  • Hi, everyone, I met a smartform question about print preview the form

    when I print preview the form there is an error message that WA_DOC_ITEM-TARIFNR doesn't exist in form, can anyone tell me how to solve this? and why? thank you in advance and merry christmas to you all.

    well it must be getting used some where check carefully,
    In main window if u r using a table element then goto data tab and see what internal table and work area u r looping at.
    кu03B1ятu03B9к

Maybe you are looking for

  • Windows on Mac

    I am a web designer, and need to test my sites on multiple platforms including (Windows) Internet Explorer. I plan to run Windows using Parallels on my Mac Pro Intel, and wonder what Windows OS I can get by with for the least amount of money. I need

  • Export view

    Dear All I have a user account in a database, under this account, i create a lot of view(Over 100) which is point to another database server table, and i want to export all of them and then import to another database. How i can do that?? I have check

  • Why Apple products are more expensive in Europe than US?

    In Spain, the Iphone 5s cost around 700€, but in United States cost less 200$ Why is more expensive here?

  • The Comcast Network Philadelphia HD

    While I'm sure this is futile, figured I'd inquire on the status for TCN HD for the philly area. It seems like verizon has access to the HD feed but has chosen not to broadcast it. Local sports in a major market shouldn't be presented only in standar

  • I have the iPad Facebook Messenger app....it's stuck.  I have tried the previous reply...did not help?

    I have a IPad.  I downloaded the Facebook messenger app.   It worked for a while, but now it's stuck.  I've had one reply ..To double click  on the home button, which I did .  Then I found the messenger icon...and held it down, to erase it.  But it d