Esempio n. 1
0
        private static void appendECI(CharacterSetECI eci, BitArray bits)
        {
            bits.appendBits(Mode.ECI.Bits, 4);

            // This is correct for values up to 127, which is all we need now.
            bits.appendBits(eci.Value, 8);
        }
Esempio n. 2
0
        private static bool decodeByteSegment(BitSource bits,
                                              StringBuilder result,
                                              int count,
                                              CharacterSetECI currentCharacterSetECI,
                                              IList <byte[]> byteSegments,
                                              IDictionary <DecodeHintType, object> hints)
        {
            // Don't crash trying to read more bits than we have available.
            if (count << 3 > bits.available())
            {
                return(false);
            }

            byte[] readBytes = new byte[count];
            for (int i = 0; i < count; i++)
            {
                readBytes[i] = (byte)bits.readBits(8);
            }
            String encoding;

            if (currentCharacterSetECI == null)
            {
                // The spec isn't clear on this mode; see
                // section 6.4.5: t does not say which encoding to assuming
                // upon decoding. I have seen ISO-8859-1 used as well as
                // Shift_JIS -- without anything like an ECI designator to
                // give a hint.
                encoding = StringUtils.guessEncoding(readBytes, hints);
            }
            else
            {
                encoding = currentCharacterSetECI.EncodingName;
            }
            try
            {
                result.Append(Encoding.GetEncoding(encoding).GetString(readBytes, 0, readBytes.Length));
            }
#if WindowsCE
            catch (PlatformNotSupportedException)
            {
                // WindowsCE doesn't support all encodings. But it is device depended.
                // So we try here the some different ones
                if (encoding == "ISO-8859-1")
                {
                    result.Append(Encoding.GetEncoding(1252).GetString(readBytes, 0, readBytes.Length));
                }
                else
                {
                    result.Append(Encoding.GetEncoding("UTF-8").GetString(readBytes, 0, readBytes.Length));
                }
            }
#endif
            catch (Exception)
            {
                return(false);
            }
            byteSegments.Add(readBytes);

            return(true);
        }
Esempio n. 3
0
        private static void addCharacterSet(int value_Renamed, System.String encodingName)
        {
            CharacterSetECI eci = new CharacterSetECI(value_Renamed, encodingName);

            VALUE_TO_ECI[(System.Int32)value_Renamed] = eci;             // can't use valueOf
            NAME_TO_ECI[encodingName] = eci;
        }
Esempio n. 4
0
        private void ZXEncode(string content, int option)
        {
            System.String encoding = QRCodeConstantVariable.DefaultEncoding;
            ErrorCorrectionLevelInternal m_EcLevelInternal = ErrorCorrectionLevelInternal.H;
            QRCodeInternal qrCodeInternal = new QRCodeInternal();

            // Step 1: Choose the mode (encoding).
            Mode mode = EncoderInternal.chooseMode(content, encoding);

            // Step 2: Append "bytes" into "dataBits" in appropriate encoding.
            BitVector dataBits = new BitVector();

            EncoderInternal.appendBytes(content, mode, dataBits, encoding);
            // Step 3: Initialize QR code that can contain "dataBits".
            int numInputBytes = dataBits.sizeInBytes();

            EncoderInternal.initQRCode(numInputBytes, m_EcLevelInternal, mode, qrCodeInternal);

            // Step 4: Build another bit vector that contains header and data.
            BitVector headerAndDataBits = new BitVector();

            // Step 4.5: Append ECI message if applicable
            if (mode == Mode.BYTE && !QRCodeConstantVariable.DefaultEncoding.Equals(encoding))
            {
                CharacterSetECI eci = CharacterSetECI.getCharacterSetECIByName(encoding);
                if (eci != null)
                {
                    EncoderInternal.appendECI(eci, headerAndDataBits);
                }
            }

            EncoderInternal.appendModeInfo(mode, headerAndDataBits);

            int numLetters = mode.Equals(Mode.BYTE)?dataBits.sizeInBytes():content.Length;

            EncoderInternal.appendLengthInfo(numLetters, qrCodeInternal.Version, mode, headerAndDataBits);
            headerAndDataBits.appendBitVector(dataBits);

            // Step 5: Terminate the bits properly.
            EncoderInternal.terminateBits(qrCodeInternal.NumDataBytes, headerAndDataBits);

            // Step 6: Interleave data bits with error correction code.
            BitVector finalBits = new BitVector();

            EncoderInternal.interleaveWithECBytes(headerAndDataBits, qrCodeInternal.NumTotalBytes, qrCodeInternal.NumDataBytes, qrCodeInternal.NumRSBlocks, finalBits);

            if (option == 3)
            {
                return;
            }

            // Step 7: Choose the mask pattern and set to "QRCodeInternal".
            ByteMatrix matrix = new ByteMatrix(qrCodeInternal.MatrixWidth, qrCodeInternal.MatrixWidth);

            qrCodeInternal.MaskPattern = EncoderInternal.chooseMaskPattern(finalBits, qrCodeInternal.EcLevelInternal, qrCodeInternal.Version, matrix);

            // Step 8.  Build the matrix and set it to "QRCodeInternal".
            MatrixUtil.buildMatrix(finalBits, qrCodeInternal.EcLevelInternal, qrCodeInternal.Version, qrCodeInternal.MaskPattern, matrix);
            qrCodeInternal.Matrix = matrix;
        }
        private static bool DecodeByteSegment(BitSource bits,
                                              StringBuilder result,
                                              int count,
                                              CharacterSetECI currentCharacterSetECI,
                                              IList <byte[]> byteSegments)
        {
            // Don't crash trying to read more bits than we have available.
            if (count << 3 > bits.Available())
            {
                return(false);
            }

            byte[] readBytes = new byte[count];
            for (int i = 0; i < count; i++)
            {
                readBytes[i] = (byte)bits.ReadBits(8);
            }
            String encoding;

            if (currentCharacterSetECI == null)
            {
                // The spec isn't clear on this mode; see
                // section 6.4.5: t does not say which encoding to assuming
                // upon decoding. I have seen ISO-8859-1 used as well as
                // Shift_JIS -- without anything like an ECI designator to
                // give a hint.
                encoding = StringUtils.GuessEncoding(readBytes);
            }
            else
            {
                encoding = currentCharacterSetECI.EncodingName;
            }
            try
            {
                result.Append(Encoding.GetEncoding(encoding).GetString(readBytes, 0, readBytes.Length));
            }
            catch (ArgumentException)
            {
                try
                {
                    // Silverlight only supports a limited number of character sets, trying fallback to UTF-8
                    result.Append(Encoding.GetEncoding("UTF-8").GetString(readBytes, 0, readBytes.Length));
                }
                catch (Exception)
                {
                    return(false);
                }
            }
            catch (Exception)
            {
                return(false);
            }
            byteSegments.Add(readBytes);

            return(true);
        }
Esempio n. 6
0
        private static void addCharacterSet(int value_Renamed, System.String[] encodingNames)
        {
            CharacterSetECI eci = new CharacterSetECI(value_Renamed, encodingNames[0]);

            VALUE_TO_ECI[(System.Int32)value_Renamed] = eci;             // can't use valueOf
            for (int i = 0; i < encodingNames.Length; i++)
            {
                NAME_TO_ECI[encodingNames[i]] = eci;
            }
        }
        /// <summary>
        /// Combine Gma.QrCodeNet.Encoding input recognition method and version control method
        /// with legacy code. To create expected answer.
        /// This is base on assume Gma.QrCodeNet.Encoding input recognition and version control sometime
        /// give different result as legacy code.
        /// </summary>
        /// <param name="content"></param>
        /// <returns></returns>
        internal static BitVector DataEncodeUsingReferenceImplementation(string content, ErrorCorrectionLevel ecLevel, out QRCodeInternal qrInternal)
        {
            if (string.IsNullOrEmpty(content))
            {
                throw new ArgumentException("input string content can not be null or empty");
            }

            //Choose mode
            RecognitionStruct recognitionResult = InputRecognise.Recognise(content);
            string            encodingName      = recognitionResult.EncodingName;
            Mode mode = ConvertMode(recognitionResult.Mode);

            //append byte to databits
            BitVector dataBits = new BitVector();

            EncoderInternal.appendBytes(content, mode, dataBits, encodingName);

            int dataBitsLength            = dataBits.size();
            VersionControlStruct vcStruct =
                VersionControl.InitialSetup(dataBitsLength, recognitionResult.Mode, ecLevel, recognitionResult.EncodingName);
            //ECI
            BitVector headerAndDataBits = new BitVector();
            string    defaultByteMode   = "iso-8859-1";

            if (mode == Mode.BYTE && !defaultByteMode.Equals(encodingName))
            {
                CharacterSetECI eci = CharacterSetECI.getCharacterSetECIByName(encodingName);
                if (eci != null)
                {
                    EncoderInternal.appendECI(eci, headerAndDataBits);
                }
            }
            //Mode
            EncoderInternal.appendModeInfo(mode, headerAndDataBits);
            //Char info
            int numLetters = mode.Equals(Mode.BYTE)?dataBits.sizeInBytes():content.Length;

            EncoderInternal.appendLengthInfo(numLetters, vcStruct.VersionDetail.Version, mode, headerAndDataBits);
            //Combine with dataBits
            headerAndDataBits.appendBitVector(dataBits);

            // Terminate the bits properly.
            EncoderInternal.terminateBits(vcStruct.VersionDetail.NumDataBytes, headerAndDataBits);

            qrInternal                 = new QRCodeInternal();
            qrInternal.Version         = vcStruct.VersionDetail.Version;
            qrInternal.MatrixWidth     = vcStruct.VersionDetail.MatrixWidth;
            qrInternal.EcLevelInternal = ErrorCorrectionLevelConverter.ToInternal(ecLevel);
            qrInternal.NumTotalBytes   = vcStruct.VersionDetail.NumTotalBytes;
            qrInternal.NumDataBytes    = vcStruct.VersionDetail.NumDataBytes;
            qrInternal.NumRSBlocks     = vcStruct.VersionDetail.NumECBlocks;
            return(headerAndDataBits);
        }
Esempio n. 8
0
 /// <param name="value">ECI value
 /// </param>
 /// <returns> {@link ECI} representing ECI of given value, or null if it is legal but unsupported
 /// </returns>
 /// <throws>  IllegalArgumentException if ECI value is invalid </throws>
 internal static ECI getECIByValue(int value_Renamed)
 {
     if (value_Renamed < 0 || value_Renamed > 999999)
     {
         throw new System.ArgumentException("Bad ECI value: " + value_Renamed);
     }
     if (value_Renamed < 900)
     {
         // Character set ECIs use 000000 - 000899
         return(CharacterSetECI.getCharacterSetECIByValue(value_Renamed));
     }
     return(null);
 }
Esempio n. 9
0
            public bool AppendECI(int value)
            {
                encodeCurrentBytesIfAny();
                CharacterSetECI characterSetECI = CharacterSetECI.getCharacterSetECIByValue(value);

                if (characterSetECI == null)
                {
                    return(false);
                    //throw FormatException.getFormatInstance(new RuntimeException("Unsupported ECI value " + value));
                }
                currentCharset = CharacterSetECI.getEncoding(characterSetECI);
                return(true);
            }
Esempio n. 10
0
 /// <param name="val">ECI value</param>
 /// <returns><see cref="ECI"/> representing ECI of given value, or null if it is legal but unsupported</returns>
 /// <throws>ArgumentException if ECI value is invalid </throws>
 public static ECI getECIByValue(int val)
 {
     if (val < 0 || val > 999999)
     {
         throw new System.ArgumentException("Bad ECI value: " + val);
     }
     if (val < 900)
     {
         // Character set ECIs use 000000 - 000899
         return(CharacterSetECI.getCharacterSetECIByValue(val));
     }
     return(null);
 }
Esempio n. 11
0
        private void button_Click(object sender, RoutedEventArgs e)
        {
            var retangulo = new iTextSharp.text.Rectangle(765, 765);
            var documento = new Document(retangulo);

            var writer = PdfWriter.GetInstance(documento, new FileStream(@"c:\teste\teste.pdf", FileMode.Create));

            documento.Open();

            var imagemDoTopo = iTextSharp.text.Image.GetInstance(@"c:\teste\imagem.png");

            imagemDoTopo.SetAbsolutePosition(0, 100);
            documento.Add(imagemDoTopo);

            PdfContentByte cb         = writer.DirectContent;
            BaseFont       outraFonte = BaseFont.CreateFont(BaseFont.COURIER, BaseFont.CP1252, false, false);

            cb.BeginText();
            cb.SetFontAndSize(outraFonte, 12);
            cb.SetColorFill(new BaseColor(51, 51, 51));
            cb.ShowTextAligned(PdfContentByte.ALIGN_LEFT, "TESTE", 50, 35, 50);
            cb.EndText();

            var paramQR = new Dictionary <EncodeHintType, object>();

            paramQR.Add(EncodeHintType.CHARACTER_SET, CharacterSetECI.GetCharacterSetECIByName("UTF-8"));
            BarcodeQRCode qrCodigo = new BarcodeQRCode("https://www.youtube.com/channel/UCcOGfx3w8BRxkfSyZFsW5fQ",
                                                       150, 150, paramQR);

            iTextSharp.text.Image imgBarCode = qrCodigo.GetImage();
            imgBarCode.SetAbsolutePosition(200, 200);
            documento.Add(imgBarCode);

            BarcodeEAN codeEAN13 = null;

            codeEAN13                  = new BarcodeEAN();
            codeEAN13.CodeType         = Barcode.EAN13;
            codeEAN13.ChecksumText     = true;
            codeEAN13.GenerateChecksum = true;
            codeEAN13.BarHeight        = 12;
            codeEAN13.Code             = "1234567890123";
            imgBarCode                 = codeEAN13.CreateImageWithBarcode(cb, null, null);
            imgBarCode.SetAbsolutePosition(150, 150);
            imgBarCode.Alignment = iTextSharp.text.Image.TEXTWRAP;
            documento.Add(imgBarCode);



            documento.Close();
        }
Esempio n. 12
0
        private static bool decodeByteSegment(BitSource bits,
                                              StringBuilder result,
                                              int count,
                                              CharacterSetECI currentCharacterSetECI,
                                              IList byteSegments,
                                              Hashtable hints)
        {
            // Don't crash trying to read more bits than we have available.
            if (count << 3 > bits.available())
            {
                return(false);
            }

            byte[] readBytes = new byte[count];
            for (int i = 0; i < count; i++)
            {
                readBytes[i] = (byte)bits.readBits(8);
            }
            String encoding;

            if (currentCharacterSetECI == null)
            {
                // The spec isn't clear on this mode; see
                // section 6.4.5: t does not say which encoding to assuming
                // upon decoding. I have seen ISO-8859-1 used as well as
                // Shift_JIS -- without anything like an ECI designator to
                // give a hint.
                encoding = StringUtils.guessEncoding(readBytes, hints);
            }
            else
            {
                encoding = currentCharacterSetECI.EncodingName;
            }
            try
            {
                result.Append(Encoding.UTF8.GetChars(readBytes, 0, readBytes.Length));
            }
            catch (Exception)
            {
                return(false);
            }
            byteSegments.Add(readBytes);

            return(true);
        }
Esempio n. 13
0
        static MinimalEncoder()
        {
            var names = new[]
            {
                "ISO-8859-2",
                "ISO-8859-3",
                "ISO-8859-4",
                "ISO-8859-5",
                "ISO-8859-6",
                "ISO-8859-7",
                "ISO-8859-8",
                "ISO-8859-9",
                "ISO-8859-10",
                "ISO-8859-11",
                "ISO-8859-13",
                "ISO-8859-14",
                "ISO-8859-15",
                "ISO-8859-16",
                "windows-1250",
                "windows-1251",
                "windows-1252",
                "windows-1253",
                "windows-1254",
                "windows-1255",
                "windows-1256",
                "windows-1257",
                "windows-1258",
                "Shift_JIS"
            };

            foreach (String name in names)
            {
                if (CharacterSetECI.getCharacterSetECIByName(name) != null)
                {
                    try
                    {
                        ENCODERS.Add(Clone(Encoding.GetEncoding(name)));
                    }
                    catch (Exception)
                    {
                        // continue
                    }
                }
            }
        }
        private static bool decodeByteSegment(BitSource bits,
                                              StringBuilder result,
                                              int count,
                                              CharacterSetECI currentCharacterSetECI,
                                              IList <byte[]> byteSegments,
                                              IDictionary <DecodeHintType, object> hints)
        {
            // Don't crash trying to read more bits than we have available.
            if (count << 3 > bits.available())
            {
                return(false);
            }

            byte[] readBytes = new byte[count];
            for (int i = 0; i < count; i++)
            {
                readBytes[i] = (byte)bits.readBits(8);
            }
            Encoding encoding;

            if (currentCharacterSetECI == null)
            {
                // The spec isn't clear on this mode; see
                // section 6.4.5: t does not say which encoding to assuming
                // upon decoding. I have seen ISO-8859-1 used as well as
                // Shift_JIS -- without anything like an ECI designator to
                // give a hint.
                encoding = StringUtils.guessCharset(readBytes, hints);
            }
            else
            {
                encoding = CharacterSetECI.getEncoding(currentCharacterSetECI.EncodingName);
            }
            if (encoding == null)
            {
                encoding = StringUtils.PLATFORM_DEFAULT_ENCODING_T;
            }
            result.Append(encoding.GetString(readBytes, 0, readBytes.Length));

            byteSegments.Add(readBytes);

            return(true);
        }
Esempio n. 15
0
 /// <summary>
 /// appends the bits
 /// </summary>
 /// <param name="bits"></param>
 public void getBits(BitArray bits)
 {
     bits.appendBits(mode.Bits, 4);
     if (characterLength > 0)
     {
         int length = CharacterCountIndicator;
         bits.appendBits(length, mode.getCharacterCountBits(resultList.version));
     }
     if (mode == Mode.ECI)
     {
         bits.appendBits(CharacterSetECI.getCharacterSetECI(encoder.encoders[charsetEncoderIndex]).Value, 8);
     }
     else if (characterLength > 0)
     {
         // append data
         Encoder.appendBytes(encoder.stringToEncode.Substring(fromPosition, characterLength), mode, bits,
                             encoder.encoders[charsetEncoderIndex]);
     }
 }
Esempio n. 16
0
        internal static DecoderResult decode(int[] codewords, String ecLevel)
        {
            var result = new StringBuilder(codewords.Length * 2);
            // Get compaction mode
            int      codeIndex      = 1;
            int      code           = codewords[codeIndex++];
            var      resultMetadata = new PDF417ResultMetadata();
            Encoding encoding       = null;

            while (codeIndex < codewords[0])
            {
                switch (code)
                {
                case TEXT_COMPACTION_MODE_LATCH:
                    codeIndex = textCompaction(codewords, codeIndex, result);
                    break;

                case BYTE_COMPACTION_MODE_LATCH:
                case BYTE_COMPACTION_MODE_LATCH_6:
                    codeIndex = byteCompaction(code, codewords, encoding ?? (encoding = getEncoding(PDF417HighLevelEncoder.DEFAULT_ENCODING_NAME)), codeIndex, result);
                    break;

                case MODE_SHIFT_TO_BYTE_COMPACTION_MODE:
                    result.Append((char)codewords[codeIndex++]);
                    break;

                case NUMERIC_COMPACTION_MODE_LATCH:
                    codeIndex = numericCompaction(codewords, codeIndex, result);
                    break;

                case ECI_CHARSET:
                    var charsetECI = CharacterSetECI.getCharacterSetECIByValue(codewords[codeIndex++]);
                    encoding = getEncoding(charsetECI.EncodingName);
                    break;

                case ECI_GENERAL_PURPOSE:
                    // Can't do anything with generic ECI; skip its 2 characters
                    codeIndex += 2;
                    break;

                case ECI_USER_DEFINED:
                    // Can't do anything with user ECI; skip its 1 character
                    codeIndex++;
                    break;

                case BEGIN_MACRO_PDF417_CONTROL_BLOCK:
                    codeIndex = decodeMacroBlock(codewords, codeIndex, resultMetadata);
                    break;

                case BEGIN_MACRO_PDF417_OPTIONAL_FIELD:
                case MACRO_PDF417_TERMINATOR:
                    // Should not see these outside a macro block
                    return(null);

                default:
                    // Default to text compaction. During testing numerous barcodes
                    // appeared to be missing the starting mode. In these cases defaulting
                    // to text compaction seems to work.
                    codeIndex--;
                    codeIndex = textCompaction(codewords, codeIndex, result);
                    break;
                }
                if (codeIndex < 0)
                {
                    return(null);
                }
                if (codeIndex < codewords.Length)
                {
                    code = codewords[codeIndex++];
                }
                else
                {
                    return(null);
                }
            }

            if (result.Length == 0)
            {
                return(null);
            }

            var decoderResult = new DecoderResult(null, result.ToString(), null, ecLevel);

            decoderResult.Other = resultMetadata;
            return(decoderResult);
        }
Esempio n. 17
0
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in .NET:
//ORIGINAL LINE: static com.google.zxing.common.DecoderResult decode(byte[] bytes, Version version, ErrorCorrectionLevel ecLevel, java.util.Map<com.google.zxing.DecodeHintType,?> hints) throws com.google.zxing.FormatException
        internal static DecoderResult decode(sbyte[] bytes, Version version, ErrorCorrectionLevel ecLevel, IDictionary <DecodeHintType, object> hints)
        {
            BitSource       bits         = new BitSource(bytes);
            StringBuilder   result       = new StringBuilder(50);
            IList <sbyte[]> byteSegments = new List <sbyte[]>(1);

            try
            {
                CharacterSetECI currentCharacterSetECI = null;
                bool            fc1InEffect            = false;
                Mode            mode;
                do
                {
                    // While still another segment to read...
                    if (bits.available() < 4)
                    {
                        // OK, assume we're done. Really, a TERMINATOR mode should have been recorded here
                        mode = Mode.TERMINATOR;
                    }
                    else
                    {
                        mode = Mode.forBits(bits.readBits(4));   // mode is encoded by 4 bits
                    }
                    if (mode != Mode.TERMINATOR)
                    {
                        if (mode == Mode.FNC1_FIRST_POSITION || mode == Mode.FNC1_SECOND_POSITION)
                        {
                            // We do little with FNC1 except alter the parsed result a bit according to the spec
                            fc1InEffect = true;
                        }
                        else if (mode == Mode.STRUCTURED_APPEND)
                        {
                            if (bits.available() < 16)
                            {
                                throw FormatException.FormatInstance;
                            }
                            // not really supported; all we do is ignore it
                            // Read next 8 bits (symbol sequence #) and 8 bits (parity data), then continue
                            bits.readBits(16);
                        }
                        else if (mode == Mode.ECI)
                        {
                            // Count doesn't apply to ECI
                            int value = parseECIValue(bits);
                            currentCharacterSetECI = CharacterSetECI.getCharacterSetECIByValue(value);
                            if (currentCharacterSetECI == null)
                            {
                                throw FormatException.FormatInstance;
                            }
                        }
                        else
                        {
                            // First handle Hanzi mode which does not start with character count
                            if (mode == Mode.HANZI)
                            {
                                //chinese mode contains a sub set indicator right after mode indicator
                                int subset     = bits.readBits(4);
                                int countHanzi = bits.readBits(mode.getCharacterCountBits(version));
                                if (subset == GB2312_SUBSET)
                                {
                                    decodeHanziSegment(bits, result, countHanzi);
                                }
                            }
                            else
                            {
                                // "Normal" QR code modes:
                                // How many characters will follow, encoded in this mode?
                                int count = bits.readBits(mode.getCharacterCountBits(version));
                                if (mode == Mode.NUMERIC)
                                {
                                    decodeNumericSegment(bits, result, count);
                                }
                                else if (mode == Mode.ALPHANUMERIC)
                                {
                                    decodeAlphanumericSegment(bits, result, count, fc1InEffect);
                                }
                                else if (mode == Mode.BYTE)
                                {
                                    decodeByteSegment(bits, result, count, currentCharacterSetECI, byteSegments, hints);
                                }
                                else if (mode == Mode.KANJI)
                                {
                                    decodeKanjiSegment(bits, result, count);
                                }
                                else
                                {
                                    throw FormatException.FormatInstance;
                                }
                            }
                        }
                    }
                } while (mode != Mode.TERMINATOR);
            }
            catch (System.ArgumentException iae)
            {
                // from readBits() calls
                throw FormatException.FormatInstance;
            }

            return(new DecoderResult(bytes, result.ToString(), byteSegments.Count == 0 ? null : byteSegments, ecLevel == null ? null : ecLevel.ToString()));
        }
        /// <summary>
        /// Performs high-level encoding of a PDF417 message using the algorithm described in annex P
        /// of ISO/IEC 15438:2001(E). If byte compaction has been selected, then only byte compaction
        /// is used.
        /// </summary>
        /// <param name="msg">the message</param>
        /// <param name="compaction">compaction mode to use</param>
        /// <param name="encoding">character encoding used to encode in default or byte compaction
        /// or null for default / not applicable</param>
        /// <param name="disableEci">if true, don't add an ECI segment for different encodings than default</param>
        /// <returns>the encoded message (the char values range from 0 to 928)</returns>
        internal static String encodeHighLevel(String msg, Compaction compaction, Encoding encoding, bool disableEci)
        {
            //the codewords 0..928 are encoded as Unicode characters
            var sb = new StringBuilder(msg.Length);

            if (encoding != null && !disableEci && String.Compare(DEFAULT_ENCODING_NAME, encoding.WebName, StringComparison.Ordinal) != 0)
            {
                CharacterSetECI eci = CharacterSetECI.getCharacterSetECIByName(encoding.WebName);
                if (eci != null)
                {
                    encodingECI(eci.Value, sb);
                }
            }

            int len         = msg.Length;
            int p           = 0;
            int textSubMode = SUBMODE_ALPHA;

            // User selected encoding mode
            switch (compaction)
            {
            case Compaction.TEXT:
                encodeText(msg, p, len, sb, textSubMode);
                break;

            case Compaction.BYTE:
                var msgBytes = toBytes(msg, encoding);
                encodeBinary(msgBytes, p, msgBytes.Length, BYTE_COMPACTION, sb);
                break;

            case Compaction.NUMERIC:
                sb.Append((char)LATCH_TO_NUMERIC);
                encodeNumeric(msg, p, len, sb);
                break;

            default:
                int    encodingMode = TEXT_COMPACTION; //Default mode, see 4.4.2.1
                byte[] bytes        = null;
                while (p < len)
                {
                    int n = determineConsecutiveDigitCount(msg, p);
                    if (n >= 13)
                    {
                        sb.Append((char)LATCH_TO_NUMERIC);
                        encodingMode = NUMERIC_COMPACTION;
                        textSubMode  = SUBMODE_ALPHA; //Reset after latch
                        encodeNumeric(msg, p, n, sb);
                        p += n;
                    }
                    else
                    {
                        int t = determineConsecutiveTextCount(msg, p);
                        if (t >= 5 || n == len)
                        {
                            if (encodingMode != TEXT_COMPACTION)
                            {
                                sb.Append((char)LATCH_TO_TEXT);
                                encodingMode = TEXT_COMPACTION;
                                textSubMode  = SUBMODE_ALPHA; //start with submode alpha after latch
                            }
                            textSubMode = encodeText(msg, p, t, sb, textSubMode);
                            p          += t;
                        }
                        else
                        {
                            if (bytes == null)
                            {
                                bytes = toBytes(msg, encoding);
                            }
                            int b = determineConsecutiveBinaryCount(msg, bytes, p, encoding);
                            if (b == 0)
                            {
                                b = 1;
                            }
                            if (b == 1 && encodingMode == TEXT_COMPACTION)
                            {
                                //Switch for one byte (instead of latch)
                                encodeBinary(bytes, 0, 1, TEXT_COMPACTION, sb);
                            }
                            else
                            {
                                //Mode latch performed by encodeBinary()
                                encodeBinary(bytes,
                                             toBytes(msg.Substring(0, p), encoding).Length,
                                             toBytes(msg.Substring(p, b), encoding).Length,
                                             encodingMode,
                                             sb);
                                encodingMode = BYTE_COMPACTION;
                                textSubMode  = SUBMODE_ALPHA; //Reset after latch
                            }
                            p += b;
                        }
                    }
                }
                break;
            }

            return(sb.ToString());
        }
Esempio n. 19
0
 private static void appendECI(CharacterSetECI eci, BitVector bits)
 {
     bits.appendBits(Mode.ECI.Bits, 4);
     // This is correct for values up to 127, which is all we need now.
     bits.appendBits(eci.Value, 8);
 }
Esempio n. 20
0
        /// <summary>
        /// Performs high-level encoding of a PDF417 message using the algorithm described in annex P
        /// of ISO/IEC 15438:2001(E). If byte compaction has been selected, then only byte compaction
        /// is used.
        ///
        /// <param name="msg">the message</param>
        /// <returns>the encoded message (the char values range from 0 to 928)</returns>
        /// </summary>
        internal static String encodeHighLevel(String msg, Compaction compaction, Encoding encoding, bool disableEci)
        {
            //the codewords 0..928 are encoded as Unicode characters
            var sb = new StringBuilder(msg.Length);

            if (!DEFAULT_ENCODING.Equals(encoding) && !disableEci)
            {
                CharacterSetECI eci = CharacterSetECI.getCharacterSetECIByName(encoding.WebName);
                if (eci != null)
                {
                    encodingECI(eci.Value, sb);
                }
            }

            int len         = msg.Length;
            int p           = 0;
            int textSubMode = SUBMODE_ALPHA;

            // User selected encoding mode
            byte[] bytes = null; //Fill later and only if needed
            if (compaction == Compaction.TEXT)
            {
                encodeText(msg, p, len, sb, textSubMode);
            }
            else if (compaction == Compaction.BYTE)
            {
                bytes = encoding.GetBytes(msg);
                encodeBinary(bytes, p, bytes.Length, BYTE_COMPACTION, sb);
            }
            else if (compaction == Compaction.NUMERIC)
            {
                sb.Append((char)LATCH_TO_NUMERIC);
                encodeNumeric(msg, p, len, sb);
            }
            else
            {
                int encodingMode = TEXT_COMPACTION; //Default mode, see 4.4.2.1
                while (p < len)
                {
                    int n = determineConsecutiveDigitCount(msg, p);
                    if (n >= 13)
                    {
                        sb.Append((char)LATCH_TO_NUMERIC);
                        encodingMode = NUMERIC_COMPACTION;
                        textSubMode  = SUBMODE_ALPHA; //Reset after latch
                        encodeNumeric(msg, p, n, sb);
                        p += n;
                    }
                    else
                    {
                        int t = determineConsecutiveTextCount(msg, p);
                        if (t >= 5 || n == len)
                        {
                            if (encodingMode != TEXT_COMPACTION)
                            {
                                sb.Append((char)LATCH_TO_TEXT);
                                encodingMode = TEXT_COMPACTION;
                                textSubMode  = SUBMODE_ALPHA; //start with submode alpha after latch
                            }
                            textSubMode = encodeText(msg, p, t, sb, textSubMode);
                            p          += t;
                        }
                        else
                        {
                            if (bytes == null)
                            {
                                bytes = encoding.GetBytes(msg);
                            }
                            int b = determineConsecutiveBinaryCount(msg, bytes, p);
                            if (b == 0)
                            {
                                b = 1;
                            }
                            if (b == 1 && encodingMode == TEXT_COMPACTION)
                            {
                                //Switch for one byte (instead of latch)
                                encodeBinary(bytes, p, 1, TEXT_COMPACTION, sb);
                            }
                            else
                            {
                                //Mode latch performed by encodeBinary()
                                encodeBinary(bytes, p, b, encodingMode, sb);
                                encodingMode = BYTE_COMPACTION;
                                textSubMode  = SUBMODE_ALPHA; //Reset after latch
                            }
                            p += b;
                        }
                    }
                }
            }

            return(sb.ToString());
        }
        private void btPdf_Click(object sender, EventArgs e)
        {
            try
            {
                /* ============ PRIMEIRA FORMA ============
                 * //var retangulo = new iTextSharp.text.Rectangle(765, 765);
                 * var documento = new Document(PageSize.A4, 10, 10, 10, 10);
                 *
                 * var writer = PdfWriter.GetInstance(documento, new FileStream(@"c:\teste\teste.pdf", FileMode.Create));
                 *
                 * documento.Open();
                 *
                 * var imagem = iTextSharp.text.Image.GetInstance(@"C:\teste\robin.png");
                 * imagem.SetAbsolutePosition(10,60);
                 * documento.Add(imagem);
                 *
                 * PdfContentByte cb = writer.DirectContent;
                 * BaseFont fonte = BaseFont.CreateFont(BaseFont.COURIER, BaseFont.CP1252, false, false);
                 *
                 * cb.BeginText();
                 * cb.SetFontAndSize(fonte, 12);
                 * cb.SetColorFill(new BaseColor(51, 51, 51));
                 * cb.ShowTextAligned(PdfContentByte.ALIGN_LEFT, "Damian Wayne\nTeste", 20, 800, 0);
                 *
                 * int linhas = dgvDados.RowCount;
                 * int colunas = dgvDados.ColumnCount;
                 *
                 * for (int i = 0; i < linhas; i++)
                 * {
                 *  for (int x = 0; x < colunas; x++)
                 *  {
                 *      cb.ShowTextAligned(PdfContentByte.ALIGN_LEFT, Convert.ToString(dgvDados.Rows[i].Cells[x].Value), 20, 400, 0);
                 *  }
                 * }
                 *
                 * cb.EndText();
                 * documento.Close();
                 *
                 * MessageBox.Show("PDF gerado com sucesso!", "Aviso", MessageBoxButtons.OK, MessageBoxIcon.Information);
                 */

                /*========== SEGUNDA FORMA ==========
                 * CHUNK: é a menor parte de um texto a ser inserido (palavra)
                 * PHRASE: é um conjunto de palavras (frases)
                 * PARAGRAPH: é um paragrafo (conjunto de frases)
                 */
                var documento = new Document(PageSize.A4, 10, 10, 10, 10);

                Stream str;

                SaveFileDialog salvarRelatorioPDF = new SaveFileDialog();

                salvarRelatorioPDF.Filter = "PDF (*.pdf) | *.pdf";

                salvarRelatorioPDF.FilterIndex      = 2;
                salvarRelatorioPDF.Title            = "Salvar Relatorio em PDF";
                salvarRelatorioPDF.RestoreDirectory = true;
                var salvar_dir = "";


                if (salvarRelatorioPDF.ShowDialog() == DialogResult.OK)
                {
                    if ((str = salvarRelatorioPDF.OpenFile()) != null)
                    {
                        salvar_dir = salvarRelatorioPDF.FileName;
                    }
                    else
                    {
                        DialogResult x = MessageBox.Show("Não Foi possivel salvar", "Aviso", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                    str.Close();
                }


                var writer = PdfWriter.GetInstance(documento, new FileStream(salvar_dir, FileMode.Create));

                documento.Open();

                var imagem = iTextSharp.text.Image.GetInstance(@"../../../image.png");
                imagem.SetAbsolutePosition(20, 775);
                documento.Add(imagem);

                var imagem2 = iTextSharp.text.Image.GetInstance(@"../../../image2.png");
                imagem2.SetAbsolutePosition(500, 775);
                documento.Add(imagem2);


                // Definindo as fontes
                var titulo = new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.TIMES_ROMAN, 16, 2, BaseColor.RED);

                var fonte = new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.COURIER, 12, 0, BaseColor.BLACK);

                var letra = new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.COURIER, 10, 0, BaseColor.BLACK);

                var rodape = new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.SYMBOL, 13, 0, BaseColor.BLUE);

                documento.Add(new Paragraph(""));
                documento.Add(new Paragraph(""));
                documento.Add(new Paragraph(""));
                //criando parágrafo
                var paragrafo1 = new Paragraph("R E L A T O R Í O", titulo);
                paragrafo1.Alignment = Element.ALIGN_CENTER;
                documento.Add(paragrafo1);

                var nome1 = new Paragraph("Lucas Anselmo", fonte);
                nome1.Alignment = Element.ALIGN_CENTER;
                documento.Add(nome1);

                var nome2 = new Paragraph("João Vinicius" + "\n" + "_____________________________________________________________________________", fonte);
                nome2.Alignment = Element.ALIGN_CENTER;
                documento.Add(nome2);

                //data do relatorio
                var paragrafo2 = new Paragraph("ITU, " + DateTime.Now.ToLongDateString());
                paragrafo2.Alignment = Element.ALIGN_RIGHT;
                documento.Add(paragrafo2);

                int  linhas  = dgvDados.RowCount;
                int  colunas = dgvDados.ColumnCount;
                var  frase   = new Phrase();
                bool flag    = false;

                for (int i = 0; i < linhas; i++)
                {
                    for (int x = 0; x < colunas; x++)
                    {
                        frase = new Phrase(Convert.ToString(dgvDados.Rows[i].Cells[x].Value) + " - ", letra);
                        //documento.Add(frase);
                        flag = documento.Add(frase);
                    }
                    frase = new Phrase("\n");
                    flag  = documento.Add(frase);
                }

                //gerar codigo de barras
                PdfContentByte cb = writer.DirectContent;
                cb.BeginText();
                iTextSharp.text.Image imgBarCode;

                BarcodeEAN codeEAN = null;
                codeEAN                  = new BarcodeEAN();
                codeEAN.CodeType         = Barcode.EAN13;
                codeEAN.ChecksumText     = true;
                codeEAN.GenerateChecksum = true;
                codeEAN.BarHeight        = 12;
                codeEAN.Code             = "1234567890123";
                imgBarCode               = codeEAN.CreateImageWithBarcode(cb, null, null);
                imgBarCode.SetAbsolutePosition(20, 350);
                imgBarCode.Alignment = iTextSharp.text.Image.TEXTWRAP;
                documento.Add(imgBarCode);
                cb.EndText();

                //Gerar QRCODE
                var paramQR = new Dictionary <EncodeHintType, object>();
                paramQR.Add(EncodeHintType.CHARACTER_SET, CharacterSetECI.GetCharacterSetECIByName("UTF-8"));
                BarcodeQRCode         qrcodigo  = new BarcodeQRCode("http://www.etecitu.com.br", 150, 150, paramQR);
                iTextSharp.text.Image imgQrCode = qrcodigo.GetImage();
                imgQrCode.SetAbsolutePosition(410, 300);
                documento.Add(imgQrCode);

                documento.Close();

                if (flag == true)
                {
                    DialogResult d = MessageBox.Show("Relatorio gerado com sucesso!\nDeseja abri-lo?", "Aviso", MessageBoxButtons.YesNo, MessageBoxIcon.Question);

                    if (d.ToString() == "Yes")
                    {
                        System.Diagnostics.Process.Start(@salvar_dir);
                    }
                }
                else
                {
                    MessageBox.Show("Não foi gerado");
                }
            }
            catch (Exception erro)
            {
                MessageBox.Show(erro.Message);
            }
        }
Esempio n. 22
0
        private static void DecodeByteSegment(BitSource bits, StringBuilder result, int count, CharacterSetECI currentCharacterSetECI, System.Collections.ArrayList byteSegments)
        {
            sbyte[] readBytes = new sbyte[count];
            if (count << 3 > bits.Available())
            {
                throw ReaderException.Instance;
            }
            for (int i = 0; i < count; i++)
            {
                readBytes[i] = (sbyte)bits.ReadBits(8);
            }

            // The spec isn't clear on this mode; see
            // section 6.4.5: t does not say which encoding to assuming
            // upon decoding. I have seen ISO-8859-1 used as well as
            // Shift_JIS -- without anything like an ECI designator to
            // give a hint.
            var encoding = currentCharacterSetECI == null?GuessEncoding(readBytes) : currentCharacterSetECI.EncodingName;

            try
            {
                //UPGRADE_TODO: The differences in the Format  of parameters for constructor 'java.lang.String.String'  may cause compilation errors.  "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1092'"
                result.Append(Encoding.GetEncoding(encoding).GetString(SupportClass.ToByteArray(readBytes)));
            }
            catch (IOException)
            {
                throw ReaderException.Instance;
            }
            byteSegments.Add(SupportClass.ToByteArray(readBytes));
        }
Esempio n. 23
0
        internal static DecoderResult Decode(sbyte[] bytes, Version version, ErrorCorrectionLevel ecLevel)
        {
            BitSource       bits   = new BitSource(bytes);
            StringBuilder   result = new StringBuilder(50);
            CharacterSetECI currentCharacterSetECI = null;
            bool            fc1InEffect            = false;

            System.Collections.ArrayList byteSegments = System.Collections.ArrayList.Synchronized(new System.Collections.ArrayList(1));
            Mode mode;

            do
            {
                // While still another segment to read...
                if (bits.Available() < 4)
                {
                    // OK, assume we're done. Really, a TERMINATOR mode should have been recorded here
                    mode = Mode.TERMINATOR;
                }
                else
                {
                    try
                    {
                        mode = Mode.ForBits(bits.ReadBits(4)); // mode is encoded by 4 bits
                    }
                    catch (ArgumentException)
                    {
                        throw ReaderException.Instance;
                    }
                }
                if (!mode.Equals(Mode.TERMINATOR))
                {
                    if (mode.Equals(Mode.FNC1_FIRST_POSITION) || mode.Equals(Mode.FNC1_SECOND_POSITION))
                    {
                        // We do little with FNC1 except alter the parsed result a bit according to the spec
                        fc1InEffect = true;
                    }
                    else if (mode.Equals(Mode.STRUCTURED_APPEND))
                    {
                        // not really supported; all we do is ignore it
                        // Read next 8 bits (symbol sequence #) and 8 bits (parity data), then continue
                        bits.ReadBits(16);
                    }
                    else if (mode.Equals(Mode.ECI))
                    {
                        // Count doesn't apply to ECI
                        int value_Renamed = ParseECIValue(bits);
                        currentCharacterSetECI = CharacterSetECI.GetCharacterSetECIByValue(value_Renamed);
                        if (currentCharacterSetECI == null)
                        {
                            throw ReaderException.Instance;
                        }
                    }
                    else
                    {
                        // How many characters will follow, encoded in this mode?
                        int count = bits.ReadBits(mode.GetCharacterCountBits(version));
                        if (mode.Equals(Mode.NUMERIC))
                        {
                            DecodeNumericSegment(bits, result, count);
                        }
                        else if (mode.Equals(Mode.ALPHANUMERIC))
                        {
                            DecodeAlphanumericSegment(bits, result, count, fc1InEffect);
                        }
                        else if (mode.Equals(Mode.BYTE))
                        {
                            DecodeByteSegment(bits, result, count, currentCharacterSetECI, byteSegments);
                        }
                        else if (mode.Equals(Mode.KANJI))
                        {
                            DecodeKanjiSegment(bits, result, count);
                        }
                        else
                        {
                            throw ReaderException.Instance;
                        }
                    }
                }
            }while (!mode.Equals(Mode.TERMINATOR));

            return(new DecoderResult(bytes, result.ToString(), (byteSegments.Count == 0)?null:byteSegments, ecLevel));
        }
 private static void decodeByteSegment(BitSource bits, StringBuilder result, int count,
                                       CharacterSetECI currentCharacterSetECI, List<byte[]> byteSegments)
 {
     var readBytes = new sbyte[count];
     if (count << 3 > bits.available())
     {
         throw ReaderException.Instance;
     }
     for (int i = 0; i < count; i++)
     {
         readBytes[i] = (sbyte) bits.readBits(8);
     }
     String encoding;
     if (currentCharacterSetECI == null)
     {
         // The spec isn't clear on this mode; see
         // section 6.4.5: t does not say which encoding to assuming
         // upon decoding. I have seen ISO-8859-1 used as well as
         // Shift_JIS -- without anything like an ECI designator to
         // give a hint.
         encoding = guessEncoding(readBytes);
     }
     else
     {
         encoding = currentCharacterSetECI.EncodingName;
     }
     try
     {
         byte[] byteArray = SupportClass.ToByteArray(readBytes);
         result.Append(Encoding.GetEncoding(encoding).GetString(byteArray, 0, byteArray.Length));
     }
     catch (IOException)
     {
         throw ReaderException.Instance;
     }
     byteSegments.Add(SupportClass.ToByteArray(readBytes));
 }
Esempio n. 25
0
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in .NET:
//ORIGINAL LINE: private static void decodeByteSegment(com.google.zxing.common.BitSource bits, StringBuilder result, int count, com.google.zxing.common.CharacterSetECI currentCharacterSetECI, java.util.Collection<byte[]> byteSegments, java.util.Map<com.google.zxing.DecodeHintType,?> hints) throws com.google.zxing.FormatException
        private static void decodeByteSegment(BitSource bits, StringBuilder result, int count, CharacterSetECI currentCharacterSetECI, ICollection <sbyte[]> byteSegments, IDictionary <DecodeHintType, object> hints)
        {
            // Don't crash trying to read more bits than we have available.
            if (count << 3 > bits.available())
            {
                throw FormatException.FormatInstance;
            }

            sbyte[] readBytes = new sbyte[count];
            for (int i = 0; i < count; i++)
            {
                readBytes[i] = (sbyte)bits.readBits(8);
            }
            string encoding;

            if (currentCharacterSetECI == null)
            {
                // The spec isn't clear on this mode; see
                // section 6.4.5: t does not say which encoding to assuming
                // upon decoding. I have seen ISO-8859-1 used as well as
                // Shift_JIS -- without anything like an ECI designator to
                // give a hint.
                encoding = StringUtils.guessEncoding(readBytes, hints);
            }
            else
            {
                encoding = currentCharacterSetECI.name();
            }
            try
            {
                //result.Append(new string(readBytes, encoding));
                result.Append(GetEncodedStringFromBuffer(readBytes, encoding));
            }
            catch (System.IO.IOException)
            {
                throw FormatException.FormatInstance;
            }
            byteSegments.Add(readBytes);
        }
Esempio n. 26
0
        /// <summary>
        /// Encodes the specified content.
        /// </summary>
        /// <param name="content">The content.</param>
        /// <param name="ecLevel">The ec level.</param>
        /// <param name="hints">The hints.</param>
        /// <returns></returns>
        public static QRCode encode(String content,
                                    ErrorCorrectionLevel ecLevel,
                                    IDictionary <EncodeHintType, object> hints)
        {
            // Determine what character encoding has been specified by the caller, if any
#if !SILVERLIGHT || WINDOWS_PHONE
            String encoding = hints == null || !hints.ContainsKey(EncodeHintType.CHARACTER_SET) ? null : (String)hints[EncodeHintType.CHARACTER_SET];
            if (encoding == null)
            {
                encoding = DEFAULT_BYTE_MODE_ENCODING;
            }
            bool generateECI = !DEFAULT_BYTE_MODE_ENCODING.Equals(encoding);
#else
            // Silverlight supports only UTF-8 and UTF-16 out-of-the-box
            const string encoding = "UTF-8";
            // caller of the method can only control if the ECI segment should be written
            // character set is fixed to UTF-8; but some scanners doesn't like the ECI segment
            bool generateECI = (hints != null && hints.ContainsKey(EncodeHintType.CHARACTER_SET));
#endif
            // http://zxingnet.codeplex.com/discussions/399045
            if (hints != null && hints.ContainsKey(EncodeHintType.DISABLE_ECI) && (bool)hints[EncodeHintType.DISABLE_ECI])
            {
                generateECI = false;
            }

            // Pick an encoding mode appropriate for the content. Note that this will not attempt to use
            // multiple modes / segments even if that were more efficient. Twould be nice.
            Mode mode = chooseMode(content, encoding);

            // This will store the header information, like mode and
            // length, as well as "header" segments like an ECI segment.
            BitArray headerBits = new BitArray();

            // Append ECI segment if applicable
            if (mode == Mode.BYTE && generateECI)
            {
                CharacterSetECI eci = CharacterSetECI.getCharacterSetECIByName(encoding);
                if (eci != null)
                {
                    appendECI(eci, headerBits);
                }
            }

            // (With ECI in place,) Write the mode marker
            appendModeInfo(mode, headerBits);

            // Collect data within the main segment, separately, to count its size if needed. Don't add it to
            // main payload yet.
            BitArray dataBits = new BitArray();
            appendBytes(content, mode, dataBits, encoding);

            // Hard part: need to know version to know how many bits length takes. But need to know how many
            // bits it takes to know version. First we take a guess at version by assuming version will be
            // the minimum, 1:

            int provisionalBitsNeeded = headerBits.Size
                                        + mode.getCharacterCountBits(Version.getVersionForNumber(1))
                                        + dataBits.Size;
            Version provisionalVersion = chooseVersion(provisionalBitsNeeded, ecLevel);

            // Use that guess to calculate the right version. I am still not sure this works in 100% of cases.
            int bitsNeeded = headerBits.Size
                             + mode.getCharacterCountBits(provisionalVersion)
                             + dataBits.Size;
            Version version = chooseVersion(bitsNeeded, ecLevel);

            BitArray headerAndDataBits = new BitArray();
            headerAndDataBits.appendBitArray(headerBits);
            // Find "length" of main segment and write it
            int numLetters = mode == Mode.BYTE ? dataBits.SizeInBytes : content.Length;
            appendLengthInfo(numLetters, version, mode, headerAndDataBits);
            // Put data together into the overall payload
            headerAndDataBits.appendBitArray(dataBits);

            Version.ECBlocks ecBlocks = version.getECBlocksForLevel(ecLevel);
            int numDataBytes          = version.TotalCodewords - ecBlocks.TotalECCodewords;

            // Terminate the bits properly.
            terminateBits(numDataBytes, headerAndDataBits);

            // Interleave data bits with error correction code.
            BitArray finalBits = interleaveWithECBytes(headerAndDataBits,
                                                       version.TotalCodewords,
                                                       numDataBytes,
                                                       ecBlocks.NumBlocks);

            QRCode qrCode = new QRCode
            {
                ECLevel = ecLevel,
                Mode    = mode,
                Version = version
            };

            //  Choose the mask pattern and set to "qrCode".
            int        dimension   = version.DimensionForVersion;
            ByteMatrix matrix      = new ByteMatrix(dimension, dimension);
            int        maskPattern = chooseMaskPattern(finalBits, ecLevel, version, matrix);
            qrCode.MaskPattern = maskPattern;

            // Build the matrix and set it to "qrCode".
            MatrixUtil.buildMatrix(finalBits, ecLevel, version, maskPattern, matrix);
            qrCode.Matrix = matrix;

            return(qrCode);
        }
Esempio n. 27
0
        internal static DecoderResult decode(byte[] bytes,
                                             Version version,
                                             QrCode.Internal.ErrorCorrectionLevel ecLevel,
                                             IDictionary <DecodeHintType, object> hints)
        {
            var             bits                   = new BitSource(bytes);
            var             result                 = new StringBuilder(50);
            var             byteSegments           = new List <byte[]>(1);
            var             symbolSequence         = -1;
            var             parityData             = -1;
            CharacterSetECI currentCharacterSetECI = null;
            bool            fc1InEffect            = false;

            Mode mode   = Mode.TERMINATOR;
            int  bitLen = Mode.NUMERIC.getBitsLength(version.VersionNumber);

            if (version.VersionNumber > 1)
            {
                try
                {
                    mode = Mode.forBits(bits.readBits(bitLen));
                }
                catch (System.ArgumentException iae)
                {
                    throw ReaderException.Instance;
                }
            }
            else
            {
                mode = Mode.NUMERIC;
            }

            if (!mode.Equals(Mode.TERMINATOR))
            {
                // How many characters will follow, encoded in this mode?
                int count = bits.readBits(mode.getCharacterCountBits(version));
                if (mode.Equals(Mode.NUMERIC))
                {
                    decodeNumericSegment(bits, result, count);
                }
                else if (mode.Equals(Mode.ALPHANUMERIC))
                {
                    decodeAlphanumericSegment(bits, result, count, fc1InEffect);
                }
                else if (mode.Equals(Mode.BYTE))
                {
                    decodeByteSegment(bits, result, count, currentCharacterSetECI, byteSegments, hints);
                }
                else if (mode.Equals(Mode.KANJI))
                {
                    decodeKanjiSegment(bits, result, count);
                }
                else
                {
                    throw ReaderException.Instance;
                }
            }

            return(new DecoderResult(bytes, result.ToString(), byteSegments.Count == 0 ? null : byteSegments, ecLevel == null ? null : ecLevel.ToString(),
                                     symbolSequence, parityData));
        }
Esempio n. 28
0
        /// <summary>
        /// Convert the text represented by this High Level Encoder into a BitArray.
        /// </summary>
        /// <returns>text represented by this encoder encoded as a <see cref="BitArray"/></returns>
        public BitArray encode()
        {
            State initialState = State.INITIAL_STATE;

            if (encoding != null && !disableEci)
            {
                CharacterSetECI eci = CharacterSetECI.getCharacterSetECI(encoding);
                if (null == eci)
                {
                    throw new ArgumentException("No ECI code for character set " + encoding.WebName);
                }
                initialState = initialState.appendFLGn(eci.Value);
            }
            ICollection <State> states = new Collection <State>();

            states.Add(initialState);
            for (int index = 0; index < text.Length; index++)
            {
                int pairCode;
                // don't remove the (int) type cast, mono compiler needs it
                int nextChar = (index + 1 < text.Length) ? (int)text[index + 1] : 0;
                switch (text[index])
                {
                case (byte)'\r':
                    pairCode = nextChar == '\n' ? 2 : 0;
                    break;

                case (byte)'.':
                    pairCode = nextChar == ' ' ? 3 : 0;
                    break;

                case (byte)',':
                    pairCode = nextChar == ' ' ? 4 : 0;
                    break;

                case (byte)':':
                    pairCode = nextChar == ' ' ? 5 : 0;
                    break;

                default:
                    pairCode = 0;
                    break;
                }
                if (pairCode > 0)
                {
                    // We have one of the four special PUNCT pairs.  Treat them specially.
                    // Get a new set of states for the two new characters.
                    states = updateStateListForPair(states, index, pairCode);
                    index++;
                }
                else
                {
                    // Get a new set of states for the new character.
                    states = updateStateListForChar(states, index);
                }
            }
            // We are left with a set of states.  Find the shortest one.
            State minState = null;

            foreach (var state in states)
            {
                if (minState == null)
                {
                    minState = state;
                }
                else
                {
                    if (state.BitCount < minState.BitCount)
                    {
                        minState = state;
                    }
                }
            }

            /*
             * State minState = Collections.min(states, new Comparator<State>() {
             * @Override
             * public int compare(State a, State b) {
             *    return a.getBitCount() - b.getBitCount();
             * }
             * });
             */
            // Convert it to a bit array, and return.
            return(minState.toBitArray(text));
        }
Esempio n. 29
0
        internal static DecoderResult decode(byte[] bytes,
                                             Version version,
                                             ErrorCorrectionLevel ecLevel,
                                             IDictionary <DecodeHintType, object> hints)
        {
            var bits           = new BitSource(bytes);
            var result         = new StringBuilder(50);
            var byteSegments   = new List <byte[]> (1);
            var symbolSequence = -1;
            var parityData     = -1;

            try {
                CharacterSetECI currentCharacterSetECI = null;
                bool            fc1InEffect            = false;
                Mode            mode;
                do
                {
                    // While still another segment to read...
                    if (bits.available() < 4)
                    {
                        // OK, assume we're done. Really, a TERMINATOR mode should have been recorded here
                        mode = Mode.TERMINATOR;
                    }
                    else
                    {
                        try {
                            mode = Mode.forBits(bits.readBits(4));                               // mode is encoded by 4 bits
                        } catch (ArgumentException) {
                            return(null);
                        }
                    }
                    if (mode != Mode.TERMINATOR)
                    {
                        if (mode == Mode.FNC1_FIRST_POSITION || mode == Mode.FNC1_SECOND_POSITION)
                        {
                            // We do little with FNC1 except alter the parsed result a bit according to the spec
                            fc1InEffect = true;
                        }
                        else if (mode == Mode.STRUCTURED_APPEND)
                        {
                            if (bits.available() < 16)
                            {
                                return(null);
                            }
                            // not really supported; but sequence number and parity is added later to the result metadata
                            // Read next 8 bits (symbol sequence #) and 8 bits (parity data), then continue
                            symbolSequence = bits.readBits(8);
                            parityData     = bits.readBits(8);
                        }
                        else if (mode == Mode.ECI)
                        {
                            // Count doesn't apply to ECI
                            int value = parseECIValue(bits);
                            currentCharacterSetECI = CharacterSetECI.getCharacterSetECIByValue(value);
                            if (currentCharacterSetECI == null)
                            {
                                return(null);
                            }
                        }
                        else
                        {
                            // First handle Hanzi mode which does not start with character count
                            if (mode == Mode.HANZI)
                            {
                                //chinese mode contains a sub set indicator right after mode indicator
                                int subset     = bits.readBits(4);
                                int countHanzi = bits.readBits(mode.getCharacterCountBits(version));
                                if (subset == GB2312_SUBSET)
                                {
                                    if (!decodeHanziSegment(bits, result, countHanzi))
                                    {
                                        return(null);
                                    }
                                }
                            }
                            else
                            {
                                // "Normal" QR code modes:
                                // How many characters will follow, encoded in this mode?
                                int count = bits.readBits(mode.getCharacterCountBits(version));
                                if (mode == Mode.NUMERIC)
                                {
                                    if (!decodeNumericSegment(bits, result, count))
                                    {
                                        return(null);
                                    }
                                }
                                else if (mode == Mode.ALPHANUMERIC)
                                {
                                    if (!decodeAlphanumericSegment(bits, result, count, fc1InEffect))
                                    {
                                        return(null);
                                    }
                                }
                                else if (mode == Mode.BYTE)
                                {
                                    if (!decodeByteSegment(bits, result, count, currentCharacterSetECI, byteSegments, hints))
                                    {
                                        return(null);
                                    }
                                }
                                else if (mode == Mode.KANJI)
                                {
                                    if (!decodeKanjiSegment(bits, result, count))
                                    {
                                        return(null);
                                    }
                                }
                                else
                                {
                                    return(null);
                                }
                            }
                        }
                    }
                } while (mode != Mode.TERMINATOR);
            } catch (ArgumentException) {
                // from readBits() calls
                return(null);
            }

#if WindowsCE
            var resultString = result.ToString().Replace("\n", "\r\n");
#else
            var resultString = result.ToString().Replace("\r\n", "\n").Replace("\n", Environment.NewLine);
#endif
            return(new DecoderResult(bytes,
                                     resultString,
                                     byteSegments.Count == 0 ? null : byteSegments,
                                     ecLevel == null ? null : ecLevel.ToString(),
                                     symbolSequence, parityData));
        }
Esempio n. 30
0
        /// <summary>
        /// Encodes the specified content.
        /// </summary>
        /// <param name="content">The content.</param>
        /// <param name="ecLevel">The ec level.</param>
        /// <param name="hints">The hints.</param>
        /// <returns></returns>
        public static QRCode encode(String content,
                                    ErrorCorrectionLevel ecLevel,
                                    IDictionary <EncodeHintType, object> hints)
        {
            // Determine what character encoding has been specified by the caller, if any
            bool hasEncodingHint = hints != null && hints.ContainsKey(EncodeHintType.CHARACTER_SET);

#if !SILVERLIGHT || WINDOWS_PHONE
            var encoding = hints == null || !hints.ContainsKey(EncodeHintType.CHARACTER_SET) ? null : (String)hints[EncodeHintType.CHARACTER_SET];
            if (encoding == null)
            {
                encoding = DEFAULT_BYTE_MODE_ENCODING;
            }
            var generateECI = hasEncodingHint || !DEFAULT_BYTE_MODE_ENCODING.Equals(encoding);
#else
            // Silverlight supports only UTF-8 and UTF-16 out-of-the-box
            const string encoding = "UTF-8";
            // caller of the method can only control if the ECI segment should be written
            // character set is fixed to UTF-8; but some scanners doesn't like the ECI segment
            var generateECI = hasEncodingHint;
#endif

            // Pick an encoding mode appropriate for the content. Note that this will not attempt to use
            // multiple modes / segments even if that were more efficient. Twould be nice.
            var mode = chooseMode(content, encoding);

            // This will store the header information, like mode and
            // length, as well as "header" segments like an ECI segment.
            var headerBits = new BitArray();

            // Append ECI segment if applicable
            if (mode == Mode.BYTE && generateECI)
            {
                var eci = CharacterSetECI.getCharacterSetECIByName(encoding);
                if (eci != null)
                {
                    var eciIsExplicitDisabled = (hints != null && hints.ContainsKey(EncodeHintType.DISABLE_ECI) && hints[EncodeHintType.DISABLE_ECI] != null && Convert.ToBoolean(hints[EncodeHintType.DISABLE_ECI].ToString()));
                    if (!eciIsExplicitDisabled)
                    {
                        appendECI(eci, headerBits);
                    }
                }
            }

            // Append the FNC1 mode header for GS1 formatted data if applicable
            var hasGS1FormatHint = hints != null && hints.ContainsKey(EncodeHintType.GS1_FORMAT);
            if (hasGS1FormatHint && hints[EncodeHintType.GS1_FORMAT] != null && Convert.ToBoolean(hints[EncodeHintType.GS1_FORMAT].ToString()))
            {
                // GS1 formatted codes are prefixed with a FNC1 in first position mode header
                appendModeInfo(Mode.FNC1_FIRST_POSITION, headerBits);
            }

            // (With ECI in place,) Write the mode marker
            appendModeInfo(mode, headerBits);

            // Collect data within the main segment, separately, to count its size if needed. Don't add it to
            // main payload yet.
            var dataBits = new BitArray();
            appendBytes(content, mode, dataBits, encoding);

            Version version;
            if (hints != null && hints.ContainsKey(EncodeHintType.QR_VERSION))
            {
                int versionNumber = Int32.Parse(hints[EncodeHintType.QR_VERSION].ToString());
                version = Version.getVersionForNumber(versionNumber);
                int bitsNeeded = calculateBitsNeeded(mode, headerBits, dataBits, version);
                if (!willFit(bitsNeeded, version, ecLevel))
                {
                    throw new WriterException("Data too big for requested version");
                }
            }
            else
            {
                version = recommendVersion(ecLevel, mode, headerBits, dataBits);
            }

            var headerAndDataBits = new BitArray();
            headerAndDataBits.appendBitArray(headerBits);
            // Find "length" of main segment and write it
            var numLetters = mode == Mode.BYTE ? dataBits.SizeInBytes : content.Length;
            appendLengthInfo(numLetters, version, mode, headerAndDataBits);
            // Put data together into the overall payload
            headerAndDataBits.appendBitArray(dataBits);

            var ecBlocks     = version.getECBlocksForLevel(ecLevel);
            var numDataBytes = version.TotalCodewords - ecBlocks.TotalECCodewords;

            // Terminate the bits properly.
            terminateBits(numDataBytes, headerAndDataBits);

            // Interleave data bits with error correction code.
            var finalBits = interleaveWithECBytes(headerAndDataBits,
                                                  version.TotalCodewords,
                                                  numDataBytes,
                                                  ecBlocks.NumBlocks);

            var qrCode = new QRCode
            {
                ECLevel = ecLevel,
                Mode    = mode,
                Version = version
            };

            //  Choose the mask pattern and set to "qrCode".
            var dimension   = version.DimensionForVersion;
            var matrix      = new ByteMatrix(dimension, dimension);
            var maskPattern = chooseMaskPattern(finalBits, ecLevel, version, matrix);
            qrCode.MaskPattern = maskPattern;

            // Build the matrix and set it to "qrCode".
            MatrixUtil.buildMatrix(finalBits, ecLevel, version, maskPattern, matrix);
            qrCode.Matrix = matrix;

            return(qrCode);
        }
Esempio n. 31
0
        /// <summary>
        /// Gets the string encoded in the aztec code bits
        /// </summary>
        /// <param name="correctedBits">The corrected bits.</param>
        /// <returns>the decoded string</returns>
        private static String getEncodedData(bool[] correctedBits)
        {
            var endIndex   = correctedBits.Length;
            var latchTable = Table.UPPER; // table most recently latched to
            var shiftTable = Table.UPPER; // table to use for the next read
            var strTable   = UPPER_TABLE;
            var index      = 0;


            // Final decoded string result
            // (correctedBits-5) / 4 is an upper bound on the size (all-digit result)
            var result = new StringBuilder((correctedBits.Length - 5) / 4);

            // Intermediary buffer of decoded bytes, which is decoded into a string and flushed
            // when character encoding changes (ECI) or input ends.
            using (var decodedBytes = new System.IO.MemoryStream())
            {
                var encoding = DEFAULT_ENCODING;

                while (index < endIndex)
                {
                    if (shiftTable == Table.BINARY)
                    {
                        if (endIndex - index < 5)
                        {
                            break;
                        }
                        int length = readCode(correctedBits, index, 5);
                        index += 5;
                        if (length == 0)
                        {
                            if (endIndex - index < 11)
                            {
                                break;
                            }
                            length = readCode(correctedBits, index, 11) + 31;
                            index += 11;
                        }
                        for (int charCount = 0; charCount < length; charCount++)
                        {
                            if (endIndex - index < 8)
                            {
                                index = endIndex; // Force outer loop to exit
                                break;
                            }
                            int code = readCode(correctedBits, index, 8);
                            decodedBytes.WriteByte((byte)code);
                            index += 8;
                        }
                        // Go back to whatever mode we had been in
                        shiftTable = latchTable;
                        strTable   = codeTables[shiftTable];
                    }
                    else
                    {
                        int size = shiftTable == Table.DIGIT ? 4 : 5;
                        if (endIndex - index < size)
                        {
                            break;
                        }
                        int code = readCode(correctedBits, index, size);
                        index += size;
                        String str = getCharacter(strTable, code);
                        if ("FLG(n)".Equals(str))
                        {
                            if (endIndex - index < 3)
                            {
                                break;
                            }
                            int n = readCode(correctedBits, index, 3);
                            index += 3;
                            //  flush bytes, FLG changes state
                            if (decodedBytes.Length > 0)
                            {
                                var byteArray = decodedBytes.ToArray();
                                result.Append(encoding.GetString(byteArray, 0, byteArray.Length));
                                decodedBytes.SetLength(0);
                            }
                            switch (n)
                            {
                            case 0:
                                result.Append((char)29);      // translate FNC1 as ASCII 29
                                break;

                            case 7:
                                throw new FormatException("FLG(7) is reserved and illegal");

                            default:
                                // ECI is decimal integer encoded as 1-6 codes in DIGIT mode
                                int eci = 0;
                                if (endIndex - index < 4 * n)
                                {
                                    break;
                                }
                                while (n-- > 0)
                                {
                                    int nextDigit = readCode(correctedBits, index, 4);
                                    index += 4;
                                    if (nextDigit < 2 || nextDigit > 11)
                                    {
                                        throw new FormatException("Not a decimal digit");
                                    }
                                    eci = eci * 10 + (nextDigit - 2);
                                }
                                CharacterSetECI charsetECI = CharacterSetECI.getCharacterSetECIByValue(eci);
                                encoding = CharacterSetECI.getEncoding(charsetECI);
                                if (encoding == null)
                                {
                                    throw new FormatException("Encoding for ECI " + eci + " can't be resolved");
                                }
                                break;
                            }
                            // Go back to whatever mode we had been in
                            shiftTable = latchTable;
                            strTable   = codeTables[shiftTable];
                        }
                        else if (str.StartsWith("CTRL_"))
                        {
                            // Table changes
                            // ISO/IEC 24778:2008 prescribes ending a shift sequence in the mode from which it was invoked.
                            // That's including when that mode is a shift.
                            // Our test case dlusbs.png for issue #642 exercises that.
                            latchTable = shiftTable;  // Latch the current mode, so as to return to Upper after U/S B/S
                            shiftTable = getTable(str[5]);
                            strTable   = codeTables[shiftTable];
                            if (str[6] == 'L')
                            {
                                latchTable = shiftTable;
                            }
                        }
                        else
                        {
                            // Though stored as a table of strings for convenience, codes actually represent 1 or 2 *bytes*.
#if (PORTABLE || NETSTANDARD1_0 || NETSTANDARD1_1 || WINDOWS_PHONE || NETFX_CORE || SILVERLIGHT)
                            var b = StringUtils.PLATFORM_DEFAULT_ENCODING_T.GetBytes(str);
#else
                            var b = Encoding.ASCII.GetBytes(str);
#endif
                            decodedBytes.Write(b, 0, b.Length);
                            // Go back to whatever mode we had been in
                            shiftTable = latchTable;
                            strTable   = codeTables[shiftTable];
                        }
                    }
                }

                if (decodedBytes.Length > 0)
                {
                    var byteArray = decodedBytes.ToArray();
                    result.Append(encoding.GetString(byteArray, 0, byteArray.Length));
                }
            }
            return(result.ToString());
        }
Esempio n. 32
0
        public static QRCode encode(String content,
                                    ErrorCorrectionLevel ecLevel,
                                    IDictionary hints)
        {
            // Determine what character encoding has been specified by the caller, if any
            String encoding = hints == null || !hints.Contains(EncodeHintType.CHARACTER_SET) ? null : (String)hints[EncodeHintType.CHARACTER_SET];

            if (encoding == null)
            {
                encoding = DEFAULT_BYTE_MODE_ENCODING;
            }
            bool doSelectMask = hints == null || !hints.Contains(EncodeHintType.QR_DO_MASK_SELECTION) ? false : (bool)hints[EncodeHintType.QR_DO_MASK_SELECTION];

            // Pick an encoding mode appropriate for the content. Note that this will not attempt to use
            // multiple modes / segments even if that were more efficient. Twould be nice.
            Mode mode = chooseMode(content, encoding);

            // This will store the header information, like mode and
            // length, as well as "header" segments like an ECI segment.
            BitArray headerBits = new BitArray();

            // Append ECI segment if applicable
            if (mode == Mode.BYTE && !DEFAULT_BYTE_MODE_ENCODING.Equals(encoding))
            {
                CharacterSetECI eci = CharacterSetECI.getCharacterSetECIByName(encoding);
                if (eci != null)
                {
                    appendECI(eci, headerBits);
                }
            }

            // (With ECI in place,) Write the mode marker
            appendModeInfo(mode, headerBits);

            // Collect data within the main segment, separately, to count its size if needed. Don't add it to
            // main payload yet.
            BitArray dataBits = new BitArray();

            appendBytes(content, mode, dataBits, encoding);

            // Hard part: need to know version to know how many bits length takes. But need to know how many
            // bits it takes to know version. To pick version size assume length takes maximum bits
            int bitsNeeded = headerBits.Size
                             + mode.getCharacterCountBits(Version.getVersionForNumber(40))
                             + dataBits.Size;
            Version version = chooseVersion(bitsNeeded, ecLevel);

            BitArray headerAndDataBits = new BitArray();

            headerAndDataBits.appendBitArray(headerBits);
            // Find "length" of main segment and write it
            int numLetters = mode == Mode.BYTE ? dataBits.SizeInBytes : content.Length;

            appendLengthInfo(numLetters, version, mode, headerAndDataBits);
            // Put data together into the overall payload
            headerAndDataBits.appendBitArray(dataBits);

            Version.ECBlocks ecBlocks = version.getECBlocksForLevel(ecLevel);
            int numDataBytes          = version.TotalCodewords - ecBlocks.TotalECCodewords;

            // Terminate the bits properly.
            terminateBits(numDataBytes, headerAndDataBits);

            // Interleave data bits with error correction code.
            BitArray finalBits = interleaveWithECBytes(headerAndDataBits,
                                                       version.TotalCodewords,
                                                       numDataBytes,
                                                       ecBlocks.NumBlocks);

            QRCode qrCode = new QRCode
            {
                ECLevel = ecLevel,
                Mode    = mode,
                Version = version
            };

            //  Choose the mask pattern and set to "qrCode".
            int        dimension   = version.DimensionForVersion;
            ByteMatrix matrix      = new ByteMatrix(dimension, dimension);
            int        maskPattern = 3;

            if (doSelectMask)
            {
                maskPattern = chooseMaskPattern(finalBits, ecLevel, version, matrix);
            }
            qrCode.MaskPattern = maskPattern;

            // Build the matrix and set it to "qrCode".
            MatrixUtil.buildMatrix(finalBits, ecLevel, version, maskPattern, matrix);
            qrCode.Matrix = matrix;

            return(qrCode);
        }