Printing the string

The below code is print the data in the cheque.For this i create a template and replace in the template with data.
StringBuffer checkTemplate = new StringBuffer();
checkTemplate.append(" VENDOR_NUMBER______ VENDOR_NAME________________________ CHECK_DATE\n");
checkTemplate.append(" \n");
checkTemplate.append(" REF_NUMBER_A INVDATE_A GROSS_AMOUNT_A DISC_TAKEN_A NET_AMT_PAID_A\n");
I replace this with my data later and place it in a string
and this string is passed as a parameter to the below function.
void printIt(String printString) {
InputStream textStream = new ByteArrayInputStream(printString.getBytes());
DocFlavor myFormat=DocFlavor.INPUT_STREAM.AUTOSENSE ;
Doc myDoc = new SimpleDoc(textStream, myFormat, null);
if (printJob.printDialog()){
try {
printService=printJob.getPrintService();
printJob.setPrintService(printService);
job = printService.createPrintJob();
PrintJobWatcher pjw = new PrintJobWatcher(job);
job.print(myDoc, aset);
pjw.waitForDone();
print = true;
}catch(Exception pe){
pe.printStackTrace();
My problem is when i send this string to the laser printer, The string contains the line character "\n" .Even though it contains the new line character laser printer doesnot print line by line. it prints all the string at one line
Please help me.
Edited by: 889575 on Oct 5, 2011 2:41 AM
Edited by: 889575 on Oct 5, 2011 2:44 AM
Edited by: 889575 on Oct 6, 2011 4:11 AM
Edited by: 889575 on Oct 6, 2011 10:42 AM

When posting code, 1) Use code tags: https://forums.oracle.com/forums/ann.jspa?annID=1429 and 2) Provide an [url http://sscce.org]SSCCE that only shows the relevant code and nothing else. For instance, do you think we really need to see all those append() lines? No. Two or three would suffice. And in fact, that's how you should have been testing in the first place. Don't start by testing everything. Start by testing just a tiny piece, and only add more when that piece works.

Similar Messages

  • Does not print the string value ? what is wrong here

    Hi,
    I am trying to print the string value that does not have spaces.
    when I do that,I dont get what I want i.e 3334445555.
    Any help in this regard is appreciated.
    Thanks
    Chat
    import java.util.StringTokenizer;
    class TestTokenizer{
    public static void main(String args[]){
              StringTokenizer st = new StringTokenizer(" 333 444 5555");
              String tokens[] =new String[3];
              int i=1;
              while (st.hasMoreTokens()) {
                   //System.out.println(st.nextToken());
                   tokens=st.nextToken();
              System.out.println(tokens.toString());

    also, be sure to format your code in your next post...click the code button at the top of the message box you type in, and past your code
    *here*[\code]                                                                                                                                                                                                                                                                                                                               

  • Problem in printing the data from database when i print inside servlet

    hi to all!
    the objective of the code below is getting the data from database table and has to send that data to the web browser using out.println .note: out - PrintWriter object
    In a getQuestion method, i am getting the data from database table and store it in String q and when i print the q within this method it is getting printed, but i got the null value when i printed the String q inside service method doPost. why..? its puzzling me.
    package servlet;
    import java.io.*;
    import javax.servlet.*;
    import javax.servlet.http.*;
    import java.sql.*;
    public class test extends HttpServlet {
         Connection con;
         ResultSet rs;
         Statement s;
         StringBuffer q;
         StringBuffer o1;
         StringBuffer o2;
         StringBuffer o3;
         public void getQuestion() throws Exception
              if(rs.next())
                   q=new StringBuffer(rs.getString("question"));
                   o1=new StringBuffer(rs.getString("option1"));
                   o2=new StringBuffer(rs.getString("option2"));
                   o3=new StringBuffer(rs.getString("option3"));
                   System.out.println(q);
                   System.out.println(o1);
                   System.out.println(o2);
                   System.out.println(o3);
         public void connect(){
              try
              Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
              con=DriverManager.getConnection("jdbc:odbc:ds","sa","server");
              s=con.createStatement();
              rs=s.executeQuery("select * from qa order by newid()");
              getQuestion();
              catch(Exception e)
                   System.out.println("erroe");
         public void doPost(HttpServletRequest request,HttpServletResponse response)
         throws IOException,ServletException
              response.setContentType("text/html");
              new test().connect();
              PrintWriter out=response.getWriter();
              request.setAttribute("question", q);
              request.setAttribute("option1", o1);
              request.setAttribute("option2", o2);
              request.setAttribute("option3", o3);
              //RequestDispatcher rd=getServletContext().getRequestDispatcher("/show.jsp");
              //rd.forward(request, response);
              out.println("<html>");
    out.println("<head>");
         out.println("<title>" + "shock!!!" + "</title>");
    out.println("</head>");
    out.println("<body>");
    out.println("<h2>"+"Read twice before u answer"+"<h2>");
    out.println("<p></p>");
    //why the value of q is not getting printed, instead i get null
    out.println("<h2>"+ q +"<h2>");
    out.println("how is it");
    out.println("</body>");
    out.println("</html>");
    Edited by: Mahesh_yeswecan on Nov 29, 2008 10:42 AM

    As u said , i have done a silly mistake earlier. though i have corrected the code still i am getting the same null value
    package servlet;
    import java.io.*;
    import javax.servlet.*;
    import javax.servlet.http.*;
    import java.sql.*;
    public class test extends HttpServlet  {
         Connection con;
         ResultSet rs;
         Statement s;
         StringBuffer q;
         StringBuffer o1;
         StringBuffer o2;
         StringBuffer o3;
         public void getQuestion() throws Exception
              if(rs.next())
                   q=new StringBuffer(rs.getString("question"));
                   o1=new StringBuffer(rs.getString("option1"));
                   o2=new StringBuffer(rs.getString("option2"));
                   o3=new StringBuffer(rs.getString("option3"));
                   System.out.println(q);
                   System.out.println(o1);
                   System.out.println(o2);
                   System.out.println(o3);
         public void connect(){
              try
              Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
              con=DriverManager.getConnection("jdbc:odbc:ds","sa","server");
              s=con.createStatement();
              rs=s.executeQuery("select * from qa order by newid()");
              getQuestion();
              catch(Exception e)
                   System.out.println("erroe");
         public void doPost(HttpServletRequest request,HttpServletResponse response)
         throws IOException,ServletException
              response.setContentType("text/html");
              connect();
              PrintWriter out=response.getWriter();
              request.setAttribute("question", q);
              request.setAttribute("option1", o1);
              request.setAttribute("option2", o2);
              request.setAttribute("option3", o3);
              //RequestDispatcher rd=getServletContext().getRequestDispatcher("/show.jsp");
              //rd.forward(request, response);
              out.println("<html>");
            out.println("<head>");
             out.println("<title>" + "shock!!!" + "</title>");
            out.println("</head>");
            out.println("<body>");
            out.println("<h2>"+"Read twice before u answer"+"<h2>");
            out.println("<p></p>");
            //why the value of q is not getting printed, instead i get null
            out.println("<h2>"+ q +"<h2>");
            out.println("how is it");
            out.println("</body>");
            out.println("</html>");
    }

  • How to split the string?

    Hi Experts,
    Can anyone explain me with code how to separate the single character from the given input string?
    For Example: Input String str = 'RAGHU'
    Output should be:
    R
    RA
    RAGH
    RAGHU
    RAGH
    RAG
    RA
    R
    Can anyone help me with code for above required output?
    Thanks in Advance,
    Regards,
    Raghu.

    HI,
    sy-index will give u the iteration number.
    first of all in this program u are counting the length of the string and it was in variable LEN.
    we are always printing the string from 0 index(1st character) to POS number of characters.
    length is 5 so LNG = 5 * 2 = 10 and LNG = 10 - 1 = 9.and first sy-index = 1.so,1 <= 5 so POS = 0 + 1 = 1. it is printing the first char
    second sy-index = 2.so,2 <= 5 so POS = 1 + 1 = 2. it is printing the first two chars
    third sy-index = 3.so,3 <= 5 so POS = 2 + 1 = 3. it is printing the first three chars
    forth sy-index = 4.so,4 <= 5 so POS = 3 + 1 = 4. it is printing the first four chars
    fifth sy-index = 5.so,5 <= 5 so POS = 4 + 1 = 5. it is printing the first five chars
    sixth sy-index = 6.so,6 > 5 so POS = 5 - 1 = 4. it is printing the first four chars
    seventh sy-index = 7.so,7 > 5 so POS = 4 - 1 = 3. it is printing the first three chars
    eighth sy-index = 8.so,8 > 5 so POS = 3 - 1 = 2. it is printing the first two chars
    ninth sy-index = 9.so,9 > 5 so POS = 2 - 1 = 1. it is printing the first char
    rgds,
    bharat.

  • Add a actionlistener to JTextArea and print out string when  the user input

    Hello:
    I got a problem to add a actionlistener to JTextArea and print out string which from the user input a sentence and after the user press the "enter".
    Could anyone help me please?
    Thanks
    import java.awt.event.*;
    import java.awt.*;
    import javax.swing.*;
    import javax.swing.JScrollBar;
    public class PanelDemo extends JFrame {
       private static JTextArea tAreaUp, tAreaDown;
       private BorderLayout layout;
       private static String strings;
       public PanelDemo()
          super( " test " );
          Container container = getContentPane();
          layout = new BorderLayout();
          container.setLayout( layout );
          tAreaUp = new JTextArea(2,1);
          tAreaUp.setLineWrap(true);
          tAreaUp.setWrapStyleWord(true);
          tAreaUp.setEditable(false);
          tAreaUp.append("I am testing ");
          tAreaUp.append("I am testing");
           JScrollPane scrollPane = new JScrollPane(tAreaUp);
           scrollPane.setVerticalScrollBarPolicy(
                            JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
           scrollPane.setPreferredSize(new Dimension(250, 250));
          tAreaDown =new JTextArea(2,1);
          tAreaDown.setLineWrap(true);
          tAreaDown.setWrapStyleWord(true);
          tAreaDown.addActionListener(new TextAreaHandler());
          JScrollPane scrollPane2 = new JScrollPane(tAreaDown);
          scrollPane2.setVerticalScrollBarPolicy(
                            JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
          container.add( scrollPane, layout.CENTER );
          container.add( scrollPane2, layout.SOUTH );
          setSize( 300, 300 );
          setVisible( true );
         //private inner class for event handling
         private class TextAreaHandler implements ActionListener{
              //process textArea events
            public void actionPerformed(ActionEvent e){
               strings=e.getActionCommand();
                System.out.println(strings);
       public static void main( String args[] )
          PanelDemo application = new PanelDemo();
          application.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
    }

    Thanks for your help, but I still got a question for you.
    Do you think the way I register the even handler to the TextArea is correct?
    Because the compailer complains about that which like
    "D:\101\fig13_27\PanelDemo.java:43: cannot resolve symbol
    symbol  : method addActionListener (PanelDemo.TextAreaHandler)
    location: class javax.swing.JTextArea
          tAreaDown.addActionListener(new TextAreaHandler());

  • How print a page to the printer with String variable

    I my name is Alexandre Lefebvre. Im in big trouble. All my program is finished. I must print only the String elements on a JTextArea to the printer (Hewllett-Packard 842c). Please help me.

    Use the java 2d Api and printable interface together.
    First, implement Printable Interface
    your class extends XXXXX implements Printable
    then use this..
    public int print(Graphics g, PageFormat pf, int index)
    if(index ! =0) return NO_SUCH_PAGE;
    Graphics2D g2 = (Graphics2D)g;
    g2.setColor(Any Color);
    g2.drawString(textArea.getText());
    return PAGE_EXISTS;
    public void actionPerformed(ActionEvent ae)
    if(ae.getSource() == printButton)
    PrinterJob pj = PrinterJob.getPrinterJob();
    pj.setPrintable(this);
    if(pj.printDialog())
    try
    pj.print();
    catch(Exception e){ // Handle }
    This works fine for printing a single page. But you've got to use some logic and iterate the print job

  • Printing the correct string...

    Hi guys,
    i've a simple question for you but i'm not able to solve it.
    Ihave a string composed by 5 field separated by whitespace
    and i want to print it with this format
    The first field is a string
    The second,the third and the fourth is a double.
    How can i do this cast before printing the correct string....?
    Please help me with code...

    Hi guys,
    i've a simple question for you but i'm not able to
    solve it.
    Ihave a string composed by 5 field separated by
    whitespace
    and i want to print it with this format
    The first field is a string
    The second,the third and the fourth is a double.So? If it's already a String, then just print it, and everything will get printed. Of course, if that's not what you want, you'll have to provide more detail.
    If you want to split the string up into its pieces, and you know the only whitespace is the separators, then you could do this: String[] pieces = str.split("\\s+"); Read these to learn more about the regex that split uses:
    Sun's Regular Expression Tutorial for Java
    Regular-Expressions.info

  • Please Help!! How to get the width of the String for print out?

    Hi there,
    I need to do some printing in my application. I just want to know how can I get the width of the string when it is printed on the paper.
    I have tried to use the following code to get the width
    Rectangle2D rec = font.getStringBounds(str, new FontRenderContext(null, true, true));
    double width = rec.getWidth();
    however, the width I got from that function is not correct (the returned width is longer than the printed one)
    Does anyone know how to solve this problem?
    Thank you and Happy New Year !

    hi,
    The getFontMetrics(Font) is also defined in the Component class and therefore you can retrieve it even if you dont override the paint method.
    try the following (provided ur code extends some class that extends Component indirectly)
    FontMetrics f = this.getFontMetrics(this.getFont());
    int width = f.stringWidth(str); //str is the String for which u need to check the width.
    hope this was useful
    happy holidayz

  • String a = "Hello"; How to print the address of  a;

    String a = "Hello";
    How to print the address of a;

    How about the address a points to?Please try to answer the question in reply 1: why?
    You can't get the address to which a variable points (except with JNI, but that again begs the question: why?) Also the address can change at any time as garbage collection moves objects around in memory.

  • How to print the output string in inverted commas

    hi all,
    my question is
    like i have a string
    "welcome to java"
    using println statement
    i need to print the above statement in inverted commas
    like the output should appear as
    "welcome to java"

    This sounds like part of some homework but what the
    heck ...
    System.out.println("\\"welcome to java\\"");I was trying to anticipate bugs in this stupid forum sofftware, this should be
    System.out.println("\"welcome to java\"");

  • To upload a RTF and a PDF file to SAP R/3 and print the same through SAP

    Hi,
    I have a requirement to upload a PDF file and a RTF file to SAP R/3 and print the same.
    I wrote the following code for uploading a RTF file to SAP R/3 and print the same. However, the problem is , the formatting present in the RTF document( bold/italics..etc) is not being reflected when I do the 'print-preview' after the executing the code below :
    report z_test_upload .
    data: begin of itab occurs 0,
             rec type string,
          end of itab.
    data: options like itcpo.
    data: filename type string,
          count type i.
    data: filetype(10) type c value 'ASC'.
    DATA: HEADER  LIKE THEAD    OCCURS   0 WITH HEADER LINE.
    DATA: NEWHEADER  LIKE THEAD    OCCURS   0 WITH HEADER LINE.
    DATA: ITFLINE LIKE TLINE    OCCURS   0 WITH HEADER LINE.
    DATA: RTFLINE LIKE HELP_STFA OCCURS   0 WITH HEADER LINE.
    DATA:   string_len TYPE i,
            n1 TYPE i.
    selection-screen begin of block b1.
      parameter: p_file1(128) default 'C:\test_itf.rtf'.
    selection-screen end of block b1.
    AT SELECTION-SCREEN ON VALUE-REQUEST FOR p_file1.
      CALL FUNCTION 'F4_FILENAME'
           IMPORTING
                file_name = p_file1.
    start-of-selection.
    move p_file1 to filename.
    call function 'GUI_UPLOAD'
         EXPORTING
              filename                = filename
              filetype                = filetype
         TABLES
              data_tab                = itab
         EXCEPTIONS
              file_open_error         = 1
              file_read_error         = 2
              no_batch                = 3
              gui_refuse_filetransfer = 4
              invalid_type            = 5
              no_authority            = 6
              unknown_error           = 7
              bad_data_format         = 8
              header_not_allowed      = 9
              separator_not_allowed   = 10
              header_too_long         = 11
              unknown_dp_error        = 12
              access_denied           = 13
              dp_out_of_memory        = 14
              disk_full               = 15
              dp_timeout              = 16
              others                  = 17.
    if sy-subrc <> 0.
      message id sy-msgid type sy-msgty number sy-msgno
                with sy-msgv1 sy-msgv2 sy-msgv3 sy-msgv4.
    endif.
    loop at itab.
      string_len = strlen( itab-rec ).
      n1 = string_len DIV 134.
      ADD 1 TO n1.
      DO n1 TIMES.
        rtfline-line = itab-rec.
        APPEND rtfline.
        SHIFT itab-rec BY 134 PLACES.
      ENDDO.
    endloop.
    HEADER-TDSTYLE = 'S_DOCUS1'.
    HEADER-TDFORM = 'S_DOCU_SHOW'.
    header-tdspras = 'E'.
    CALL FUNCTION 'CONVERT_TEXT'
      EXPORTING
      CODEPAGE               = '0000'
        DIRECTION              = 'IMPORT'
        FORMAT_TYPE            = 'RTF'
       FORMATWIDTH            = 72
        HEADER                 = header
        SSHEET                 = 'WINHELP.DOT'
        WITH_TAB               = 'X'
        WORD_LANGU             = SY-LANGU
        TABLETYPE              = 'ASC'
      TAB_SUBSTITUTE         = 'X09  '
      LF_SUBSTITUTE          = ' '
      REPLACE_SYMBOLS        = 'X'
      REPLACE_SAPCHARS       = 'X'
      MASK_BRACKETS          = 'X'
      IMPORTING
        NEWHEADER              = NEWHEADER
      WITH_TAB_E             =
      FORMATWIDTH_E          =
      TABLES
        FOREIGN                = RTFLINE
        ITF_LINES              = ITFLINE.
      LINKS_TO_CONVERT       =
    if sy-subrc <> 0.
    endif.
    CALL FUNCTION 'PRINT_TEXT_ITF'
      EXPORTING
         HEADER        = newheader
         OPTIONS       = options
    IMPORTING
      RESULT        =
      TABLES
        LINES         = itfline.
    if sy-subrc <> 0.
    endif.
    Any hints or suggestions to solve this problem will be highly appreciated.
    Thanks,
    Avra

    Hi Vishwas,
    Check out the thread [Efficient way of saving documents uploaded|Re: Efficient way of saving documents uploaded by users; and check the blog by Raja Thangamani.
    Also check the thread [Export Images through Function Modules   |Export Images through Function Modules;.
    Hope it helps you.

  • How to print the script in condensed mode

    Hi to all,
    Pls help me.
    How to print the script in condensed mode and particular window only print in the condensed mode.

    Hi,
    Hi
    It will remove the blank spaces in front of the variable
    and if you use the extension NO-GAPS
    It will remove all the blank spaces in the variable field.
    DATA: ws_val1 type char12.
    ws_val1 = ' 100 123'.
    Condense ws_val1.
    Write / ws_val1.
    Condense ws_val1 no-gaps.
    write / ws_val1.
    It will give output as
    100 123
    100123
    The CONDENSE statement deletes redundant spaces from a string:
    CONDENSE c NO-GAPS.
    This statement removes any leading blanks in the field c and replaces other sequences of blanks by exactly one blank. The result is a left-justified sequence of words, each separated by one blank. If the addition NO-GAPS is specified, all blanks are removed.
    Please check this link for sample code.
    http://help.sap.com/saphelp_nw2004s/helpdata/en/fc/eb33e6358411d1829f0000e829fbfe/content.htm
    Regards,
    Raj.

  • Not Printing the Content of Object:SOme Garbage Value on Screen

    i have made one program of Vehicle class which adds and prints the Details of Vehicles in the ArrayList but it always showa the Garbage Value in return.
    import java.util.*;
    import java.awt.*;
    import java.lang.*;
    import java.io.*;
    public class Vehicle
         private int reg_no;
         private String model_name;
         private int model_no;
         private int yr_manufacture;
         private String veh_type;
         private int price;
         private int weight;
         private String veh_status;
         public ArrayList vehicles;
         static BufferedReader keyboard = new BufferedReader (new InputStreamReader (System.in));
         public Vehicle()
              //super();          
              vehicles=new ArrayList(10);
         public Vehicle(int regno,String mo_name,int mo_no,int year_manu,String type_veh,int cost,int weight,String status)
         this.reg_no=regno;
         this.model_name=mo_name;
         this.model_no=mo_no;
         this.yr_manufacture=year_manu;      
         this.veh_type=type_veh;
         this.price=cost;
         this.weight=weight;
         this.veh_status=status;
         public void addVehicle() throws IOException
              int regno;
              String mo_name;
              int mo_no;
              int year_manu;
              String type_veh;
              int weight=0;
              int no_person;
              int cargo;
              int cost;
              String status;
              String confirm;
              int countvehicle=0;
              //start of do-while loop
              do {
                   System.out.print("Input the Vehicle Registration Number(Integer):");
                   regno=Integer.parseInt(keyboard.readLine().trim());
                   System.out.print("Input the Vehicle Make(String)eg. Mercedes,Ferrari,BMW etc: ");
                   mo_name=keyboard.readLine();
                   System.out.print("Input the Vehicle Model(Integer): ");
                   mo_no=Integer.parseInt(keyboard.readLine().trim());
                   System.out.print("Input the Vehicle Manufactured Year(Integer): ");
                   year_manu=Integer.parseInt(keyboard.readLine().trim());
                   System.out.print("Input the Vehicle Type:(CAR/BUS/TRUCK)");
                   type_veh=keyboard.readLine();
                   System.out.print("Where do u want this Vehicle to be Loaded:(Type F or I)?");
                   status =keyboard.readLine();
                        if(countvehicle>6 && status.equals("I"))
                        System.out.println("Sorry.........Ferry is Overloaded your Vehicle will be Loacally on the Island");
                        status="Island";
                        System.out.println("Vehicle in Island");
                        else
                             System.out.println("Vehicle loaded on to Ferry");
                             status="Ferry";
                   //decide the weight Factor for the Vehicle
                   if(type_veh.equals("CAR"))
                        weight=1500;                
                   else if(type_veh.equals("BUS"))      
                        System.out.print("Input the boarding No of Person in Bus: ");
                        no_person=Integer.parseInt(keyboard.readLine().trim());
                        weight=(10000+(no_person*75));// Assuming the weight of one Person is 75kg.
                   else if(type_veh.equals("TRUCK"))
                        System.out.print("Input the Truck Cargo Load: ");
                        cargo=Integer.parseInt(keyboard.readLine().trim());
                        weight=(4500+cargo);                
                   System.out.print("Input the Vehicle Price: ");
                   cost=Integer.parseInt(keyboard.readLine().trim());
                   Vehicle regVehicle= new Vehicle (regno,mo_name,mo_no,year_manu,type_veh,cost,weight,status);
                   vehicles.add(regVehicle);//Add to the Vector
                   regVehicle.printall();
                   //Saving the Added Object in File
                   /*try
                             FileOutputStream f_out = new FileOutputStream("Added.txt");                    
                             ObjectOutputStream obj_out = new ObjectOutputStream(f_out);
                             obj_out.writeObject(vehicles.add(regVehicle));
                        catch (FileNotFoundException e)
                             System.err.println("Error:"+ e.getMessage());
                        catch (IOException e)
                             System.err.println("Error:"+ e.getMessage());
                   countvehicle++;
                   System.out.print ("Add a new vehicle (y or n)? ");
                   System.out.flush();      
         confirm= keyboard.readLine();
                   } while (confirm.equals("y")); //end of do while loop
         public Vehicle getVehicle(int index) throws IOException
              return (Vehicle)vehicles.get(index);
         public int getRegNo() throws IOException
              return reg_no;               
         public Vehicle lookUpVehicle (int accnos)throws IOException
    //start of for loop
              for(int i=0;i<vehicles.size();i++)
              //checks if the information entered are correct using an if statement
              if((((Vehicle)vehicles.get(i)).getRegNo()) == accnos)
                   return ((Vehicle)vehicles.get(i));
    return null;
         public void printDetails()throws IOException
              System.out.println("--------Vehicle Details------------ ");
         for(int i=0;i<vehicles.size();i++)
              System.out.println(" " + getVehicle(i));           
         //System.out.println("\n\n");
         //return ((Vehicle)elements());*/
         /*Iterator it = vehicles.iterator();
              while (it.hasNext())
                   System.out.println(it.next());
         public void printall()
              System.out.println(reg_no);
              System.out.println(model_name);
              System.out.println(model_no);
              System.out.println(weight);
    }

    sohamdave wrote:
    what toString will contain in them.i didn't get you there.it is the whole data type-casted to String or only object type-casted to StringSimply return a String representation of the Vehicle object; frequently the String contains the member variable values, e.g.
    public String toString() {
       return model_name+" "+veh_type;
    }The List toString() method itself invokes your method when the List itself needs to be printed.
    kind regards,
    Jos

  • Print a string on a specific printer

    Hello everyone,
    I need some help.
    I have to print a string in LabView. Previously the method used was to set on the option "Automatically print front panel every time VI completes execution" in the Print Options of the VI Properties.
    Now, however, I should dynamically select the printer on which to print this string. The printer name is dynamically loaded from a text file.
    Actually I'm trying to use the Print Report function (Easy Text Report.vi) that works fine, but it creates problems during the compiling: it create 3 folders in the directory where the executable is located (here the folders: NI_HTML, NI_report, NI_Standard Report) with all the VI "in freedom", not compiled but copied in there.
    There are other methods to print a string through the name of the printer, or to solve this problem of creating random folders and VIs?
    Attachments:
    PrintTest.vi ‏9 KB

    Your application does something internally that depends on the VIs being stored flat inside the executable. LabVIEW 8.x layout basicaly creates one flat archive inside the executable with all VIs stored in one level. That means it can not store VI files more than once with the same name. The Report Generatino Tools are however written using LabVIEW OOP which requires VIs to be named the same in order to allow dynamic dispatch.
    If you deselect the LabVIEW 8.x layout option, the VIs are stored inside the executable in the same hierarchical structure as they are on disk in the source code of your application. That allows multple VIs with the same name to be placed inside the executable, but it does make the internal file hierarchy more complex.
    Bsically you have two options:
    1) figure out where in your appliction yoeu depend on internal paths of VIs to be in a flat order. Most likely this are Current VI path nodes that your application uses to strip twice a path element to find the directory in which the executable is located, for instance to find configuration files or similar. Replace this legacy code construct with an Application Directory property which will return the directory your executable is in rspectively the directory of your project file when you run your app in the devlopment environment.
    2) Live with the extra files outside of your executable!
    Rolf Kalbermatter
    CIT Engineering Netherlands
    a division of Test & Measurement Solutions

  • How to print the report directly without previewing (report viewer) using c# windows application

    Hi,
    Currently, we are using crystal report to all of our reporting applications, but since I/users have encountered some issues about CR's speed to load only a simple report, maybe it is now time for us to adopt a new reporting environment in which I think SSRS
    can fill this problem.
    To start with, I have here a sample code, that uses the crystal report to print the report directly without previewing:
    csCashInvoiceCal csCashCal; --Crystal report name .rpt
    dsCsReceipt dsCs; --created dataset
    DataTable u;
    DataRow s;
    private System.Drawing.Printing.PrintDocument printDocument1;
    private System.Windows.Forms.PrintDialog printDialog1;
    ParameterValues paramValue;
    ParameterDiscreteValue discreteValue;
    ParameterFieldDefinition fieldDefinition;
    private void btnPrint_Click(object sender, EventArgs e)
    this.Cursor = Cursors.WaitCursor;
    loadReceipt2();
    print2();
    csCashCal.Close();
    this.Cursor = Cursors.Default;
    private void loadReceipt2()
    dsCs = new dsCsReceipt(); --created dataset
    u = dsCs.Tables.Add("DtCsReceipt");
    u.Columns.Add("Qty", Type.GetType("System.String"));
    u.Columns.Add("UOM", Type.GetType("System.String"));
    u.Columns.Add("Description", Type.GetType("System.String"));
    u.Columns.Add("UnitPrice", Type.GetType("System.String"));
    u.Columns.Add("Discount", Type.GetType("System.String"));
    u.Columns.Add("Amount", Type.GetType("System.String"));
    try
    for (int i = 0; i < dgvDesc.Rows.Count - 1; i++)
    s = u.NewRow(); double.TryParse(dgvDesc.Rows[i].Cells[Discount2.Name].Value.ToString(), out discount);
    s["Qty"] = double.Parse(dgvDesc.Rows[i].Cells[Qty.Name].Value.ToString());
    s["UOM"] = dgvDesc.Rows[i].Cells[Uom2.Name].Value.ToString();
    s["Description"] = invcode + dgvDesc.Rows[i].Cells[Description.Name].Value.ToString();
    s["UnitPrice"] = dgvDesc.Rows[i].Cells[UnitPrice.Name].Value.ToString();
    if (discount != 0)
    s["Discount"] = "(" + string.Format("{0:0.##}", discount) + "%)";
    else
    s["Discount"] = "";
    s["Amount"] = dgvDesc.Rows[i].Cells[Amount2.Name].Value.ToString();
    u.Rows.Add(s);
    catch (Exception) { }
    csCashCal = new csCashInvoiceCal();
    csCashCal.SetDataSource(dsCs.Tables[1]);
    //csCashCal.Refresh();
    loadParameter2();
    private void loadParameter2()
    ParameterFieldDefinitions paramFieldDefinitions;
    paramValue = new ParameterValues();
    discreteValue = new ParameterDiscreteValue();
    paramFieldDefinitions = csCashCal.DataDefinition.ParameterFields;
    discreteValue.Value = date;
    fieldDefinition = paramFieldDefinitions["Date"];
    commonParam();
    discreteValue.Value = txtcsno.Text;
    fieldDefinition = paramFieldDefinitions["InvoiceNo"];
    commonParam();
    discreteValue.Value = txtNameTo.Text;
    fieldDefinition = paramFieldDefinitions["CustomerName"];
    commonParam();
    discreteValue.Value = txtAdd.Text;
    fieldDefinition = paramFieldDefinitions["CustomerAddress"];
    commonParam();
    ------other parameters----
    private void commonParam()
    paramValue.Clear();
    paramValue.Add(discreteValue);
    fieldDefinition.ApplyCurrentValues(paramValue);
    private void print2()
    using (printDocument1 = new System.Drawing.Printing.PrintDocument())
    using (this.printDialog1 = new PrintDialog())
    //this.printDialog1.UseEXDialog = true;
    this.printDialog1.Document = this.printDocument1;
    DialogResult dr = this.printDialog1.ShowDialog();
    if (dr == DialogResult.OK)
    int nCopy = this.printDocument1.PrinterSettings.Copies;
    int sPage = this.printDocument1.PrinterSettings.FromPage;
    int ePage = this.printDocument1.PrinterSettings.ToPage;
    string PrinterName = this.printDocument1.PrinterSettings.PrinterName;
    try
    csCashCal.PrintOptions.PrinterName = PrinterName;
    csCashCal.PrintToPrinter(nCopy, false, sPage, ePage);
    printcount++;
    //saveCountPrint();
    catch (Exception err)
    MessageBox.Show(err.ToString());
    This is only a simple sales receipt application that uses dgv and textboxes to push its data to dataset to the crystal report, a simple one but there are instances that it is very slow.
    But I'm having trouble implementing this using SSRS, since I'm only new to this one, wherein I created the report using report wizard, with two button options inside the form for print preview or direct print selection. Actually, it is very easy to implement
    with print preview because it uses reportviewer. My problem is that how can I print the report directly without using a reportviewer?
    So here is my code so far which I don't know what's next:
    private void button2_Click(object sender, EventArgs e)
    this.Cursor = Cursors.WaitCursor;
    loadReceipt3();
    //print3();
    this.Cursor = Cursors.Default;
    ReportParameter[] parameter = new ReportParameter[11];
    private void loadParameter3()
    parameter[0] = new ReportParameter("InvoiceNo", txtcsno.Text);
    parameter[1] = new ReportParameter("Date", date);
    parameter[2] = new ReportParameter("CustomerTin", txtTin.Text);
    parameter[3] = new ReportParameter("CustomerName", txtNameTo.Text);
    parameter[4] = new ReportParameter("CustomerAddress", txtAdd.Text);
    parameter[5] = new ReportParameter("Agent", agent);
    parameter[6] = new ReportParameter("Discount", "Discount: ");
    parameter[7] = new ReportParameter("TotalDiscount", lblDiscount.Text + "%");
    parameter[8] = new ReportParameter("TotalSales", rdtotal);
    parameter[9] = new ReportParameter("Tax", rdtax);
    parameter[10] = new ReportParameter("TotalAmount", rdnet);
    private void loadReceipt3()
    DataSet dsrs = new DataSet();
    DataTable dtrs = new DataTable();
    DataRow drs;
    dtrs.Columns.Add("Qty", Type.GetType("System.String"));
    dtrs.Columns.Add("UOM", Type.GetType("System.String"));
    dtrs.Columns.Add("Description", Type.GetType("System.String"));
    dtrs.Columns.Add("UnitPrice", Type.GetType("System.String"));
    dtrs.Columns.Add("Discount", Type.GetType("System.String"));
    dtrs.Columns.Add("Amount", Type.GetType("System.String"));
    try
    for (int i = 0; i < dgvDesc.Rows.Count - 1; i++)
    drs = dtrs.NewRow();
    drs["Qty"] = double.Parse(dgvDesc.Rows[i].Cells[Qty.Name].Value.ToString());
    drs["UOM"] = dgvDesc.Rows[i].Cells[Uom2.Name].Value.ToString();
    drs["Description"] = invcode + dgvDesc.Rows[i].Cells[Description.Name].Value.ToString();
    drs["UnitPrice"] = dgvDesc.Rows[i].Cells[UnitPrice.Name].Value.ToString();
    if (discount != 0)
    drs["Discount"] = "(" + string.Format("{0:0.##}", discount) + "%)";
    else
    drs["Discount"] = "";
    drs["Amount"] = dgvDesc.Rows[i].Cells[Amount2.Name].Value.ToString();
    dtrs.Rows.Add(s);
    catch (Exception) { }
    int addtlRow = 7;
    if (addtlRow > (count - 1))
    addtlRow = addtlRow - (count - 1);
    for (int i = 0; i < addtlRow; i++)
    dtrs.Rows.Add();
    loadParameter3();
    LocalReport localreport = new LocalReport();
    localreport.SetParameters(parameter);
    localreport.DataSources.Clear();
    localreport.DataSources.Add(new ReportDataSource("dsSalesReceiptSsrs", dtrs));
    localreport.Refresh();
    //what's next....
    So what's next after local..refresh()? Actually, I have googled a lot but I didn't found the exact solution that I'm looking for which confuses me a lot.
    Anyway I'm using VS 2010 with sql server 2012 express.
    You're help will be greatly appreciated.
    Thank you,
    Hardz

    After some further studies with ReportViewer controls and with the use of this tutorial @ : http://msdn.microsoft.com/en-us/library/ms252091.aspx, which helps me a lot on how to print a report without using a report viewer, I found out what is missing
    with my code above and helps solve my question.
    Here's the continuation of the code above:
    private void loadReceipt3()
    loadParameter3();
    LocalReport localreport = new LocalReport();
    localreport.ReportPath = @"..\..\SsrsCashReceipt.rdlc";
    localreport.SetParameters(parameter);
    localreport.DataSources.Clear();
    localreport.DataSources.Add(new ReportDataSource("dsSalesReceiptSsrs", dtrs));
    Export(localreport);
    print4();
    private IList<Stream> m_streams;
    private int m_currentPageIndex;
    private void Export(LocalReport report)
    string deviceInfo =
    @"<DeviceInfo>
    <OutputFormat>EMF</OutputFormat>
    <PageWidth>8.5in</PageWidth>
    <PageHeight>11in</PageHeight>
    <MarginTop>0.25in</MarginTop>
    <MarginLeft>0.25in</MarginLeft>
    <MarginRight>0.25in</MarginRight>
    <MarginBottom>0.25in</MarginBottom>
    </DeviceInfo>";
    Warning[] warnings;
    m_streams = new List<Stream>();
    report.Render("Image", deviceInfo, CreateStream,
    out warnings);
    foreach (Stream stream in m_streams)
    stream.Position = 0;
    private void print4()
    if (m_streams == null || m_streams.Count == 0)
    throw new Exception("Error: no stream to print.");
    PrintDocument printDoc = new PrintDocument();
    PrintDialog printDlg = new PrintDialog();
    printDlg.Document = printDoc;
    DialogResult dr = printDlg.ShowDialog();
    if (dr == DialogResult.OK)
    if (!printDoc.PrinterSettings.IsValid)
    throw new Exception("Error: cannot find the default printer.");
    else
    printDoc.PrintPage += new PrintPageEventHandler(PrintPage);
    m_currentPageIndex = 0;
    printDoc.Print();
    Dispose();
    public void Dispose()
    if (m_streams != null)
    foreach (Stream stream in m_streams)
    stream.Close();
    m_streams = null;
    private Stream CreateStream(string name, string fileNameExtension, Encoding encoding, string mimeType, bool willSeek)
    Stream stream = new FileStream(name + "." + fileNameExtension,
    FileMode.Create);
    m_streams.Add(stream);
    return stream;
    private void PrintPage(object sender, PrintPageEventArgs ev)
    Metafile pageImage = new
    Metafile(m_streams[m_currentPageIndex]);
    // Adjust rectangular area with printer margins.
    Rectangle adjustedRect = new Rectangle(
    ev.PageBounds.Left - (int)ev.PageSettings.HardMarginX,
    ev.PageBounds.Top - (int)ev.PageSettings.HardMarginY,
    ev.PageBounds.Width,
    ev.PageBounds.Height);
    // Draw a white background for the report
    ev.Graphics.FillRectangle(Brushes.White, adjustedRect);
    // Draw the report content
    ev.Graphics.DrawImage(pageImage, adjustedRect);
    // Prepare for the next page. Make sure we haven't hit the end.
    m_currentPageIndex++;
    ev.HasMorePages = (m_currentPageIndex < m_streams.Count);
    Thank you very much for this wonderful tutorial. :)

Maybe you are looking for

  • Public Constructor in atg

    Hi , i was going through the doc Public Constructor , why constructor without args is needed in creating a nucleus component. i create a component like Test.java name; getxx(); setxx(); Test.properties name=Kavi when i went to dyn/admin im able to se

  • Does anyone here access a shared calendar with their Blackberry???

    I work for a very large company and I don't use my personal calendar. I use a calendar on a shared mailbox where several people enter appointments I need to attend. So far I have not been able to get a hold of anyone in our IT department who knows if

  • Reader Extensions Service Empty binary return

    I'm using the ReaderExtensionsService and get a response with a Blob but the binary data is empty. I'm sending the variable blob=base64 just in case and still get no binary data. Any ideas why?

  • Blocking my number w/ text

    I know if you dial *67 before making a call, it makes your number come up as restricted on the other person's caller id.  Is there any way to do this for text messaging as well?

  • Consistent Kernel Panics

    Hey Everyone, I've updated my MacPro to Snow Leopard, nothing odd about this system, (quad 2x2.66 xeons, 7gb ram, 1x500gb seagate, 3x1tb hitachi, 1xnvidia 7300gt, 1xati 2600xt, 1xati 4870 (1gb flashed)) and it ran great for a day or so until i starte