2013-05-07 2 views
0

У меня есть очень простая функция печати в приложении, которая печатает содержимое Jtextpane. Я хочу установить размер страницы по умолчанию на A4, но после поиска я нахожу много способов, связанных с документами и документами и т. Д., Я хочу сохранить это как можно проще.Простая настройка размера страницы при печати JTextPane?

Мой кода в настоящее время:

public void printy(){ 
    JTextPane jtp = new JTextPane(); 
    jtp.setBackground(Color.white); 
    try { 
      // open the file we have just decrypted 

       File myFile = new File(deletefile + "mx.txt"); 
       FileInputStream fIn = new FileInputStream(myFile); 
       BufferedReader myReader = new BufferedReader(
         new InputStreamReader(fIn)); 
       String aDataRow = ""; 
       String aBuffer = ""; 
       while ((aDataRow = myReader.readLine()) != null) { 
        aBuffer += aDataRow + "\n"; 
       } 

       String[] splitdata = aBuffer.split("`"); //recover the file and split it based on ` 
      String lines = ""; 
      for(String line : splitdata){ 
      lines = lines + line + System.getProperty("line.separator") + System.getProperty("line.separator"); 
      } 

       myReader.close(); 

       System.out.println(Arrays.toString(splitdata)); 
       System.out.println(lines); 

       jtp.setText(lines); 
       boolean show = true; 
       try { 
        //set the header and footer data here 
        MessageFormat headerFormat = new MessageFormat("HEADER HERE"); 
        MessageFormat footerFormat = new MessageFormat("FOOTER HERE"); 
        Paper A4 = new Paper(); 
        A4.setSize(595, 842); 
        A4.setImageableArea(43, 43, 509, 756); 


        jtp.print(headerFormat, footerFormat, show, null, null, show); 


       } catch (java.awt.print.PrinterException ex) { 
        ex.printStackTrace(); 
       } 
      } catch (Exception ez) { 
       System.out.println("error in array building"); 
      } 
} 
} 

Я поставил A4 размер бумаги, но не знаю, как установить его в .print атрибутов для JTextPane.

Спасибо за помощь;

Энди

+0

Может ли [это] (http://stackoverflow.com/questions/13558152/how-can-i-print-a-custom-paper-size-cheques-8-x-4) помочь? – Mateusz

+0

Сортировка, но я изо всех сил пытаюсь понять, как использовать пример в моем коде. Я надеялся, что могу сохранить в основном тот же код (как его простой), но заменить один из нулевых параметров на какой-то размер бумаги? – andy

ответ

1

На самом деле, попробовав ссылку, предоставленную StanislavL, я нашел в руководствах оракула то, что я считаю лучшим способом решения моей проблемы, код, с которым я пошел, был;

public void printy(){ 
    JTextPane jtp = new JTextPane(); 
    jtp.setBackground(Color.white); 
    try { 
      // open the file we have just decrypted 

       File myFile = new File(deletefile + "mx.txt"); 
       FileInputStream fIn = new FileInputStream(myFile); 
       BufferedReader myReader = new BufferedReader(
         new InputStreamReader(fIn)); 
       String aDataRow = ""; 
       String aBuffer = ""; 
       while ((aDataRow = myReader.readLine()) != null) { 
        aBuffer += aDataRow + "\n"; 
       } 

       String[] splitdata = aBuffer.split("`"); //recover the file and split it based on ` 
      String lines = ""; 
      for(String line : splitdata){ 
      lines = lines + line + System.getProperty("line.separator") + System.getProperty("line.separator"); 
      } 

       myReader.close(); 

       System.out.println(Arrays.toString(splitdata)); 
       System.out.println(lines); 

       jtp.setText(lines); 
       boolean show = true; 
       try { 
        //set the header and footer data here 
        MessageFormat headerFormat = new MessageFormat("Your header here - {0}"); //sets the page number 
        MessageFormat footerFormat = new MessageFormat("Your footer here"); 

        PrintRequestAttributeSet attr_set = new HashPrintRequestAttributeSet(); 
        attr_set.add(MediaSizeName.ISO_A4); 
        attr_set.add(Sides.DUPLEX); 

        jtp.print(headerFormat, footerFormat, show, null, attr_set, show); 


       } catch (java.awt.print.PrinterException ex) { 
        ex.printStackTrace(); 
       } 

      } catch (Exception ez) { 
       System.out.println("error in array building"); 
      } 

} 
} 

Надеюсь, это поможет кому-то другому, не говоря о его совершенстве, но он отлично работает и добавляет дуплекс по умолчанию.

2

Вы можете использовать подход http://java-sl.com/JEditorPanePrinter.html

Там вы можете пройти PageFormat вам нужно, где вы можете указать желаемый размер/тип бумаги.

+0

Спасибо, это похоже на простое решение, которое мне нужно. Я отчитаю, как только попробую. – andy