我一直在尝试使用 Windows 操作系统上的 Java Print Service API 打印包含俄语字母的文本文档,但到目前为止还没有成功。打印机打印文件,但 unicode 字符出现乱码。
运行程序时,指定了 VM 参数-Dfile.encoding=utf8
以下是代码
import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.UnsupportedEncodingException;
import javax.print.Doc;
import javax.print.DocFlavor;
import javax.print.DocPrintJob;
import javax.print.PrintException;
import javax.print.PrintService;
import javax.print.PrintServiceLookup;
import javax.print.SimpleDoc;
import javax.print.attribute.HashPrintRequestAttributeSet;
import javax.print.attribute.PrintRequestAttributeSet;
import javax.print.attribute.standard.Sides;
public class PrintUtf8Doc {
public static void main(String[] args) throws UnsupportedEncodingException {
FileInputStream textstream=null;
DataInputStream da=null;
byte buff[]=new byte[1024*20];
try {
textstream = new FileInputStream("D:\\test\\russian.txt");
da=new DataInputStream(textstream);
da.read(buff);
} catch (Exception e) {
e.printStackTrace();
}
if (textstream == null) {
return;
}
// Set the document type
DocFlavor myFormat = DocFlavor.BYTE_ARRAY.AUTOSENSE;
// Create a Doc
Doc myDoc = new SimpleDoc(buff, myFormat, null);
// Build a set of attributes
PrintRequestAttributeSet aset = new HashPrintRequestAttributeSet();
aset.add(Sides.DUPLEX);
System.out.println("Host Encoding: "+myFormat.hostEncoding);
PrintService service = PrintServiceLookup.lookupDefaultPrintService();
DocFlavor flavs[]=service.getSupportedDocFlavors();
for(DocFlavor flavor: flavs){
System.out.println(flavor.toString());
}
// Create a print job from one of the print services
if (service!=null) {
DocPrintJob printJob=service.createPrintJob();
try {
printJob.print(myDoc, aset);
} catch (PrintException e) {
e.printStackTrace();
}
}
}
}
-------------------------------------------------------------------
The supported flavors are printed in the console
Host Encoding: UTF8
image/gif; class="[B"
image/gif; class="java.io.InputStream"
image/gif; class="java.net.URL"
image/jpeg; class="[B"
image/jpeg; class="java.io.InputStream"
image/jpeg; class="java.net.URL"
image/png; class="[B"
image/png; class="java.io.InputStream"
image/png; class="java.net.URL"
application/x-java-jvm-local-objectref; class="java.awt.print.Pageable"
application/x-java-jvm-local-objectref; class="java.awt.print.Printable"
application/octet-stream; class="[B"
application/octet-stream; class="java.net.URL"
application/octet-stream; class="java.io.InputStream"
我什至尝试将 docFlavor 更改为 "application/octet-stream; class="java.io.InputStream" 并将 inputStream 传递给 SimpleDoc() 构造函数,但仍然是同样的问题
看起来即使平台编码设置为 UTF8,Windows 上的 Java 打印服务也无法正确读取字节。
是否有任何设置需要完成或更正?任何建议都会有很大帮助