PDF to ZPL conversion

Any IBM i topic that does not fit in another forum
Post Reply
User avatar
Ticonderogah
Posts: 3
Joined: Wed Jul 28, 2021 12:05 pm

PDF to ZPL conversion

Post by Ticonderogah »

Anyone know of a way to convert .PDF documents into ZPLII language? I'm currently using java to convert .PNG to ZPLII (see below) but it won't work for PDF's. It reads the .PNG from an IFS directory (first parameter) then stores the converted data in another IFS directory(second parameter). We're using this for carrier shipping labels. Another issue I'm running into is that the PDF documents I want to convert contain multiple shipping labels. Not sure how to break those up into separate blocks for the conversion.

I've found some examples online that use PHP and .NET to do this but I'd rather use java if possible. I'm no java guru... but I've put in the time to figure out how to store, compile, and prototype java on the 400. Don't really have time to spend learning all those things with a different language. I suppose an alternative would be to convert the .PDF to .PNG images then use the code below... Any ideas?

ZPLConverter.java

Code: Select all

import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import javax.imageio.ImageIO;
import java.lang.Exception;
import java.lang.ClassLoader;
import java.io.File;
public class ZPLConverter {
    private int blackLimit = 380;
    private int total;
    private int widthBytes;
    private boolean compressHex = false;
    private static Map<Integer, String> mapCode = new HashMap<Integer, String>();
    {
        mapCode.put(1, "G");
        mapCode.put(2, "H");
        mapCode.put(3, "I");
        mapCode.put(4, "J");
        mapCode.put(5, "K");
        mapCode.put(6, "L");
        mapCode.put(7, "M");
        mapCode.put(8, "N");
        mapCode.put(9, "O");
        mapCode.put(10, "P");
        mapCode.put(11, "Q");
        mapCode.put(12, "R");
        mapCode.put(13, "S");
        mapCode.put(14, "T");
        mapCode.put(15, "U");
        mapCode.put(16, "V");
        mapCode.put(17, "W");
        mapCode.put(18, "X");
        mapCode.put(19, "Y");
        mapCode.put(20, "g");
        mapCode.put(40, "h");
        mapCode.put(60, "i");
        mapCode.put(80, "j");
        mapCode.put(100, "k");
        mapCode.put(120, "l");
        mapCode.put(140, "m");
        mapCode.put(160, "n");
        mapCode.put(180, "o");
        mapCode.put(200, "p");
        mapCode.put(220, "q");
        mapCode.put(240, "r");
        mapCode.put(260, "s");
        mapCode.put(280, "t");
        mapCode.put(300, "u");
        mapCode.put(320, "v");
        mapCode.put(340, "w");
        mapCode.put(360, "x");
        mapCode.put(380, "y");        
        mapCode.put(400, "z");            
    }
    public String convertfromImg(BufferedImage image) throws IOException {
        String cuerpo = createBody(image);
        if(compressHex)
           cuerpo = encodeHexAscii(cuerpo);
        return headDoc() + cuerpo + footDoc();        
    }
    private String createBody(BufferedImage orginalImage) throws IOException {
        StringBuffer sb = new StringBuffer();
        Graphics2D graphics = orginalImage.createGraphics();
        graphics.drawImage(orginalImage, 0, 0, null);
        int height = orginalImage.getHeight();
        int width = orginalImage.getWidth();
        int rgb, red, green, blue, index=0;        
        char auxBinaryChar[] =  {'0', '0', '0', '0', '0', '0', '0', '0'};
        widthBytes = width/8;
        if(width%8>0){
            widthBytes= (((int)(width/8))+1);
        } else {
            widthBytes= width/8;
        }
        this.total = widthBytes*height;
        for (int h = 0; h<height; h++)
        {
            for (int w = 0; w<width; w++)
            {
                rgb = orginalImage.getRGB(w, h);
                red = (rgb >> 16 ) & 0x000000FF;
                green = (rgb >> 8 ) & 0x000000FF;
                blue = (rgb) & 0x000000FF;
                char auxChar = '1';
                int totalColor = red + green + blue;
                if(totalColor>blackLimit){
                    auxChar = '0';
                }
                auxBinaryChar[index] = auxChar;
                index++;
                if(index==8 || w==(width-1)){
                    sb.append(fourByteBinary(new String(auxBinaryChar)));
                    auxBinaryChar =  new char[]{'0', '0', '0', '0', '0', '0', '0', '0'};
                    index=0;
                }
            }
            sb.append("\n");
        }
        return sb.toString();
    }
    private String fourByteBinary(String binaryStr){
        int decimal = Integer.parseInt(binaryStr,2);
        if (decimal>15){
            return Integer.toString(decimal,16).toUpperCase();
        } else {
            return "0" + Integer.toString(decimal,16).toUpperCase();
        }
    }
    private String encodeHexAscii(String code){
        int maxlinea =  widthBytes * 2;        
        StringBuffer sbCode = new StringBuffer();
        StringBuffer sbLinea = new StringBuffer();
        String previousLine = null;
        int counter = 1;
        char aux = code.charAt(0);
        boolean firstChar = false; 
        for(int i = 1; i< code.length(); i++ ){
            if(firstChar){
                aux = code.charAt(i);
                firstChar = false;
                continue;
            }
            if(code.charAt(i)=='\n'){
                if(counter>=maxlinea && aux=='0'){
                    sbLinea.append(",");
                } else     if(counter>=maxlinea && aux=='F'){
                    sbLinea.append("!");
                } else if (counter>20){
                    int multi20 = (counter/20)*20;
                    int resto20 = (counter%20);
                    sbLinea.append(mapCode.get(multi20));
                    if(resto20!=0){
                        sbLinea.append(mapCode.get(resto20) + aux);    
                    } else {
                        sbLinea.append(aux);    
                    }
                } else {
                    sbLinea.append(mapCode.get(counter) + aux);
                    if(mapCode.get(counter)==null){
                    }
                }
                counter = 1;
                firstChar = true;
                if(sbLinea.toString().equals(previousLine)){
                    sbCode.append(":");
                } else {
                    sbCode.append(sbLinea.toString());
                }                
                previousLine = sbLinea.toString();
                sbLinea.setLength(0);
                continue;
            }
            if(aux == code.charAt(i)){
                counter++;                
            } else {
                if(counter>20){
                    int multi20 = (counter/20)*20;
                    int resto20 = (counter%20);
                    sbLinea.append(mapCode.get(multi20));
                    if(resto20!=0){
                        sbLinea.append(mapCode.get(resto20) + aux);    
                    } else {
                        sbLinea.append(aux);    
                    }
                } else {
                    sbLinea.append(mapCode.get(counter) + aux);
                }
                counter = 1;
                aux = code.charAt(i);
            }            
        }
        return sbCode.toString();
    }
    private String headDoc(){
        String str = "^XA " +
                        "^FO0,0^GFA,"+ total + ","+ total + "," + widthBytes +", ";
        return str;
    }
    private String footDoc(){
        String str = "^FS"+
                        "^XZ";        
        return str;
    }
    public void setCompressHex(boolean compressHex) {
        this.compressHex = compressHex;
    }
    public void setBlacknessLimitPercentage(int percentage){
        blackLimit = ( percentage * 768 / 100);
    }
    public static void main(String[] args) throws Exception {
      //  BufferedImage orginalImage = ImageIO.read(new File(args[0].trim()));
		BufferedImage orginalImage = ImageIO.read(new File("/home/AS5289/ZPL/image01.png"));
        ZPLConverter zp = new ZPLConverter();
        zp.setCompressHex(true);
        zp.setBlacknessLimitPercentage(50);     
			args[0] = zp.convertfromImg(orginalImage);
		//  System.out.println(args[1].trim());
       // System.out.println(zp.convertfromImg(orginalImage)); 
    }
}
RPG Source

