【发布时间】:2013-04-16 05:47:16
【问题描述】:
我使用Book 类在打印 PDF 文档时为页面提供不同的方向。
但是当我使用 Book 类时,只打印第一页。其他页面不打印。但是Book#getNumberOfPages 回复我4。
我的代码如下所示:
public static getDoc(DocAttributeSet dset) {
final PDFFile pdfFile = new PDFFile(buf);
Book book = new Book();
for (int i=0; i<pdfFile.getNumPages(); i++) {
PDFPage page = pdfFile.getPage(i);
PageFormat pageFormat = new PageFormat();
if (page.getAspectRatio() >= 1) {
pageFormat.setOrientation(PageFormat.LANDSCAPE);
} else {
pageFormat.setOrientation(PageFormat.PORTRAIT);
}
boolean needStop = false;
if (pdfFile.getNumPages() - 1 == i ) { // if latest page, then stopping ('needStop' = NO_SUCH_PAGE)
needStop = true;
}
book.append(getPrintable(page, needStop), pageFormat);
}
return new SimpleDoc(book, DocFlavor.SERVICE_FORMATTED.PAGEABLE, dset);
}
private static Printable getPrintable(final PDFPage page, final boolean needStop) {
return new Printable() {
public int print(Graphics g, PageFormat pageFormat, int index) throws PrinterException {
if (needStop) {
return NO_SUCH_PAGE;
}
// no scaling, center PDF
... // code omitted
return PAGE_EXISTS;
}
};
}
请注意:我使用此代码打印文档:
DocPrintJob job = prn.createPrintJob();
job.print(myDoc, aset);
即我不使用旧 API:
Book bk = new Book();
job.setPageable(bk);
【问题讨论】:
-
我不明白您为什么要进行如此扩展,而您可以简单地
new SimpleDoc(psStream, DocFlavor.INPUT_STREAM.AUTOSENSE, null);其中psStream是您的 PDF 文件的InputStream? -
@MadProgrammer 因为并非所有打印机都支持 PDF 格式。所以我将PDF文件转换为图像并将其打印为图像。我认为问题与
PAGE_EXISTS和NO_SUCH_PAGE有关...使用Book时我需要如何返回PAGE_EXISTS和NO_SUCH_PAGE?我的用法对吗? -
使用像这里这样的可打印书籍:stackoverflow.com/a/4256155/2382406