`
Harold_xlp
  • 浏览: 154394 次
  • 性别: Icon_minigender_1
  • 来自: 深圳
社区版块
存档分类
最新评论

PDF指定盘口打印

 
阅读更多

程序控制打印机,从那个盘口出纸,达到业务的应用,目前只支持TOP,MIDDLE,BOTTOM,其它的一般打印机上没有;

 

public class PDFPrint implements Printable {
 private PDFFile file;

 PDFPrint(PDFFile file) {
  this.file = file;
 }

 public int print(Graphics g, PageFormat format, int index)
   throws PrinterException {
  int pagenum = index + 1;
  // don't bother if the page number is out of range.
  if ((pagenum >= 1) && (pagenum <= file.getNumPages())) {
   // fit the PDFPage into the printing area
   Graphics2D g2 = (Graphics2D) g;
   PDFPage page = file.getPage(pagenum);
   double pwidth = format.getImageableWidth();
   double pheight = format.getImageableHeight();
   double aspect = page.getAspectRatio();
   double paperaspect = pwidth / pheight;
   Rectangle imgbounds = null;
   if (aspect > paperaspect) {
    // paper is too tall pdfpage is too wide
    int height = (int) (pwidth / aspect);
    imgbounds = new Rectangle(
      (int) format.getImageableX(),
      (int) (format.getImageableY() + ((pheight - height) / 2)),
      (int) pwidth, height);
   } else {
    // paper is too wide pdfpage is too tall
    int width = (int) (pheight * aspect);
    imgbounds = new Rectangle(
      (int) (format.getImageableX() + ((pwidth - width) / 2)),
      (int) format.getImageableY(), width, (int) pheight);
   }
   // render the page
   PDFRenderer pgs = new PDFRenderer(page, g2, imgbounds, null, null);
   try {
    page.waitForFinish();
    pgs.run();
   } catch (InterruptedException ie) {
   }
   return PAGE_EXISTS;
  } else {
   return NO_SUCH_PAGE;
  }
 }

 public static void main(String[] args) throws Exception {
  File f = new File("d:/CNIT1199.pdf");
  FileInputStream fis = new FileInputStream(f);
  FileChannel fc = fis.getChannel();
  ByteBuffer bb = fc.map(FileChannel.MapMode.READ_ONLY, 0, fc.size());
  PDFFile pdfFile = new PDFFile(bb); // Create PDF Print Page
  PDFPrintPage pages = new PDFPrintPage(pdfFile); // Create Print Job
  PrinterJob pjob = PrinterJob.getPrinterJob();
  PageFormat pf = PrinterJob.getPrinterJob().defaultPage();

  pjob.setJobName(f.getName());
  Book book = new Book();
  book.append(pages, pf, pdfFile.getNumPages());
  pjob.setPageable(book); // Send print job to default printer
  PrintService printService = PrintServiceLookup
    .lookupDefaultPrintService();
  pjob.setPrintService(printService);
  PrintRequestAttributeSet pras = new HashPrintRequestAttributeSet();
  //pras.add(MediaTray.MIDDLE);// 从2盘出
   pras.add(MediaTray.TOP);//从1盘出
  // pras.add(MediaTray.BOTTOM);//从3盘出
  pjob.print(pras);

 }
}

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics