用Java打印qr代码

时间:2014-04-08 16:53:29

标签: java pdf printing qr-code

如果你能帮助我解决我已经有一段时间的这个小问题,我真的很感激。

问题是,当我打印包含qr代码的pdf时,qr代码未显示在打印文档中,它只显示一个空格。 拜托,我希望你能帮助我......这是我正在使用的代码:

package utilities;

import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Rectangle;
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.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.ByteBuffer;

import com.sun.pdfview.PDFFile;
import com.sun.pdfview.PDFPage;
import com.sun.pdfview.PDFRenderer;
import static java.awt.print.Printable.NO_SUCH_PAGE;
import static java.awt.print.Printable.PAGE_EXISTS;

/**
 * Converts the PDF content into printable format
 */
public class PrintPdf2 {

    private PrinterJob pjob = null;

    public static void main(String[] args) throws IOException, PrinterException {       
                String ruta="C:\\examplePDF.pdf";
        System.out.println("Printing: " + ruta);
        // Create a PDFFile from a File reference
        FileInputStream fis = new FileInputStream(ruta);
        PrintPdf2 printPDFFile = new PrintPdf2(fis, "Test Print PDF");
        printPDFFile.print();
    }

    public PrintPdf2(InputStream inputStream, String jobName) throws IOException, PrinterException {
        byte[] pdfContent = new byte[inputStream.available()];
        inputStream.read(pdfContent, 0, inputStream.available());
        initialize(pdfContent, jobName);
    }

    public PrintPdf2(byte[] content, String jobName) throws IOException, PrinterException {
        initialize(content, jobName);
    }

    private void initialize(byte[] pdfContent, String jobName) throws IOException, PrinterException {
        ByteBuffer bb = ByteBuffer.wrap(pdfContent);
        // Create PDF Print Page
        PDFFile pdfFile = new PDFFile(bb);
        PDFPrintPage pages = new PDFPrintPage(pdfFile);

        // Create Print Job
        pjob = PrinterJob.getPrinterJob();
        PageFormat pf = PrinterJob.getPrinterJob().defaultPage();
        pjob.setJobName(jobName);
        Book book = new Book();
        book.append(pages, pf, pdfFile.getNumPages());
        pjob.setPageable(book);

        // to remove margins
        Paper paper = new Paper();
        paper.setImageableArea(0, 0, paper.getWidth(), paper.getHeight());
        pf.setPaper(paper);
    }

    public void print() throws PrinterException {
        // Send print job to default printer
        pjob.print();
    }
}

/**
 * Class that actually converts the PDF file into Printable format
 */
class PDFPrintPage implements Printable {

    private PDFFile file;

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

    public int print(Graphics g, PageFormat format, int index) throws PrinterException {
        int pagenum = index + 1;
        if ((pagenum >= 1) && (pagenum <= file.getNumPages())) {
            Graphics2D g2 = (Graphics2D) g;
            PDFPage page = file.getPage(pagenum);

            // fit the PDFPage into the printing area
            Rectangle imageArea = new Rectangle((int) format.getImageableX(), (int) format.getImageableY(),
                    (int) format.getImageableWidth(), (int) format.getImageableHeight());
            g2.translate(0, 0);
            PDFRenderer pgs = new PDFRenderer(page, g2, imageArea, null, null);
            try {
                page.waitForFinish();
                pgs.run();
            } catch (InterruptedException ie) {
                // nothing to do
            }
            return PAGE_EXISTS;
        } else {
            return NO_SUCH_PAGE;
        }
    }
}

提前致谢:)

2 个答案:

答案 0 :(得分:1)

我已经解决了这个问题,我使用了apache的pdfbox,这是我使用的代码:

import java.awt.print.PrinterJob;
import javax.print.PrintService;
import org.apache.log4j.Logger;
import org.apache.pdfbox.pdmodel.PDDocument;

public class PrintPdf {
private static Logger log = Logger.getLogger(PrintPdf.class);

    public void print(String printer, String pdfRoute) {
        log.info("Printing document: "+pdfRoute);
        try{
         PDDocument document = null;
                document = PDDocument.load( pdfRoute );
                PrinterJob printJob = PrinterJob.getPrinterJob();   
                    PrintService[] printService = PrinterJob.lookupPrintServices();
                     boolean printerFound = false;
                     for(int i = 0; !printerFound && i < printService.length; i++)
                     {
                         if(printService[i].getName().indexOf(printer) != -1)
                         {
                             printJob.setPrintService(printService[i]);
                             printerFound = true;
                             break;
                         }
                     }
                     if(printerFound)
                        document.silentPrint( printJob );
                     else
                        log.info("The printer: "+printer + "was NOT found");
        }catch(Exception e){
            e.printStackTrace();
            log.error("Error when printing pdf",e);
        }

    }




}

以防有人需要它。

答案 1 :(得分:0)

使用“itextpdf”库也非常简单:

private void print() throws DocumentException, IOException {
    com.itextpdf.text.Document pdfDocument = new com.itextpdf.text.Document(PageSize.A4);
    java.io.File pdfFile = new java.io.File("d:/qrCode.pdf");
    com.itextpdf.text.pdf.PdfWriter.getInstance(pdfDocument, new java.io.FileOutputStream(pdfFile));
    pdfDocument.open();

    com.itextpdf.text.pdf.PdfPTable qrCodeTable = new com.itextpdf.text.pdf.PdfPTable(new float[] { 1.0f });

    java.util.Map<com.itextpdf.text.pdf.qrcode.EncodeHintType, Object> hints = new java.util.HashMap<com.itextpdf.text.pdf.qrcode.EncodeHintType, Object>();
    hints.put(com.itextpdf.text.pdf.qrcode.EncodeHintType.CHARACTER_SET, "ISO-8859-1");
    com.itextpdf.text.pdf.BarcodeQRCode qrCode = new com.itextpdf.text.pdf.BarcodeQRCode("TEST CODE", 200, 200, hints);
    com.itextpdf.text.Image qrCodeImage = qrCode.getImage();

    qrCodeTable.addCell(qrCodeImage);
    pdfDocument.add(qrCodeTable);

    pdfDocument.close();
}