使用PDFRenderer 0.9.1库在java中打印pdf文件

时间:2015-05-02 06:54:58

标签: java pdf printing

我正在尝试使用这个使用PDFRenderer库并在Epson TM-T20打印机中打印的java代码打印80mm宽的收据。我用Windows XPS打印预览测试它结果没问题,但是当我在我的物理爱普生打印机中打印出来时,打印机外出的很小,几乎是微观的。

public static void printPdf2(String filename) throws IOException, PrinterException{

    // Create a PDFFile from a File reference
    File f = new File(filename);
    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);

    fis.close();

    // 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);
    PrintRequestAttributeSet attr_set = new HashPrintRequestAttributeSet();
    attr_set.add(MediaSizeName.ISO_A6);

    // Send print job to default printer
    pjob.print(attr_set);


}

发送到此方法的pdf文件是事先格式化的,除了printRequestAttributeSet之外,还提到以A6格式打印。我不知道是什么导致它在微观层面上打印。

1 个答案:

答案 0 :(得分:0)

好的,所以找到了一个更好的方法来完成对我有用的任务。这是代码:

//this is where the method gets called with these params
JPrintFile.printPdf3(FILE,"PDF Print Job");

打印pdf文件的方法

public static void printPdf3 (String filePath, String jobName) throws IOException, PrinterException {

    FileInputStream fileInputStream = new FileInputStream(filePath);
    byte[] pdfContent = new byte[fileInputStream.available()];
    fileInputStream.read(pdfContent, 0, fileInputStream.available());
    ByteBuffer buffer = ByteBuffer.wrap(pdfContent);

    final PDFFile pdfFile = new PDFFile(buffer);
    PDFPrintPage pages = new PDFPrintPage(pdfFile);
    PrinterJob printJob = PrinterJob.getPrinterJob();
    PageFormat pageFormat = PrinterJob.getPrinterJob().defaultPage();
    printJob.setJobName(jobName);
    Book book = new Book();

    book.append(pages, pageFormat, pdfFile.getNumPages());
    printJob.setPageable(book);
    Paper paper = new Paper();

    //paper has a default size, but i changed the size and ImageableArea
    //for my specific needs
    paper.setSize(400, 600);
    paper.setImageableArea(0, 0, paper.getWidth()-20, paper.getHeight()-20);
    System.out.println(paper.getHeight());
    System.out.println(paper.getWidth());
    pageFormat.setPaper(paper);

    //using default printService here
    PrintService p=PrintServiceLookup.lookupDefaultPrintService();
    printJob.setPrintService(p);

    PrintRequestAttributeSet attr_set = new HashPrintRequestAttributeSet();
    attr_set.add(MediaSizeName.ISO_A6);

    printJob.print(attr_set);
    fileInputStream.close();
}

要实现这一点,您需要PDFRenderer 0.9.1。只需下载.jar并将其添加到项目的构建路径中即可。