package com.java456.print; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.Image; import java.awt.Toolkit; import java.awt.print.Book; import java.awt.print.PageFormat; import java.awt.print.Paper; import java.awt.print.Printable; import java.awt.print.PrinterException; import java.awt.print.PrinterJob; import java.io.File; import java.io.IOException; import javax.print.PrintService; import org.apache.pdfbox.pdmodel.PDDocument; import org.apache.pdfbox.printing.PDFPageable; import org.apache.pdfbox.printing.PDFPrintable; public class Test_Print { public static void main(String[] args) throws IOException, PrinterException { PDDocument document = PDDocument.load(new File("D:/123/11.pdf"));//这种方式不能打印图片。 printWithPaper(document); } /** * 打印功能 * @author 作者微信 xiaomao0055 */ public static void printWithPaper(PDDocument document)throws IOException, PrinterException { PrinterJob job = PrinterJob.getPrinterJob(); //job.setPageable(new PDFPageable(document)); job.setPrintable(new Printable() { @Override public int print(Graphics graphics, PageFormat pageFormat, int pageIndex) throws PrinterException { if(pageIndex > 0){ return Printable.NO_SUCH_PAGE;//若不是从0页开始打印返回 } int x = (int)pageFormat.getImageableX(); int y = (int)pageFormat.getImageableY();//有效打印内容左上角点的坐标 Graphics2D g2 = (Graphics2D)graphics; g2.translate(x, y); Image img = Toolkit.getDefaultToolkit().getImage("D:\\123\\1.jpg"); g2.drawImage(img, x, y, null); return Printable.PAGE_EXISTS; } });//设置打印页面 try { job.print(); } catch (PrinterException e1) { e1.printStackTrace(); } } }
站长微信:xiaomao0055
站长QQ:14496453