簡體   English   中英

使用PrinterURI屬性時,Java打印機服務會引發ClassCastException

[英]Java Printer Service throws ClassCastException while using PrinterURI Attribute

我已經實現了一個程序,可以使用IP地址,打印機名稱將文檔打印到特定的打印機

碼:

URI myURI=null;
FileInputStream psStream=null;
try   {
       psStream = new FileInputStream( "sample.docx" );
   }
catch ( FileNotFoundException e )   {
    e.printStackTrace();
}
    DocFlavor psInFormat = DocFlavor.INPUT_STREAM.GIF;
    Doc myDoc = new SimpleDoc( psStream, psInFormat, null );
     PrintRequestAttributeSet aset = new HashPrintRequestAttributeSet();
    aset.add( new Copies(5) );
    try {             
        String host="192.255.301.147";
        String printer="HP LaserJet 5000 Series PCL6";
        String theUrl = "ipp://"+host+"/printers/"+printer;
        theUrl = URLEncoder.encode(theUrl, "UTF-8");
        myURI =  new URI(theUrl);       
              aset.add(new PrinterURI(myURI));  
    } catch (URISyntaxException e) {
        System.out.println("URI exception caught: "+e);         
    } catch (UnsupportedEncodingException e) {
             e.printStackTrace();
    }

  PrintService[] services = PrintServiceLookup.lookupPrintServices( psInFormat, aset );
   if ( services.length > 0 ) {
     DocPrintJob job = services[0].createPrintJob();          
     try {
             job.print( myDoc, aset );
     }
     catch ( PrintException e ){
     }
}

在運行程序時, 獲取ClasscastException

Exception in thread "Main Thread" java.lang.ClassCastException
    at javax.print.attribute.AttributeSetUtilities.verifyAttributeValue(AttributeSetUtilities.java:534)
    at javax.print.attribute.HashAttributeSet.add(HashAttributeSet.java:283)
    at com.src.print.TestPrint2.main(TestPrint2.java:64)

在沒有在RequestAttributeSet( aset.add(new PrinterURI(myURI)) )中添加PrinterURI Attribute的情況下,程序可以正常工作。 它采用默認打印機配置並打印文檔。

你能幫我這個忙嗎? 如何使用PrinterURI API?

我遇到了相同的錯誤消息“ ClasscastException”。 我自己發現這是一個粗心的錯誤。 希望能幫助別人。

PrintService[] services = PrintServiceLookup.lookupPrintServices( psInFormat, aset );

.lookupPrintServices使用的是PrintServiceAttributeSet

job.print( myDoc, aset );

.print正在使用PrintRequestAttributeSet

它們不是同一組AttributeSet

通過閱讀stacktrace和相關類文檔,最有可能發生此異常,因為HashPrintRequestAttributeSet (擴展了PrintRequestAttributeset )強制所有添加的類型必須符合PrintRequestAttribute

如果您看到PrinterURI的文檔,則會看到它沒有實現導致異常的接口。 閱讀您的代碼和問題,我想您可能想使用Destination而不是PrinterURI。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM