java 打印:纸张尺寸不正确
java printing : incorrect paper size
我正在尝试打印 A4 尺寸的 pdf,但输出结果与预期不同。
这是它的样子
但应该是这样的
两张图片分辨率相同
这是生成此输出的代码。
PrinterJob pj = PrinterJob.getPrinterJob();
pj.setPrintService(service);
PageFormat pf = new PageFormat();
Paper paper = new Paper();
paper.setSize(595, 842); // a4 in px
paper.setImageableArea(0, 0, 595, 842);
pf.setPaper(paper);
Book book = new Book();
book.append(pages, pf, pdfFile.getNumPages());
pj.setPageable(book);
pj.print();
基本上只是缩小了。我应该怎么做才能解决这个问题?
顺便说一下,我没有使用真正的打印机。我正在使用接受打印请求并输出 pdf 的 virtual printer。
我已经找到了解决办法。我使用 javax.print 库而不是 java.awt.print。
File file = new File("path/to/pdf");
DocFlavor flavor = DocFlavor.INPUT_STREAM.PDF;
PrintRequestAttributeSet attr = new HashPrintRequestAttributeSet();
attr.add(MediaSizeName.ISO_A4);
FileInputStream fis = new FileInputStream(file);
Doc doc = new SimpleDoc(fis, flavor, null);
DocPrintJob job = printService.createPrintJob();
job.print(doc, attr);
fis.close();
现在打印正确了。
我正在尝试打印 A4 尺寸的 pdf,但输出结果与预期不同。
这是它的样子
但应该是这样的
两张图片分辨率相同
这是生成此输出的代码。
PrinterJob pj = PrinterJob.getPrinterJob();
pj.setPrintService(service);
PageFormat pf = new PageFormat();
Paper paper = new Paper();
paper.setSize(595, 842); // a4 in px
paper.setImageableArea(0, 0, 595, 842);
pf.setPaper(paper);
Book book = new Book();
book.append(pages, pf, pdfFile.getNumPages());
pj.setPageable(book);
pj.print();
基本上只是缩小了。我应该怎么做才能解决这个问题?
顺便说一下,我没有使用真正的打印机。我正在使用接受打印请求并输出 pdf 的 virtual printer。
我已经找到了解决办法。我使用 javax.print 库而不是 java.awt.print。
File file = new File("path/to/pdf");
DocFlavor flavor = DocFlavor.INPUT_STREAM.PDF;
PrintRequestAttributeSet attr = new HashPrintRequestAttributeSet();
attr.add(MediaSizeName.ISO_A4);
FileInputStream fis = new FileInputStream(file);
Doc doc = new SimpleDoc(fis, flavor, null);
DocPrintJob job = printService.createPrintJob();
job.print(doc, attr);
fis.close();
现在打印正确了。