Code: Select all

H DFTACTGRP(*NO)
     ************************************************
      /COPY QSYSINC/QRPGLESRC,JNI
      /copy libhttp2/qrpglesrc,ifsio_h
      *---Java-Variables--------------------------
       dcl-s j_mainParam0 object(*JAVA : 'java.lang.String' ) Dim(2);
       dcl-s airstring Object(*JAVA:'java.lang.String');
      *------EBCDIC-char-to-Java-String--------------------
       dcl-pr makestring Object(*JAVA:'java.lang.String') extproc (*JAVA:
                                      'java.lang.String':*CONSTRUCTOR );
           bytes varchar(60) const;
       end-pr;
      *-----Java-String-to-EBCDIC-char---------------------
       dcl-pr getBytes varchar(300000) extproc(*JAVA:'java.lang.String':
                                                             'getBytes');
       End-Pr;
      *----ZPLConverter-png-to-ZPL-Java-Method---------------------
         dcl-pr main  extproc(*JAVA : 'ZPLConverter' : 'main' ) Static;
           arg0 Object(*JAVA : 'java.lang.String' ) Dim(2) Options(*VARSIZE);
         end-pr;
      *----Qc3ExecuteCommand-prototype-------------------------
          dcl-pr QcmdExc extpgm;
            *n char(512) options(*varsize) const;
            *n packed(15:5) const;
          end-pr;
      *---Main-prototype---------------------------------------
          dcl-pr Mainz extpgm('JVPNGZPL2');
            *n char(150);
            *n char(150);
          end-pr;

          dcl-pi Mainz;
            imgin char(150);
            imgout char(150);
          end-pi;
      *---Standalone-Variables------------------------------
            dcl-s cmd varchar(512);
            dcl-s len packed(15:5);
            dcl-s t char(1) inz('''');
            dcl-s label char(300000);
            dcl-s rdd int(10);
            dcl-s xout varchar(150);
            dcl-s xin varchar(150);
      *-----------------------------------------------------
       /Free
          xout = %trim(imgout);
          xin = %trim(imgin);
        cmd = 'ADDENVVAR ENVVAR(CLASSPATH) VALUE(' + t + '.:' +
              '/OPS_util/Java/jt400.jar:/OPS_util/Java' +
                                          t + ') REPLACE(*YES)';
              len = %len(%trim(cmd));
             QcmdExc(cmd:len);

             airstring = makestring(%trim(imgin));
              j_mainParam0(1) = airstring;
                 Clear airstring;

             airstring = makestring(' ');
              j_mainParam0(2) = airstring;
                 Clear airstring;

              main( j_mainParam0);

               label = getBytes(j_mainParam0(2));

                 len = %len(%trim(label));
      **Create output file(remove it if it exists)
          unlink(xout);
             rdd = open(xout
                       :%bitor(O_WRONLY:O_CREAT:O_EXCL
                       :O_CCSID:O_INHERITMODE)
                       :0
                       :0);

                  callp write(rdd
                             :%addr(label)
                             :len);
                  callp close(rdd);
              unlink(xin);

         *inlr = *on;
       /End-Free
      *--------------------------------------------
Post Reply