2016-11-24 103 views
1

我正在編寫程序來生成標籤並使用標籤紙打印標準打印標籤。我可以創建一張圖像並保存,但是,我在標籤紙上打印圖像時遇到問題。它是空白的。我可以將圖像寫入磁盤並打開圖像,它似乎是一個有效的圖像。但是,無論我做什麼,我都無法打印它。我寫了一個測試程序來嘗試打印它無濟於事。我從網上下載了一張圖片,並能夠打印該圖片。無法將標籤打印到打印機

創建的標籤需要打印在標籤紙上(從上到下包含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

這是一個非常多的不必要的代碼 - 你能提供一個[最小的,完整的和可驗證的](http://stackoverflow.com/help/mcve)的例子嗎? – Jerrybibo

+0

這是完整的示例程序。我只是一個測試打印:阿貝爾計劃,簡單地從文件加載一個圖像,並打印它,它的工作。我在這裏創建了一個PrintLabel應用程序不喜歡的圖像。我無法弄清楚它是什麼。除了刪除一些調試(這是我的錯誤沒有得到它全部),沒有太多的刪除,將離開正在運行的程序與我試圖解決的問題。 – user1777296

回答

0

該邏輯有一個錯誤。我認爲在調用方法時我可以輕鬆地呈現單個頁面,直到完成爲每個標籤創建圖像爲止。 0,我跟蹤了我打印的標籤。這是錯誤的。我需要爲索引1打印一個通過b標籤的次數爲索引1被調用的次數,然後每次索引2通過時打印下一組標籤,重寫此邏輯解決了問題。