Here is my pure Java solution. It works well on CentOS, SUSE, and Windows 7. And no installation of any software is needed.
import java.io.File;
import java.io.FileOutputStream;
import javax.print.DocFlavor;
import javax.print.DocPrintJob;
import javax.print.SimpleDoc;
import javax.print.StreamPrintService;
import javax.print.StreamPrintServiceFactory;
import javax.print.attribute.HashPrintRequestAttributeSet;
import javax.print.attribute.PrintRequestAttributeSet;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.printing.PDFPrintable;
import org.apache.pdfbox.printing.Scaling;
public class Printing {
public static void main(String[] args) {
try {
DocFlavor flavor = DocFlavor.SERVICE_FORMATTED.PRINTABLE;
String psMimeType = DocFlavor.BYTE_ARRAY.POSTSCRIPT.getMimeType();
StreamPrintServiceFactory[] factories = StreamPrintServiceFactory.lookupStreamPrintServiceFactories(flavor, psMimeType);
System.out.println ("Available PS services: " + factories.length);
System.out.println ("Format: " + factories[0].getOutputFormat());
FileOutputStream outStream = new FileOutputStream("/path/to/your.ps");
StreamPrintService printService = factories[0].getPrintService(outStream);
PrintRequestAttributeSet aset = new HashPrintRequestAttributeSet();
aset.add(MediaSizeName.NA_LETTER);
PDDocument doc = PDDocument.load(new File("/path/to/my.pdf"));
SimpleDoc pdfDoc = new SimpleDoc(new PDFPrintable(doc, Scaling.SCALE_TO_FIT, false), flavor, null);
DocPrintJob newJob = printService.createPrintJob();
newJob.print(pdfDoc, aset);
outStream.close();
}
catch(Exception ex) {
ex.printStackTrace();
}
}
}
Dependency:
dependencies {
compile group: org.apache.pdfbox , name: pdfbox , version: 2.0.8
}