我正在尝试找到一个可以处理作业的打印服务,我正在使用Java中的PrintService API。 这是我的代码:
private PrintService[] services = null;
services = PrintServiceLookup.lookupPrintServices(DocFlavor.INPUT_STREAM.PDF, null);
System.out.println("We found : " + services.length + " service(s)");
输出总是:
We found : 0 service(s)
虽然我的计算机上安装了打印机,但我不知道它为什么找不到服务!注意到:
答案 0 :(得分:1)
找不到与指定的DocFlavor对应的PrintService:'PDF' 因为当我试图找出我的打印机支持的DocFlavor时:
PrintService[] prnSvc = PrintServiceLookup.lookupPrintServices(null, null);
DocFlavor[] docFalvor = prnSvc[0].getSupportedDocFlavors();
for (int i = 0; i < docFalvor.length; i++) {
System.out.println(docFalvor[i].getMimeType());
}
我得到了:
image/gif
image/gif
image/gif
image/jpeg
image/jpeg
image/jpeg
image/png
image/png
image/png
application/x-java-jvm-local-objectref
application/x-java-jvm-local-objectref
application/octet-stream
application/octet-stream
application/octet-stream
类似帖子:Printer services Not found?和Java Print program with Specfications issues?
答案 1 :(得分:0)
似乎Windows下的PDF功能存在问题。我遇到了同样的问题,但尚未找到解决方案。 其他人找到了解决方法,但现在这似乎是非法的(见https://community.oracle.com/thread/2046162)。
修改强>
我通过将PDF转换为PNG图像解决了这个问题。
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPage;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.List;
import static java.awt.image.BufferedImage.TYPE_INT_RGB;
import static javax.imageio.ImageIO.write;
import static org.apache.pdfbox.pdmodel.PDDocument.load;
public class PdfToImageConverter {
public static String GIF = "gif";
public static String JPG = "jpg";
public static String PNG = "png";
public static byte[] convertPdfTo(final String imageType, final byte[] pdfContent) throws IOException {
final PDDocument document = load(new ByteArrayInputStream(pdfContent));
final List<PDPage> allPages = document.getDocumentCatalog().getAllPages();
final PDPage pdPage = allPages.get(0);
final BufferedImage image = pdPage.convertToImage(TYPE_INT_RGB, 300);
final ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
write(image, "png", outputStream);
outputStream.flush();
final byte[] imageInByte = outputStream.toByteArray();
outputStream.close();
return imageInByte;
}
}
我将MediaSizeName.ISO_A4
作为PrintRequestAttribute添加到PrintJob,此解决方案适合我。