ZhekaKozlov
ZhekaKozlov

Reputation: 39614

Cannot print to PDF printer from Java

I want to print the string "Hello world" to 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 "Foxit Reader PDF Printer". The print job seems to be submitted, but I don't know where to find the printed PDF file. In theory, the printer should ask about the location of the PDF file (because when printing from Paint and Notepad it asks). 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?

Upvotes: 0

Views: 1285

Answers (1)

alkaliexce
alkaliexce

Reputation: 35

Might wanna take a look at your printer's capability to print pdf. I tried and had silence as well. Tend i found that the docflavors supported by my specific printer did not include 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. That brings up your requested dialog box, not too sure about docprintjob though.

Upvotes: 0

Related Questions