无法将标签打印到打印机

时间:2016-11-24 01:50:56

标签: java image printing labels

我正在编写一个程序来生成标签并在使用标签纸打印的标准上打印标签。我可以创建一个图像并保存它但是,我在标签页上打印图像时遇到问题。这是空白的。我可以将图像写入磁盘并打开图像,它似乎是一个有效的图像。但是,无论我做什么,我都无法打印出来。我写了一个测试程序试图打印它无济于事。我从网上下载了一张图片并能够打印出来。

创建的标签需要打印在标签纸上(从上到下包含6个标签)。我需要创建一个标签,并从纸张上所需的标签开始打印。

LabelImage类为标签创建图像。图像左侧最多打印4位数字(顺时针旋转90度),然后是一些字符串值。我不得不在单独的图像中创建数字,因为我无法在单个图像中正确旋转它们。

import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Stroke;
import java.awt.geom.AffineTransform;
import java.awt.image.BufferedImage;
import java.util.HashMap;
import java.util.Map;

public class LabelImage {

    public static final Map <String, Color> ColorMap = new HashMap <> ();

    // Define label size
    public static final int LABEL_WIDTH = 830;
    public static final int LABEL_HALF_WIDTH = LABEL_WIDTH / 2;
    public static final int LABEL_HEIGHT = 190;
    public static final int LABEL_HALF_HEIGHT = LABEL_HEIGHT / 2;

    // Define rectangle to print out digits in for the label
    public static final int LEFT_DIGIT_RECT_TLX = 15;
    public static final int LEFT_DIGIT_RECT_TLY = 30;
    public static final int LEFT_DIGIT_RECT_WIDTH = 80;
    public static final int LEFT_DIGIT_RECT_HEIGHT = (LABEL_HEIGHT - (LEFT_DIGIT_RECT_TLY * 2));
    public static final int LEFT_DIGIT_TLX_OFFSET = -10;
    public static final int LEFT_DIGIT_TLY_OFFSET = 15;

    public static final int LEFT_DIGIT_ROTATE_X = LEFT_DIGIT_RECT_WIDTH / 2;
    public static final int LEFT_DIGIT_ROTATE_Y = LEFT_DIGIT_RECT_TLY + (LEFT_DIGIT_RECT_HEIGHT / 4);
    public static final int LEFT_DIGIT_ROTATE_Y2 = LEFT_DIGIT_ROTATE_Y + (LEFT_DIGIT_RECT_HEIGHT / 2);

    // Create a separate image of the digits, then rotate the image
    public static final int LEFT_DIGIT_TLX = 20;
    public static final int LEFT_DIGIT_TLX2 = (LEFT_DIGIT_RECT_HEIGHT / 2) + LEFT_DIGIT_TLX;
    public static final int LEFT_DIGIT_TLY = (LEFT_DIGIT_RECT_WIDTH - 25);
    public static final int ROTATE_X = 0;
    public static final int ROTATE_Y = 0;

    public static final float DIGIT_FRAME_THICKNESS = 5;

    public static final int CLIENT_ID_X = 380;
    public static final int CLIENT_ID_Y = 30;
    public static final int CLIENT_ID_Y2 = LABEL_HALF_HEIGHT + CLIENT_ID_Y;

    public static final int CLIENT_NAME_X = 450;
    public static final int CLIENT_NAME_Y = 30;
    public static final int CLIENT_NAME_Y2 = LABEL_HALF_HEIGHT + CLIENT_NAME_Y;

    public static final int PROJECT_NAME_X = CLIENT_NAME_X;
    public static final int PROJECT_NAME_Y = 50;
    public static final int PROJECT_NAME_Y2 = LABEL_HALF_HEIGHT + PROJECT_NAME_Y;

    public static final int OTHER_X = CLIENT_ID_X;
    public static final int OTHER_Y = 70;
    public static final int OTHER_Y2 = LABEL_HALF_HEIGHT + OTHER_Y;

    Font normalFont = new Font("TimesRoman", Font.BOLD, 14);
    Font leftDigitFont = new Font("TimesRoman", Font.BOLD, 42);



