简体   繁体   English

无法从Java打印到PDF打印机

[英]Cannot print to PDF printer from Java

I want to print the string "Hello world" to PDF. 我想将字符串"Hello world"打印为PDF。 This is my code: 这是我的代码:

import java.io.ByteArrayInputStream;
import java.io.InputStream;

import javax.print.Doc;
import javax.print.DocFlavor;
import javax.print.DocPrintJob;
import javax.print.PrintService;
import javax.print.PrintServiceLookup;
import javax.print.ServiceUI;
import javax.print.SimpleDoc;
import javax.print.attribute.HashPrintRequestAttributeSet;
import javax.print.attribute.PrintRequestAttributeSet;
import javax.print.event.PrintJobAdapter;
import javax.print.event.PrintJobEvent;

public class App {

    public static void main(String[] args) throws Exception {
        DocFlavor flavor = DocFlavor.INPUT_STREAM.AUTOSENSE;

        PrintService[] services = PrintServiceLookup.lookupPrintServices(flavor, null);

        PrintRequestAttributeSet pras = new HashPrintRequestAttributeSet();
        PrintService service = ServiceUI.printDialog(null, 200, 200, services, null, flavor, pras);

        // prints the famous hello world! plus a form feed
        InputStream is = new ByteArrayInputStream("hello world!\f".getBytes("UTF8"));

        Doc doc = new SimpleDoc(is, flavor, null);
        DocPrintJob job = service.createPrintJob();

        job.print(doc, pras);
    }
}

When the 'Print' dialog is shown I select "Foxif Reader PDF Printer". 当显示“打印”对话框时,我选择“ Foxif Reader PDF打印机”。 The print job seems to be submitted, but I don't know where to find the printed PDF file. 打印作业似乎已提交,但我不知道在哪里可以找到打印的PDF文件。 In theory, the printer should ask about the location of the PDF file (because when printing from Paint and Notepad it asks). 从理论上讲,打印机应该询问PDF文件的位置(因为从它询问的Paint和Notepad打印时)。 But there are no dialogs. 但是没有对话。 The job is silent. 这项工作是沉默的。

How to make my code show the standard Windows "Save as" dialog when printing to PDF? 打印到PDF时,如何使我的代码显示标准的Windows“另存为”对话框?

Might wanna take a look at your printer's capability to print pdf. 可能想看看您的打印机打印pdf的功能。 I tried and had silence as well. 我尝试过,也保持沉默。 Tend i found that the docflavors supported by my specific printer did not include pdf. 趋势我发现我的特定打印机支持的文档不包括pdf。 Before anything you should try printing a image file and checking if its still silence. 在进行任何操作之前,您应该尝试打印图像文件并检查其是否仍然静音。

Secondly, I know for a fact that theres a printDialog method in the PrinterJob lib if you ever wanna try using that for a change. 其次,我知道一个事实,如果您想尝试使用它来进行更改,则PrinterJob库中有一个printDialog方法。 That brings up your requested dialog box, not too sure about docprintjob though. 这会弹出您要求的对话框,但是对于docprintjob不太确定。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM