使用Java在网络打印机上打印PDF文件

3
伙计们,我在使用Java打印PDF时遇到了困难。我编写的代码如下:

`

public static void main(String[] args) throws PrinterException, PrintException, IOException{
        DocFlavor docflavor = new DocFlavor.INPUT_STREAM ("application/octet-stream");
    //  DocFlavor docflavor = DocFlavor.SERVICE_FORMATTED.PAGEABLE;
/*      DocFlavor flavor = DocFlavor.SERVICE_FORMATTED.;*/
        PrintService printService = PrintServiceLookup.lookupDefaultPrintService();
        DocFlavor[] docF = printService.getSupportedDocFlavors();
        for(int i = 0; i<docF.length;i++){
            System.out.println(docF[i]);
        }
        FileInputStream fis = new FileInputStream("pathofpdffile");



        Doc pdfDoc = new SimpleDoc(fis, docflavor, null);


        DocPrintJob printJob = printService.createPrintJob();
        PrintRequestAttributeSet aset = new HashPrintRequestAttributeSet();

        aset.add(new Copies(1));
        aset.add(Sides.ONE_SIDED);
        printJob.print(pdfDoc,aset);

        fis.close();

以上代码启动了打印活动,但问题是我只得到了编码字符,无法得到我的精确文件。

第二个问题是,如果我将DocFlavor更改为SERVICE_FORMATTED.PAGEABLE,则会抛出错误。

java.lang.IllegalArgumentException: data is not of declared type
at javax.print.SimpleDoc.<init>(Unknown Source)
at com.calculator.main.PrintingTest.main(PrintingTest.java:42)

如果我将DocFlavor更改为INPUT_STREAM.PDF,则会抛出错误。

`Exception in thread "main" sun.print.PrintJobFlavorException: invalid flavor
at sun.print.Win32PrintJob.print(Unknown Source)
at com.calculator.main.PrintingTest.main(PrintingTest.java:49)`

我正在尝试在网络打印机上完成这一切。 任何帮助都将是巨大的帮助。

请参阅以下链接:https://dev59.com/zUzSa4cB1Zd3GeqPoqww - RaviH
你使用哪个框架来解析和打印PDF文件? - Aaron Digulla
@RaviH:我不喜欢使用任何外部的jar包来完成这个。我也已经仔细阅读了您发布的链接。还需要更多帮助吗? - saharsh
@AaronDigulla:框架我没明白你的意思... :( 这只是普通的Java代码。 - saharsh
当你在不同的打印机上打印时,它能正常工作吗? - Aaron Digulla
2个回答

12

只需按照以下代码更改使用AUTO_SENSE。

InputStream inputStream = new FileInputStream("C://test.pdf");
Doc doc = new SimpleDoc(inputStream, DocFlavor.INPUT_STREAM.AUTOSENSE,null);

1

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接