    static {
        ColorMap.put("0", new Color(255, 120, 130, 100));
        ColorMap.put("1", new Color(252, 0, 105, 100));
        ColorMap.put("2", new Color(255, 165, 10, 100));
        ColorMap.put("3", new Color(255, 85, 10, 100));
        ColorMap.put("4", new Color(122, 252, 12, 100));
        ColorMap.put("5", new Color(0, 145, 0, 100));
        ColorMap.put("6", new Color(60, 255, 255, 100));
        ColorMap.put("7", new Color(40, 0, 120, 100));
        ColorMap.put("8", new Color(222, 182, 245, 100));
        ColorMap.put("9", new Color(145, 55, 0, 100));

        ColorMap.put("0", new Color(196, 23, 27, 100));
        ColorMap.put("1", new Color(232, 85, 66, 100));
        ColorMap.put("2", new Color(236, 131, 101, 100));
        ColorMap.put("3", new Color(230, 229, 48, 100));
        ColorMap.put("4", new Color(184, 224, 101, 100));
        ColorMap.put("5", new Color(53, 161, 19, 100));
        ColorMap.put("6", new Color(66, 142, 232, 100));
        ColorMap.put("7", new Color(98, 83, 234, 100));
        ColorMap.put("8", new Color(26, 15, 126, 100));
        ColorMap.put("9", new Color(95, 17, 143, 100));
    }

    /**
     * Prints a digit on the left hand side of the label, rotated 90 degrees 
     * clockwise. At the specified digit location.
     * @param digit the digit to print
     * @param ndx  the index location to print at
     */
    private void printLeftDigit(Graphics2D g2, String digit, int ndx) {

        // find the top-left coordinate of the rectangle
        int tlx = LEFT_DIGIT_RECT_TLX + (LEFT_DIGIT_RECT_WIDTH * ndx);
        int tly = LEFT_DIGIT_RECT_TLY;

        // Draw the colored rectangle
        Color origColor = g2.getColor();
        g2.setColor(ColorMap.get(digit));
        g2.fillRect(tlx, tly, LEFT_DIGIT_RECT_WIDTH, LEFT_DIGIT_RECT_HEIGHT);
        g2.setColor(origColor);

        // Draw a black outline for the box over the rectangle
        Stroke oldStroke = g2.getStroke();
        g2.setStroke(new BasicStroke(DIGIT_FRAME_THICKNESS));
        g2.drawRect(tlx, tly, LEFT_DIGIT_RECT_WIDTH-1, LEFT_DIGIT_RECT_HEIGHT);
        g2.setStroke(oldStroke);

        // Center of digit to rotate around
        int cdx = tlx + LEFT_DIGIT_ROTATE_X;

        // Write the digit in the rectangle
        AffineTransform origTransform = g2.getTransform();
        g2.setFont(leftDigitFont);
        //g2.rotate(Math.PI/25);

        double angle = Math.toRadians(90.0);

        g2.setColor(Color.BLACK);
        g2.rotate(angle, cdx, LEFT_DIGIT_ROTATE_Y);
        g2.drawString(digit, cdx + LEFT_DIGIT_TLX_OFFSET, LEFT_DIGIT_ROTATE_Y + LEFT_DIGIT_TLY_OFFSET);
        g2.setTransform(origTransform);

        //g2.setColor(Color.GREEN);
        g2.rotate(angle, cdx, LEFT_DIGIT_ROTATE_Y2);
        g2.drawString(digit, cdx + LEFT_DIGIT_TLX_OFFSET, LEFT_DIGIT_ROTATE_Y2 + LEFT_DIGIT_TLY_OFFSET);
        g2.setTransform(origTransform);
    }

    /**
     * This method creates a 2nd image for the digits, then rotates the image and puts it 
     * over the label image.
     *
     * @param g2
     * @param digit
     * @param ndx 
     */
    private void printLeftDigit2(Graphics2D g2, String digit, int ndx) {

        // Width is the top to bottom rectangle size
        // height is the left to right rectangle width (because it will be rotated)
        //BufferedImage image = new BufferedImage(LEFT_DIGIT_RECT_HEIGHT, LEFT_DIGIT_RECT_WIDTH, BufferedImage.TYPE_INT_ARGB);
        BufferedImage image = new BufferedImage(LEFT_DIGIT_RECT_HEIGHT, LEFT_DIGIT_RECT_WIDTH, BufferedImage.TYPE_INT_RGB);
        Graphics2D imageGraphics = image.createGraphics();

        // Fill the rectangle with the expected color
        imageGraphics.setColor(ColorMap.get(digit));
        imageGraphics.fillRect(0, 0, LEFT_DIGIT_RECT_HEIGHT, LEFT_DIGIT_RECT_WIDTH);

        // Draw a black outline for the box over the rectangle
        imageGraphics.setColor(Color.BLACK);
        Stroke oldStroke = imageGraphics.getStroke();
        imageGraphics.setStroke(new BasicStroke(DIGIT_FRAME_THICKNESS));
        imageGraphics.drawRect(0, 0, LEFT_DIGIT_RECT_HEIGHT, LEFT_DIGIT_RECT_WIDTH);
        imageGraphics.setStroke(oldStroke);

        // Draw the Digits in the rectangle (top-left of digit)
        imageGraphics.setFont(leftDigitFont);
        imageGraphics.drawString(digit, LEFT_DIGIT_TLX, LEFT_DIGIT_TLY);
        imageGraphics.drawString(digit, LEFT_DIGIT_TLX2, LEFT_DIGIT_TLY);
        imageGraphics.dispose();

        // Put the image on the current graphic
        AffineTransform aff = g2.getTransform();
        double theta = Math.toRadians(90.0);
        //AffineTransform rotate = AffineTransform.getRotateInstance(theta, rotx, roty);
        //(x,y) = middle of rectangle
        AffineTransform rotate = AffineTransform.getRotateInstance(theta, 40, 65);
        //x >0 moves down; <0 moves up
        //y >0: moves left; <0: moves right
        int moveright = 15 - (ndx * LEFT_DIGIT_RECT_WIDTH);
        rotate.translate(10, moveright);
        //g2.drawImage(image, rotate, this);
    }

    public BufferedImage createImageWithText(ClientProject clientProject){

        //ARGB = transparent
        BufferedImage bufferedImage = new BufferedImage(830, 190,BufferedImage.TYPE_INT_ARGB);
        Graphics g = bufferedImage.getGraphics();
        g.setColor(Color.YELLOW);
        g.fillRoundRect(0, 0, LABEL_WIDTH, LABEL_HEIGHT, 10, 10);

        String clientId = String.valueOf(clientProject.getClientId());
        String clientName = clientProject.getClientName();
        String projectName = clientProject.getProjectName();
        String created = "DFC: " + DateUtil.format(clientProject.getCreated(), DateUtil.LABEL_DATE_PATTERN);

        // Setup for drawing to screen
        g.setColor(Color.BLACK);
        g.setFont(normalFont);
        g.drawLine(0, LABEL_HALF_HEIGHT, LABEL_WIDTH, LABEL_HALF_HEIGHT);

        // write client id on tabs
        String tmp = clientId;
        if (clientId.length() > 4) {
            tmp = tmp.substring(0, 4);
            System.out.println("tmp = " + tmp);
        }
        StringBuilder sb = new StringBuilder(tmp);
        sb.reverse();
        for (int ndx=0; ndx < sb.length(); ndx++) {
            try {
                printLeftDigit2((Graphics2D)g, String.valueOf(sb.charAt(ndx)), ndx);
            } catch (NumberFormatException e) {
            }
        }

        // Write client id
        g.setFont(normalFont);
        g.drawString(clientId, CLIENT_ID_X, CLIENT_ID_Y);
        g.drawString(clientId, CLIENT_ID_X, CLIENT_ID_Y2);

        // Write Client Name
        g.drawString(clientName, CLIENT_NAME_X, CLIENT_NAME_Y);
        g.drawString(clientName, CLIENT_NAME_X, CLIENT_NAME_Y2);

        // Write Project Name
        g.drawString(projectName, PROJECT_NAME_X, PROJECT_NAME_Y);
        g.drawString(projectName, PROJECT_NAME_X, PROJECT_NAME_Y2);

        // Write created
        g.drawString(created, OTHER_X, OTHER_Y);
        g.drawString(created, OTHER_X, OTHER_Y2);

        return bufferedImage;
    }
}

PrintLabel程序应该将图像打印到标签纸上,但我无法打印出上面代码创建的图像。我从网上的其他地方拿过这个课程,并试图为我的目的修改它。

import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.awt.print.PageFormat;
import java.awt.print.Paper;
import java.awt.print.Printable;
import static java.awt.print.Printable.NO_SUCH_PAGE;
import static java.awt.print.Printable.PAGE_EXISTS;
import java.awt.print.PrinterException;
import java.awt.print.PrinterJob;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import javax.imageio.ImageIO;

public class PrintLabel {


    protected static double fromCMToPPI(double cm) {            
        return toPPI(cm * 0.393700787);            
    }

    protected static double toPPI(double inch) {            
        return inch * 72d;            
    }

    protected static String dump(Paper paper) {            
        StringBuilder sb = new StringBuilder(64);
        sb.append(paper.getWidth()).append("x").append(paper.getHeight())
           .append("/").append(paper.getImageableX()).append("x").
           append(paper.getImageableY()).append(" - ").append(paper
       .getImageableWidth()).append("x").append(paper.getImageableHeight());            
        return sb.toString();            
    }

    protected static String dump(PageFormat pf) {    
        Paper paper = pf.getPaper();            
        return dump(paper);    
    }

    public void process() {

        PrinterJob pj = PrinterJob.getPrinterJob();
        if (pj.printDialog()) {
            PageFormat pf = pj.defaultPage();
            Paper paper = pf.getPaper();
            double width = fromCMToPPI(20.3);
            double height = fromCMToPPI(25.4);

            paper.setSize(width, height);
            paper.setImageableArea(
                            fromCMToPPI(0.25), 
                            fromCMToPPI(0.5), 
                            width - fromCMToPPI(0.35), 
                            height - fromCMToPPI(1));

            System.out.println("Before- " + dump(paper));
            pf.setOrientation(PageFormat.PORTRAIT);
            pf.setPaper(paper);
            System.out.println("After- " + dump(paper));
            System.out.println("After- " + dump(pf));
            //dump(pf);

            PageFormat validatePage = pj.validatePage(pf);
            System.out.println("Valid- " + dump(validatePage));

            MyPrintable printable = new MyPrintable();
            printable.labels.add(new ClientProject(112, 208, "Taxes", "Tax Refund"));
            printable.determinePageCount();

            pj.setPrintable(printable, pf);

            try {
                pj.print();
            } catch (PrinterException ex) {
                ex.printStackTrace();
            }
        }
    }
    public static void main(String[] args) {
        PrintLabel pl = new PrintLabel();
        pl.process();
    }

    public class MyPrintable implements Printable {

        public int startAtLabel = 0;
        public int totalPages = 0;
        public List <ClientProject> labels = new ArrayList <> ();
        private List <ClientProject> printed = new ArrayList <> ();


        /**
         * Determines how many pages to print, there are 6 labels per page. If we
         * start at index 5 (the last one) and there are 2 labels, there are 2
         * pages to print.
         */
        public void determinePageCount() {
            int max = this.startAtLabel + this.labels.size();
            this.totalPages = max / 6;
            if ((max % 6) != 0) {
                this.totalPages++;
            }
        }

        @Override
        public int print(Graphics graphics, PageFormat pageFormat, int pageIndex) 
                throws PrinterException {

            System.out.println(pageIndex);
            int result = NO_SUCH_PAGE;    
            // first page is index 0, if 1 page max index is 0
            if (pageIndex < this.totalPages) {                    

                Graphics2D g2d = (Graphics2D) graphics;                    
                System.out.println("[Print] " + dump(pageFormat));                    

                double width = pageFormat.getImageableWidth();
                double height = pageFormat.getImageableHeight();    
                g2d.translate((int) pageFormat.getImageableX(), 
                    (int) pageFormat.getImageableY());
                System.out.printf("wxh = (%fx%f)", width,height);

                // Max of 6 labels per page
                int maxLabelsOnPage = 6;
                if (pageIndex == 0) {
                    maxLabelsOnPage = 6 - startAtLabel;
                }

                // Loop for up to the max number of labels or until we run out 
                // of labels
                for (int labelCnt=0; labelCnt < maxLabelsOnPage; labelCnt++) {

                    // We have run out of labels and there is nothing left to print
                    if (this.labels.isEmpty()) {
                        break;
                    }

                    // Remove the label from the list and add it to the printed list
                    ClientProject cp = this.labels.remove(0);
                    this.printed.add(cp);

                    // Create the image for the label
                    BufferedImage image = null;
                    try {

                        // Create the image for the label
                        LabelImage li = new LabelImage();
                        BufferedImage bi = li.createImageWithText(cp);

                        // Load the label image
                        //image = ImageIO.read(new File("C:\\Consulting\\Development\\JJCPA\\finland.png"));
                        System.out.printf("image %d x %d%n", bi.getWidth(), bi.getHeight());

                        // Draw the image at the label offset
                        graphics.drawImage(bi, 0, 0, bi.getWidth(), bi.getHeight(), null);

                        // Write to a file to verify the image is valid
                        File outputfile = new File("image.png");
                        ImageIO.write(bi, "png", outputfile);
                    } catch (IOException e) {
                    }
                }

                result = PAGE_EXISTS;    
            }    
            return result;    
        }
    }
}

ClientProject是一个简单的数据结构。

public class ClientProject {

    private final SimpleIntegerProperty projectId;
    private final SimpleIntegerProperty clientId;
    private final SimpleStringProperty category;
    private final SimpleStringProperty type;
    private final SimpleStringProperty projectDesc;
    private final SimpleStringProperty projectName;
    private final SimpleStringProperty projectName2;
    private final SimpleStringProperty fileOrBinder;
    private final ObjectProperty <LocalDate> created;
    private final ObjectProperty <LocalDate> destroyed;

1 个答案:

答案 0 :(得分:0)

逻辑错误。我想我可以在调用方法时轻松渲染单个页面,直到我为每个标签创建图像。 0thus,我跟踪了我打印的标签。这是错的。我需要为索引1打印一个通过b标签多次调用索引1,然后在每次传递索引2时打印下一组标签,重写此逻辑解决了问题。