Exemple #1
0
        private static PdfFunction.Type3 CreateStitchingCmykShadingFunction()
        {
            PdfArray domain0to1     = new PdfArray(new float[] { 0, 1 });
            PdfArray range0to1For4n = new PdfArray(new float[] { 0, 1, 0, 1, 0, 1, 0, 1 });

            float[]           cmykColor0 = new float[] { 0.2f, 0.4f, 0f, 0f };
            float[]           cmykColor1 = new float[] { 0.2f, 1f, 0f, 0f };
            PdfFunction.Type2 function0  = new PdfFunction.Type2(domain0to1, null, new PdfArray(cmykColor0), new PdfArray
                                                                     (cmykColor1), new PdfNumber(1));
            PdfFunction.Type2 function1 = new PdfFunction.Type2(domain0to1, null, new PdfArray(cmykColor1), new PdfArray
                                                                    (cmykColor0), new PdfNumber(1));
            PdfArray boundForTwoFunctionsSubdomains = new PdfArray(new float[] { 0.5f });
            PdfArray encodeStitchingSubdomainToNthFunctionDomain = new PdfArray(new float[] { 0, 1, 0, 1 });

            return(new PdfFunction.Type3(domain0to1, range0to1For4n, new List <PdfFunction>(JavaUtil.ArraysAsList(function0
                                                                                                                  , function1)), boundForTwoFunctionsSubdomains, encodeStitchingSubdomainToNthFunctionDomain));
        }
Exemple #2
0
 public static void AddRectToClipper(Clipper clipper, Point[] rectVertices, PolyType polyType)
 {
     clipper.AddPath(new List <IntPoint>(ConvertToLongPoints(new List <Point>(JavaUtil.ArraysAsList(rectVertices)
                                                                              ))), polyType, true);
 }
Exemple #3
0
        /* "ECC200" fills an nrow x ncol array with appropriate values for ECC200 */
        private void Ecc200()
        {
            int row;
            int col;
            int chr;

            /* First, fill the array[] with invalid entries */
            JavaUtil.Fill(array, (short)0);
            /* Starting in the correct location for character #1, bit 8,... */
            chr = 1;
            row = 4;
            col = 0;
            do
            {
                /* repeatedly first check for one of the special corner cases, then... */
                if (row == nrow && col == 0)
                {
                    Corner1(chr++);
                }
                if (row == nrow - 2 && col == 0 && ncol % 4 != 0)
                {
                    Corner2(chr++);
                }
                if (row == nrow - 2 && col == 0 && ncol % 8 == 4)
                {
                    Corner3(chr++);
                }
                if (row == nrow + 4 && col == 2 && ncol % 8 == 0)
                {
                    Corner4(chr++);
                }
                do
                {
                    /* sweep upward diagonally, inserting successive characters,... */
                    if (row < nrow && col >= 0 && array[row * ncol + col] == 0)
                    {
                        Utah(row, col, chr++);
                    }
                    row -= 2;
                    col += 2;
                }while (row >= 0 && col < ncol);
                row += 1;
                col += 3;
                do
                {
                    /* & then sweep downward diagonally, inserting successive characters,... */
                    if (row >= 0 && col < ncol && array[row * ncol + col] == 0)
                    {
                        Utah(row, col, chr++);
                    }
                    row += 2;
                    col -= 2;
                }while (row < nrow && col >= 0);
                row += 3;
                col += 1;
            }while (row < nrow || col < ncol);
            /* ... until the entire array is scanned */
            /* Lastly, if the lower righthand corner is untouched, fill in fixed pattern */
            if (array[nrow * ncol - 1] == 0)
            {
                array[nrow * ncol - 1] = array[nrow * ncol - ncol - 2] = 1;
            }
        }
Exemple #4
0
        public virtual void AddSinglesConstructor()
        {
            PageRange range = new PageRange("5, 1");

            NUnit.Framework.Assert.AreEqual(range.GetQualifyingPageNums(10), JavaUtil.ArraysAsList(5, 1));
        }
Exemple #5
0
 /// <summary>
 /// Adds polygon path based on array of
 /// <see cref="iText.Kernel.Geom.Point"/>
 /// (internally converting
 /// them by
 /// <see cref="ConvertToLongPoints(System.Collections.Generic.IList{E})"/>
 /// ) and adds this path to
 /// <see cref="Clipper"/>
 /// instance, treating the path as
 /// a closed polygon.
 /// <para />
 /// The return value will be false if the path is invalid for clipping. A path is invalid for clipping when:
 /// <ul>
 /// <li>it has less than 3 vertices;
 /// <li>the vertices are all co-linear.
 /// </ul>
 /// </summary>
 /// <param name="clipper">
 ///
 /// <see cref="Clipper"/>
 /// instance to which the created polygon path will be added.
 /// </param>
 /// <param name="polyVertices">
 /// an array of
 /// <see cref="iText.Kernel.Geom.Point"/>
 /// which will be internally converted
 /// to clipper path and added to the clipper instance.
 /// </param>
 /// <param name="polyType">
 /// either
 /// <see cref="PolyType.SUBJECT"/>
 /// or
 /// <see cref="PolyType.CLIP"/>
 /// denoting whether added
 /// path is a subject of clipping or a part of the clipping polygon.
 /// </param>
 /// <returns>true if polygon path was successfully added, false otherwise.</returns>
 public static bool AddPolygonToClipper(Clipper clipper, Point[] polyVertices, PolyType polyType)
 {
     return(clipper.AddPath(new List <IntPoint>(ConvertToLongPoints(new List <Point>(JavaUtil.ArraysAsList(polyVertices
                                                                                                           )))), polyType, true));
 }
Exemple #6
0
 public override bool Equals(Object o)
 {
     return(this == o || o != null && GetType() == o.GetType() && JavaUtil.ArraysEquals(content, ((iText.Kernel.Pdf.PdfLiteral
                                                                                                   )o).content));
 }
Exemple #7
0
 public PdfLiteral(int size)
     : this(new byte[size])
 {
     JavaUtil.Fill(content, (byte)32);
 }
Exemple #8
0
 /// <summary><inheritDoc/></summary>
 /// <exception cref="System.IO.IOException"/>
 public virtual float ReadFloat()
 {
     return(JavaUtil.IntBitsToFloat(ReadInt()));
 }
Exemple #9
0
 /// <exception cref="System.IO.IOException"/>
 public float ReadFloatLE()
 {
     return(JavaUtil.IntBitsToFloat(ReadIntLE()));
 }
 internal And(params Evaluator[] evaluators)
     : this(JavaUtil.ArraysAsList(evaluators))
 {
 }
 private byte[] SubArray(byte[] array, int beg, int end)
 {
     return(JavaUtil.ArraysCopyOfRange(array, beg, end + 1));
 }
Exemple #12
0
 public override String ToString()
 {
     return(JavaUtil.ArraysToString(ranges));
 }
Exemple #13
0
 public override int GetHashCode()
 {
     return(JavaUtil.ArraysHashCode(ranges));
 }
Exemple #14
0
        /// <summary>
        /// Processes an individual pathing operator and all of its arguments, converting into one or more
        /// <see cref="iText.Svg.Renderers.Path.IPathShape"/>
        /// objects.
        /// </summary>
        /// <param name="pathProperties">
        /// The property operator and all arguments as an array of
        /// <see cref="System.String"/>
        /// s
        /// </param>
        /// <param name="previousShape">
        /// The previous shape which can affect the positioning of the current shape. If no previous
        /// shape exists
        /// <see langword="null"/>
        /// is passed.
        /// </param>
        /// <returns>
        /// a
        /// <see cref="System.Collections.IList{E}"/>
        /// of each
        /// <see cref="iText.Svg.Renderers.Path.IPathShape"/>
        /// that should be drawn to represent the operator.
        /// </returns>
        private IList <IPathShape> ProcessPathOperator(String[] pathProperties, IPathShape previousShape)
        {
            IList <IPathShape> shapes = new List <IPathShape>();

            if (pathProperties.Length == 0 || String.IsNullOrEmpty(pathProperties[0]) || SvgPathShapeFactory.GetArgumentCount
                    (pathProperties[0]) < 0)
            {
                return(shapes);
            }
            int argumentCount = SvgPathShapeFactory.GetArgumentCount(pathProperties[0]);

            if (argumentCount == 0)
            {
                // closePath operator
                if (previousShape == null)
                {
                    throw new SvgProcessingException(SvgLogMessageConstant.INVALID_CLOSEPATH_OPERATOR_USE);
                }
                shapes.Add(zOperator);
                currentPoint = zOperator.GetEndingPoint();
                return(shapes);
            }
            for (int index = 1; index < pathProperties.Length; index += argumentCount)
            {
                if (index + argumentCount > pathProperties.Length)
                {
                    break;
                }
                IPathShape pathShape = SvgPathShapeFactory.CreatePathShape(pathProperties[0]);
                if (pathShape is MoveTo)
                {
                    shapes.AddAll(AddMoveToShapes(pathShape, pathProperties));
                    return(shapes);
                }
                String[] shapeCoordinates = GetShapeCoordinates(pathShape, previousShape, JavaUtil.ArraysCopyOfRange(pathProperties
                                                                                                                     , index, index + argumentCount));
                if (pathShape != null)
                {
                    if (shapeCoordinates != null)
                    {
                        pathShape.SetCoordinates(shapeCoordinates, currentPoint);
                    }
                    currentPoint = pathShape.GetEndingPoint();
                    // unsupported operators are ignored.
                    shapes.Add(pathShape);
                }
                previousShape = pathShape;
            }
            return(shapes);
        }
Exemple #15
0
        /// <summary>This method checks if the image is a valid JPEG and processes some parameters.</summary>
        /// <exception cref="iText.IO.IOException"/>
        /// <exception cref="System.IO.IOException"/>
        private static void ProcessParameters(Stream jpegStream, String errorID, ImageData image)
        {
            byte[][] icc = null;
            if (jpegStream.Read() != 0xFF || jpegStream.Read() != 0xD8)
            {
                throw new iText.IO.IOException(iText.IO.IOException._1IsNotAValidJpegFile).SetMessageParams(errorID);
            }
            bool firstPass = true;
            int  len;

            while (true)
            {
                int v = jpegStream.Read();
                if (v < 0)
                {
                    throw new iText.IO.IOException(iText.IO.IOException.PrematureEofWhileReadingJpeg);
                }
                if (v == 0xFF)
                {
                    int marker = jpegStream.Read();
                    if (firstPass && marker == M_APP0)
                    {
                        firstPass = false;
                        len       = GetShort(jpegStream);
                        if (len < 16)
                        {
                            StreamUtil.Skip(jpegStream, len - 2);
                            continue;
                        }
                        byte[] bcomp = new byte[JFIF_ID.Length];
                        int    r     = jpegStream.Read(bcomp);
                        if (r != bcomp.Length)
                        {
                            throw new iText.IO.IOException(iText.IO.IOException._1CorruptedJfifMarker).SetMessageParams(errorID);
                        }
                        bool found = true;
                        for (int k = 0; k < bcomp.Length; ++k)
                        {
                            if (bcomp[k] != JFIF_ID[k])
                            {
                                found = false;
                                break;
                            }
                        }
                        if (!found)
                        {
                            StreamUtil.Skip(jpegStream, len - 2 - bcomp.Length);
                            continue;
                        }
                        StreamUtil.Skip(jpegStream, 2);
                        int units = jpegStream.Read();
                        int dx    = GetShort(jpegStream);
                        int dy    = GetShort(jpegStream);
                        if (units == 1)
                        {
                            image.SetDpi(dx, dy);
                        }
                        else
                        {
                            if (units == 2)
                            {
                                image.SetDpi((int)(dx * 2.54f + 0.5f), (int)(dy * 2.54f + 0.5f));
                            }
                        }
                        StreamUtil.Skip(jpegStream, len - 2 - bcomp.Length - 7);
                        continue;
                    }
                    if (marker == M_APPE)
                    {
                        len = GetShort(jpegStream) - 2;
                        byte[] byteappe = new byte[len];
                        for (int k = 0; k < len; ++k)
                        {
                            byteappe[k] = (byte)jpegStream.Read();
                        }
                        if (byteappe.Length >= 12)
                        {
                            String appe = iText.IO.Util.JavaUtil.GetStringForBytes(byteappe, 0, 5, "ISO-8859-1");
                            if (appe.Equals("Adobe"))
                            {
                                image.SetInverted(true);
                            }
                        }
                        continue;
                    }
                    if (marker == M_APP2)
                    {
                        len = GetShort(jpegStream) - 2;
                        byte[] byteapp2 = new byte[len];
                        for (int k = 0; k < len; ++k)
                        {
                            byteapp2[k] = (byte)jpegStream.Read();
                        }
                        if (byteapp2.Length >= 14)
                        {
                            String app2 = iText.IO.Util.JavaUtil.GetStringForBytes(byteapp2, 0, 11, "ISO-8859-1");
                            if (app2.Equals("ICC_PROFILE"))
                            {
                                int order = byteapp2[12] & 0xff;
                                int count = byteapp2[13] & 0xff;
                                // some jpeg producers don't know how to count to 1
                                if (order < 1)
                                {
                                    order = 1;
                                }
                                if (count < 1)
                                {
                                    count = 1;
                                }
                                if (icc == null)
                                {
                                    icc = new byte[count][];
                                }
                                icc[order - 1] = byteapp2;
                            }
                        }
                        continue;
                    }
                    if (marker == M_APPD)
                    {
                        len = GetShort(jpegStream) - 2;
                        byte[] byteappd = new byte[len];
                        for (int k = 0; k < len; k++)
                        {
                            byteappd[k] = (byte)jpegStream.Read();
                        }
                        // search for '8BIM Resolution' marker
                        int k_1;
                        for (k_1 = 0; k_1 < len - PS_8BIM_RESO.Length; k_1++)
                        {
                            bool found = true;
                            for (int j = 0; j < PS_8BIM_RESO.Length; j++)
                            {
                                if (byteappd[k_1 + j] != PS_8BIM_RESO[j])
                                {
                                    found = false;
                                    break;
                                }
                            }
                            if (found)
                            {
                                break;
                            }
                        }
                        k_1 += PS_8BIM_RESO.Length;
                        if (k_1 < len - PS_8BIM_RESO.Length)
                        {
                            // "PASCAL String" for name, i.e. string prefix with length byte
                            // padded to be even length; 2 null bytes if empty
                            byte namelength = byteappd[k_1];
                            // add length byte
                            namelength++;
                            // add padding
                            if (namelength % 2 == 1)
                            {
                                namelength++;
                            }
                            // just skip name
                            k_1 += namelength;
                            // size of the resolution data
                            int resosize = (byteappd[k_1] << 24) + (byteappd[k_1 + 1] << 16) + (byteappd[k_1 + 2] << 8) + byteappd[k_1
                                                                                                                                   + 3];
                            // should be 16
                            if (resosize != 16)
                            {
                                // fail silently, for now
                                //System.err.println("DEBUG: unsupported resolution IRB size");
                                continue;
                            }
                            k_1 += 4;
                            int dx = (byteappd[k_1] << 8) + (byteappd[k_1 + 1] & 0xff);
                            k_1 += 2;
                            // skip 2 unknown bytes
                            k_1 += 2;
                            int unitsx = (byteappd[k_1] << 8) + (byteappd[k_1 + 1] & 0xff);
                            k_1 += 2;
                            // skip 2 unknown bytes
                            k_1 += 2;
                            int dy = (byteappd[k_1] << 8) + (byteappd[k_1 + 1] & 0xff);
                            k_1 += 2;
                            // skip 2 unknown bytes
                            k_1 += 2;
                            int unitsy = (byteappd[k_1] << 8) + (byteappd[k_1 + 1] & 0xff);
                            if (unitsx == 1 || unitsx == 2)
                            {
                                dx = (unitsx == 2 ? (int)(dx * 2.54f + 0.5f) : dx);
                                // make sure this is consistent with JFIF data
                                if (image.GetDpiX() != 0 && image.GetDpiX() != dx)
                                {
                                    ILog logger = LogManager.GetLogger(typeof(JpegImageHelper));
                                    logger.Debug(MessageFormatUtil.Format("Inconsistent metadata (dpiX: {0} vs {1})", image.GetDpiX(), dx));
                                }
                                else
                                {
                                    image.SetDpi(dx, image.GetDpiY());
                                }
                            }
                            if (unitsy == 1 || unitsy == 2)
                            {
                                dy = (unitsy == 2 ? (int)(dy * 2.54f + 0.5f) : dy);
                                // make sure this is consistent with JFIF data
                                if (image.GetDpiY() != 0 && image.GetDpiY() != dy)
                                {
                                    ILog logger = LogManager.GetLogger(typeof(JpegImageHelper));
                                    logger.Debug(MessageFormatUtil.Format("Inconsistent metadata (dpiY: {0} vs {1})", image.GetDpiY(), dy));
                                }
                                else
                                {
                                    image.SetDpi(image.GetDpiX(), dx);
                                }
                            }
                        }
                        continue;
                    }
                    firstPass = false;
                    int markertype = Marker(marker);
                    if (markertype == VALID_MARKER)
                    {
                        StreamUtil.Skip(jpegStream, 2);
                        if (jpegStream.Read() != 0x08)
                        {
                            throw new iText.IO.IOException(iText.IO.IOException._1MustHave8BitsPerComponent).SetMessageParams(errorID);
                        }
                        image.SetHeight(GetShort(jpegStream));
                        image.SetWidth(GetShort(jpegStream));
                        image.SetColorSpace(jpegStream.Read());
                        image.SetBpc(8);
                        break;
                    }
                    else
                    {
                        if (markertype == UNSUPPORTED_MARKER)
                        {
                            throw new iText.IO.IOException(iText.IO.IOException._1UnsupportedJpegMarker2).SetMessageParams(errorID, JavaUtil.IntegerToString
                                                                                                                               (marker));
                        }
                        else
                        {
                            if (markertype != NOPARAM_MARKER)
                            {
                                StreamUtil.Skip(jpegStream, GetShort(jpegStream) - 2);
                            }
                        }
                    }
                }
            }
            if (icc != null)
            {
                int total = 0;
                for (int k = 0; k < icc.Length; ++k)
                {
                    if (icc[k] == null)
                    {
                        icc = null;
                        return;
                    }
                    total += icc[k].Length - 14;
                }
                byte[] ficc = new byte[total];
                total = 0;
                for (int k = 0; k < icc.Length; ++k)
                {
                    Array.Copy(icc[k], 14, ficc, total, icc[k].Length - 14);
                    total += icc[k].Length - 14;
                }
                try {
                    image.SetProfile(IccProfile.GetInstance(ficc, image.GetColorSpace()));
                }
                catch (ArgumentException) {
                }
            }
        }
Exemple #16
0
 /// <summary><inheritDoc/></summary>
 /// <exception cref="System.IO.IOException"/>
 public virtual double ReadDouble()
 {
     return(JavaUtil.LongBitsToDouble(ReadLong()));
 }
        /* (non-Javadoc)
         * @see com.itextpdf.styledxmlparser.css.resolve.shorthand.IShorthandResolver#resolveShorthand(java.lang.String)
         */
        public virtual IList <CssDeclaration> ResolveShorthand(String shorthandExpression)
        {
            if (UNSUPPORTED_VALUES_OF_FONT_SHORTHAND.Contains(shorthandExpression))
            {
                ILog logger = LogManager.GetLogger(typeof(FontShorthandResolver));
                logger.Error(MessageFormatUtil.Format("The \"{0}\" value of CSS shorthand property \"font\" is not supported"
                                                      , shorthandExpression));
            }
            if (CommonCssConstants.INITIAL.Equals(shorthandExpression) || CommonCssConstants.INHERIT.Equals(shorthandExpression
                                                                                                            ))
            {
                return(JavaUtil.ArraysAsList(new CssDeclaration(CommonCssConstants.FONT_STYLE, shorthandExpression), new CssDeclaration
                                                 (CommonCssConstants.FONT_VARIANT, shorthandExpression), new CssDeclaration(CommonCssConstants.FONT_WEIGHT
                                                                                                                            , shorthandExpression), new CssDeclaration(CommonCssConstants.FONT_SIZE, shorthandExpression), new CssDeclaration
                                                 (CommonCssConstants.LINE_HEIGHT, shorthandExpression), new CssDeclaration(CommonCssConstants.FONT_FAMILY
                                                                                                                           , shorthandExpression)));
            }
            String         fontStyleValue   = null;
            String         fontVariantValue = null;
            String         fontWeightValue  = null;
            String         fontSizeValue    = null;
            String         lineHeightValue  = null;
            String         fontFamilyValue  = null;
            IList <String> properties       = GetFontProperties(iText.IO.Util.StringUtil.ReplaceAll(shorthandExpression, "\\s*,\\s*"
                                                                                                    , ","));

            foreach (String value in properties)
            {
                int slashSymbolIndex = value.IndexOf('/');
                if (CommonCssConstants.ITALIC.Equals(value) || CommonCssConstants.OBLIQUE.Equals(value))
                {
                    fontStyleValue = value;
                }
                else
                {
                    if (CommonCssConstants.SMALL_CAPS.Equals(value))
                    {
                        fontVariantValue = value;
                    }
                    else
                    {
                        if (FONT_WEIGHT_NOT_DEFAULT_VALUES.Contains(value))
                        {
                            fontWeightValue = value;
                        }
                        else
                        {
                            if (slashSymbolIndex > 0)
                            {
                                fontSizeValue   = value.JSubstring(0, slashSymbolIndex);
                                lineHeightValue = value.JSubstring(slashSymbolIndex + 1, value.Length);
                            }
                            else
                            {
                                if (FONT_SIZE_VALUES.Contains(value) || CssUtils.IsMetricValue(value) || CssUtils.IsNumericValue(value) ||
                                    CssUtils.IsRelativeValue(value))
                                {
                                    fontSizeValue = value;
                                }
                                else
                                {
                                    fontFamilyValue = value;
                                }
                            }
                        }
                    }
                }
            }
            IList <CssDeclaration> cssDeclarations = JavaUtil.ArraysAsList(new CssDeclaration(CommonCssConstants.FONT_STYLE
                                                                                              , fontStyleValue == null ? CommonCssConstants.INITIAL : fontStyleValue), new CssDeclaration(CommonCssConstants
                                                                                                                                                                                          .FONT_VARIANT, fontVariantValue == null ? CommonCssConstants.INITIAL : fontVariantValue), new CssDeclaration
                                                                               (CommonCssConstants.FONT_WEIGHT, fontWeightValue == null ? CommonCssConstants.INITIAL : fontWeightValue
                                                                               ), new CssDeclaration(CommonCssConstants.FONT_SIZE, fontSizeValue == null ? CommonCssConstants.INITIAL
                 : fontSizeValue), new CssDeclaration(CommonCssConstants.LINE_HEIGHT, lineHeightValue == null ? CommonCssConstants
                                                      .INITIAL : lineHeightValue), new CssDeclaration(CommonCssConstants.FONT_FAMILY, fontFamilyValue == null
                 ? CommonCssConstants.INITIAL : fontFamilyValue));

            return(cssDeclarations);
        }
Exemple #18
0
 /// <exception cref="System.IO.IOException"/>
 public double ReadDoubleLE()
 {
     return(JavaUtil.LongBitsToDouble(ReadLongLE()));
 }
Exemple #19
0
 public override int GetHashCode()
 {
     return(content == null ? 0 : JavaUtil.ArraysHashCode(content));
 }
Exemple #20
0
 public PageRangePartAnd(params PageRange.IPageRangePart[] conditions)
 {
     this.conditions.AddAll(JavaUtil.ArraysAsList(conditions));
 }
Exemple #21
0
        /// <summary>Writes cross reference table and trailer to PDF.</summary>
        protected internal virtual void WriteXrefTableAndTrailer(PdfDocument document, PdfObject fileId, PdfObject
                                                                 crypto)
        {
            PdfWriter writer = document.GetWriter();

            if (!document.properties.appendMode)
            {
                for (int i = count; i > 0; --i)
                {
                    PdfIndirectReference lastRef = xref[i];
                    if (lastRef == null || lastRef.IsFree())
                    {
                        RemoveFreeRefFromList(i);
                        --count;
                    }
                    else
                    {
                        break;
                    }
                }
            }
            IList <int> sections = CreateSections(document, false);

            if (document.properties.appendMode && sections.Count == 0)
            {
                // no modifications.
                xref = null;
                return;
            }
            long startxref  = writer.GetCurrentPos();
            long xRefStmPos = -1;

            if (writer.IsFullCompression())
            {
                PdfStream xrefStream = (PdfStream) new PdfStream().MakeIndirect(document);
                xrefStream.MakeIndirect(document);
                xrefStream.Put(PdfName.Type, PdfName.XRef);
                xrefStream.Put(PdfName.ID, fileId);
                if (crypto != null)
                {
                    xrefStream.Put(PdfName.Encrypt, crypto);
                }
                xrefStream.Put(PdfName.Size, new PdfNumber(this.Size()));
                int offsetSize = GetOffsetSize(Math.Max(startxref, Size()));
                xrefStream.Put(PdfName.W, new PdfArray(JavaUtil.ArraysAsList((PdfObject) new PdfNumber(1), new PdfNumber(offsetSize
                                                                                                                         ), new PdfNumber(2))));
                xrefStream.Put(PdfName.Info, document.GetDocumentInfo().GetPdfObject());
                xrefStream.Put(PdfName.Root, document.GetCatalog().GetPdfObject());
                PdfArray index = new PdfArray();
                foreach (int?section in sections)
                {
                    index.Add(new PdfNumber((int)section));
                }
                if (document.properties.appendMode && !document.reader.hybridXref)
                {
                    // "not meaningful in hybrid-reference files"
                    PdfNumber lastXref = new PdfNumber(document.reader.GetLastXref());
                    xrefStream.Put(PdfName.Prev, lastXref);
                }
                xrefStream.Put(PdfName.Index, index);
                iText.Kernel.Pdf.PdfXrefTable xrefTable = document.GetXref();
                for (int k = 0; k < sections.Count; k += 2)
                {
                    int first = (int)sections[k];
                    int len   = (int)sections[k + 1];
                    for (int i = first; i < first + len; i++)
                    {
                        PdfIndirectReference reference = xrefTable.Get(i);
                        if (reference.IsFree())
                        {
                            xrefStream.GetOutputStream().Write(0);
                            xrefStream.GetOutputStream().Write(reference.GetOffset(), offsetSize);
                            xrefStream.GetOutputStream().Write(reference.GetGenNumber(), 2);
                        }
                        else
                        {
                            if (reference.GetObjStreamNumber() == 0)
                            {
                                xrefStream.GetOutputStream().Write(1);
                                xrefStream.GetOutputStream().Write(reference.GetOffset(), offsetSize);
                                xrefStream.GetOutputStream().Write(reference.GetGenNumber(), 2);
                            }
                            else
                            {
                                xrefStream.GetOutputStream().Write(2);
                                xrefStream.GetOutputStream().Write(reference.GetObjStreamNumber(), offsetSize);
                                xrefStream.GetOutputStream().Write(reference.GetIndex(), 2);
                            }
                        }
                    }
                }
                xrefStream.Flush();
                xRefStmPos = startxref;
            }
            // For documents with hybrid cross-reference table, i.e. containing xref streams as well as regular xref sections,
            // we write additional regular xref section at the end of the document because the /Prev reference from
            // xref stream to a regular xref section doesn't seem to be valid
            bool needsRegularXref = !writer.IsFullCompression() || document.properties.appendMode && document.reader.hybridXref;

            if (needsRegularXref)
            {
                startxref = writer.GetCurrentPos();
                writer.WriteString("xref\n");
                iText.Kernel.Pdf.PdfXrefTable xrefTable = document.GetXref();
                if (xRefStmPos != -1)
                {
                    // Get rid of all objects from object stream. This is done for hybrid documents
                    sections = CreateSections(document, true);
                }
                for (int k = 0; k < sections.Count; k += 2)
                {
                    int first = (int)sections[k];
                    int len   = (int)sections[k + 1];
                    writer.WriteInteger(first).WriteSpace().WriteInteger(len).WriteByte((byte)'\n');
                    for (int i = first; i < first + len; i++)
                    {
                        PdfIndirectReference reference = xrefTable.Get(i);
                        StringBuilder        off       = new StringBuilder("0000000000").Append(reference.GetOffset());
                        StringBuilder        gen       = new StringBuilder("00000").Append(reference.GetGenNumber());
                        writer.WriteString(off.JSubstring(off.Length - 10, off.Length)).WriteSpace().WriteString(gen.JSubstring(gen
                                                                                                                                .Length - 5, gen.Length)).WriteSpace();
                        if (reference.IsFree())
                        {
                            writer.WriteBytes(freeXRefEntry);
                        }
                        else
                        {
                            writer.WriteBytes(inUseXRefEntry);
                        }
                    }
                }
                PdfDictionary trailer = document.GetTrailer();
                // Remove all unused keys in case stamp mode in case original file has full compression, but destination file has not.
                trailer.Remove(PdfName.W);
                trailer.Remove(PdfName.Index);
                trailer.Remove(PdfName.Type);
                trailer.Remove(PdfName.Length);
                trailer.Put(PdfName.Size, new PdfNumber(this.Size()));
                trailer.Put(PdfName.ID, fileId);
                if (xRefStmPos != -1)
                {
                    trailer.Put(PdfName.XRefStm, new PdfNumber(xRefStmPos));
                }
                if (crypto != null)
                {
                    trailer.Put(PdfName.Encrypt, crypto);
                }
                writer.WriteString("trailer\n");
                if (document.properties.appendMode)
                {
                    PdfNumber lastXref = new PdfNumber(document.reader.GetLastXref());
                    trailer.Put(PdfName.Prev, lastXref);
                }
                writer.Write(document.GetTrailer());
                writer.Write('\n');
            }
            WriteKeyInfo(document);
            writer.WriteString("startxref\n").WriteLong(startxref).WriteString("\n%%EOF\n");
            xref = null;
            freeReferencesLinkedList.Clear();
        }
Exemple #22
0
 private static float[] GetDefaultColorants(int numOfColorants)
 {
     float[] colorants = new float[numOfColorants];
     JavaUtil.Fill(colorants, 1f);
     return(colorants);
 }
Exemple #23
0
        public virtual void AddCustomEvenConstructor()
        {
            PageRange range = new PageRange("even");

            NUnit.Framework.Assert.AreEqual(range.GetQualifyingPageNums(5), JavaUtil.ArraysAsList(2, 4));
        }
 public virtual void QueueTest()
 {
     TestCache(new EventDataCacheQueueBased <String, DataCacheTest.SimpleData>(), JavaUtil.ArraysAsList(new DataCacheTest.SimpleData
                                                                                                            ("type1", 10), new DataCacheTest.SimpleData("type2", 4), new DataCacheTest.SimpleData("type3", 5), new
                                                                                                        DataCacheTest.SimpleData("type2", 12)), JavaUtil.ArraysAsList(new DataCacheTest.SimpleData("type1", 10
                                                                                                                                                                                                   ), new DataCacheTest.SimpleData("type2", 16), new DataCacheTest.SimpleData("type3", 5)));
 }
Exemple #25
0
 /// <summary>
 /// Adds polyline path based on array of
 /// <see cref="iText.Kernel.Geom.Point"/>
 /// (internally converting
 /// them by
 /// <see cref="ConvertToLongPoints(System.Collections.Generic.IList{E})"/>
 /// ) and adds this path to
 /// <see cref="Clipper"/>
 /// instance, treating the path as
 /// a polyline (an open path in terms of clipper library). This path is added to the subject of future clipping.
 /// Polylines cannot be part of clipping polygon.
 /// <para />
 /// The return value will be false if the path is invalid for clipping. A path is invalid for clipping when:
 /// <ul>
 /// <li>it has less than 2 vertices;
 /// </ul>
 /// </summary>
 /// <param name="clipper">
 ///
 /// <see cref="Clipper"/>
 /// instance to which the created polyline path will be added.
 /// </param>
 /// <param name="lineVertices">
 /// an array of
 /// <see cref="iText.Kernel.Geom.Point"/>
 /// which will be internally converted
 /// to clipper path and added to the clipper instance.
 /// </param>
 /// <returns>true if polyline path was successfully added, false otherwise.</returns>
 public static bool AddPolylineSubjectToClipper(Clipper clipper, Point[] lineVertices)
 {
     return(clipper.AddPath(new List <IntPoint>(ConvertToLongPoints(new List <Point>(JavaUtil.ArraysAsList(lineVertices
                                                                                                           )))), PolyType.SUBJECT, false));
 }
 public virtual void BiggestCountTest()
 {
     TestCache(new EventDataCacheComparatorBased <String, DataCacheTest.SimpleData>(new EventDataHandlerUtil.BiggerCountComparator
                                                                                    <String, DataCacheTest.SimpleData>()), JavaUtil.ArraysAsList(new DataCacheTest.SimpleData("type1", 10)
                                                                                                                                                 , new DataCacheTest.SimpleData("type2", 4), new DataCacheTest.SimpleData("type3", 5), new DataCacheTest.SimpleData
                                                                                                                                                     ("type2", 8)), JavaUtil.ArraysAsList(new DataCacheTest.SimpleData("type2", 12), new DataCacheTest.SimpleData
                                                                                                                                                                                              ("type1", 10), new DataCacheTest.SimpleData("type3", 5)));
 }
Exemple #27
0
        // this method is ugly, and does a lot. but other breakups cause rescanning and stringbuilder generations
        internal static void Escape(StringBuilder accum, String str, OutputSettings outputSettings, bool inAttribute
                                    , bool normaliseWhite, bool stripLeadingWhite)
        {
            bool lastWasWhite    = false;
            bool reachedNonWhite = false;

            Entities.EscapeMode        escapeMode  = outputSettings.EscapeMode();
            System.Text.Encoding       encoder     = outputSettings.Charset();
            Entities.CoreCharset       coreCharset = GetCoreCharsetByName(outputSettings.Charset().Name());
            IDictionary <char, String> map         = escapeMode.GetMap();
            int length = str.Length;
            int codePoint;

            for (int offset = 0; offset < length; offset += iText.IO.Util.TextUtil.CharCount(codePoint))
            {
                codePoint = str.CodePointAt(offset);
                if (normaliseWhite)
                {
                    if (iText.StyledXmlParser.Jsoup.Helper.StringUtil.IsWhitespace(codePoint))
                    {
                        if ((stripLeadingWhite && !reachedNonWhite) || lastWasWhite)
                        {
                            continue;
                        }
                        accum.Append(' ');
                        lastWasWhite = true;
                        continue;
                    }
                    else
                    {
                        lastWasWhite    = false;
                        reachedNonWhite = true;
                    }
                }
                // surrogate pairs, split implementation for efficiency on single char common case (saves creating strings, char[]):
                if (codePoint < iText.IO.Util.TextUtil.CHARACTER_MIN_SUPPLEMENTARY_CODE_POINT)
                {
                    char c = (char)codePoint;
                    // html specific and required escapes:
                    switch (c)
                    {
                    case '&': {
                        accum.Append("&amp;");
                        break;
                    }

                    case (char)0xA0: {
                        if (escapeMode != Entities.EscapeMode.xhtml)
                        {
                            accum.Append("&nbsp;");
                        }
                        else
                        {
                            accum.Append("&#xa0;");
                        }
                        break;
                    }

                    case '<': {
                        // escape when in character data or when in a xml attribue val; not needed in html attr val
                        if (!inAttribute || escapeMode == Entities.EscapeMode.xhtml)
                        {
                            accum.Append("&lt;");
                        }
                        else
                        {
                            accum.Append(c);
                        }
                        break;
                    }

                    case '>': {
                        if (!inAttribute)
                        {
                            accum.Append("&gt;");
                        }
                        else
                        {
                            accum.Append(c);
                        }
                        break;
                    }

                    case '"': {
                        if (inAttribute)
                        {
                            accum.Append("&quot;");
                        }
                        else
                        {
                            accum.Append(c);
                        }
                        break;
                    }

                    default: {
                        if (CanEncode(coreCharset, c, encoder))
                        {
                            accum.Append(c);
                        }
                        else
                        {
                            if (map.ContainsKey(c))
                            {
                                accum.Append('&').Append(map.Get(c)).Append(';');
                            }
                            else
                            {
                                accum.Append("&#x").Append(JavaUtil.IntegerToHexString(codePoint)).Append(';');
                            }
                        }
                        break;
                    }
                    }
                }
                else
                {
                    String c = new String(iText.IO.Util.TextUtil.ToChars(codePoint));
                    if (encoder.CanEncode(c))
                    {
                        // uses fallback encoder for simplicity
                        accum.Append(c);
                    }
                    else
                    {
                        accum.Append("&#x").Append(JavaUtil.IntegerToHexString(codePoint)).Append(';');
                    }
                }
            }
        }
Exemple #28
0
 /// <summary>Adds an unspecified amount of tabstop elements as properties to the Paragraph.</summary>
 /// <param name="tabStops">
 /// the
 /// <see cref="TabStop">tabstop(s)</see>
 /// to be added as properties
 /// </param>
 /// <returns>this Paragraph</returns>
 /// <seealso cref="TabStop"/>
 public virtual iText.Layout.Element.Paragraph AddTabStops(params TabStop[] tabStops)
 {
     AddTabStopsAsProperty(JavaUtil.ArraysAsList(tabStops));
     return(this);
 }
Exemple #29
0
        private IRenderer CreateListSymbolRenderer(int index, IRenderer renderer)
        {
            Object defaultListSymbol = GetListItemOrListProperty(renderer, this, Property.LIST_SYMBOL);

            if (defaultListSymbol is Text)
            {
                return(SurroundTextBullet(new TextRenderer((Text)defaultListSymbol)));
            }
            else
            {
                if (defaultListSymbol is Image)
                {
                    return(new ImageRenderer((Image)defaultListSymbol));
                }
                else
                {
                    if (defaultListSymbol is ListNumberingType)
                    {
                        ListNumberingType numberingType = (ListNumberingType)defaultListSymbol;
                        String            numberText;
                        switch (numberingType)
                        {
                        case ListNumberingType.DECIMAL: {
                            numberText = index.ToString();
                            break;
                        }

                        case ListNumberingType.DECIMAL_LEADING_ZERO: {
                            numberText = (index < 10 ? "0" : "") + index.ToString();
                            break;
                        }

                        case ListNumberingType.ROMAN_LOWER: {
                            numberText = RomanNumbering.ToRomanLowerCase(index);
                            break;
                        }

                        case ListNumberingType.ROMAN_UPPER: {
                            numberText = RomanNumbering.ToRomanUpperCase(index);
                            break;
                        }

                        case ListNumberingType.ENGLISH_LOWER: {
                            numberText = EnglishAlphabetNumbering.ToLatinAlphabetNumberLowerCase(index);
                            break;
                        }

                        case ListNumberingType.ENGLISH_UPPER: {
                            numberText = EnglishAlphabetNumbering.ToLatinAlphabetNumberUpperCase(index);
                            break;
                        }

                        case ListNumberingType.GREEK_LOWER: {
                            numberText = GreekAlphabetNumbering.ToGreekAlphabetNumber(index, false, true);
                            break;
                        }

                        case ListNumberingType.GREEK_UPPER: {
                            numberText = GreekAlphabetNumbering.ToGreekAlphabetNumber(index, true, true);
                            break;
                        }

                        case ListNumberingType.ZAPF_DINGBATS_1: {
                            numberText = JavaUtil.CharToString((char)(index + 171));
                            break;
                        }

                        case ListNumberingType.ZAPF_DINGBATS_2: {
                            numberText = JavaUtil.CharToString((char)(index + 181));
                            break;
                        }

                        case ListNumberingType.ZAPF_DINGBATS_3: {
                            numberText = JavaUtil.CharToString((char)(index + 191));
                            break;
                        }

                        case ListNumberingType.ZAPF_DINGBATS_4: {
                            numberText = JavaUtil.CharToString((char)(index + 201));
                            break;
                        }

                        default: {
                            throw new InvalidOperationException();
                        }
                        }
                        Text textElement = new Text(GetListItemOrListProperty(renderer, this, Property.LIST_SYMBOL_PRE_TEXT) + numberText
                                                    + GetListItemOrListProperty(renderer, this, Property.LIST_SYMBOL_POST_TEXT));
                        IRenderer textRenderer;
                        // Be careful. There is a workaround here. For Greek symbols we first set a dummy font with document=null
                        // in order for the metrics to be taken into account correctly during layout.
                        // Then on draw we set the correct font with actual document in order for the font objects to be created.
                        if (numberingType == ListNumberingType.GREEK_LOWER || numberingType == ListNumberingType.GREEK_UPPER || numberingType
                            == ListNumberingType.ZAPF_DINGBATS_1 || numberingType == ListNumberingType.ZAPF_DINGBATS_2 || numberingType
                            == ListNumberingType.ZAPF_DINGBATS_3 || numberingType == ListNumberingType.ZAPF_DINGBATS_4)
                        {
                            String constantFont = (numberingType == ListNumberingType.GREEK_LOWER || numberingType == ListNumberingType
                                                   .GREEK_UPPER) ? StandardFonts.SYMBOL : StandardFonts.ZAPFDINGBATS;
                            textRenderer = new _TextRenderer_211(constantFont, textElement);
                            try {
                                textRenderer.SetProperty(Property.FONT, PdfFontFactory.CreateFont(constantFont));
                            }
                            catch (System.IO.IOException) {
                            }
                        }
                        else
                        {
                            textRenderer = new TextRenderer(textElement);
                        }
                        return(SurroundTextBullet(textRenderer));
                    }
                    else
                    {
                        if (defaultListSymbol is IListSymbolFactory)
                        {
                            return(SurroundTextBullet(((IListSymbolFactory)defaultListSymbol).CreateSymbol(index, this, renderer).CreateRendererSubTree
                                                          ()));
                        }
                        else
                        {
                            if (defaultListSymbol == null)
                            {
                                return(null);
                            }
                            else
                            {
                                throw new InvalidOperationException();
                            }
                        }
                    }
                }
            }
        }
Exemple #30
0
        /// <summary>Places the barcode in a <c>PdfCanvas</c>.</summary>
        /// <remarks>
        /// Places the barcode in a <c>PdfCanvas</c>. The
        /// barcode is always placed at coordinates (0, 0). Use the
        /// translation matrix to move it elsewhere.
        /// <para />
        /// The bars and text are written in the following colors:
        /// <table border="1" summary="">
        /// <tr>
        /// <th><c>barColor</c></th>
        /// <th><c>textColor</c></th>
        /// <th>Result</th>
        /// </tr>
        /// <tr>
        /// <td><c>null</c></td>
        /// <td><c>null</c></td>
        /// <td>bars and text painted with current fill color</td>
        /// </tr>
        /// <tr>
        /// <td><c>barColor</c></td>
        /// <td><c>null</c></td>
        /// <td>bars and text painted with <c>barColor</c></td>
        /// </tr>
        /// <tr>
        /// <td><c>null</c></td>
        /// <td><c>textColor</c></td>
        /// <td>bars painted with current color<br />text painted with <c>textColor</c></td>
        /// </tr>
        /// <tr>
        /// <td><c>barColor</c></td>
        /// <td><c>textColor</c></td>
        /// <td>bars painted with <c>barColor</c><br />text painted with <c>textColor</c></td>
        /// </tr>
        /// </table>
        /// </remarks>
        /// <param name="canvas">the <c>PdfCanvas</c> where the barcode will be placed</param>
        /// <param name="barColor">the color of the bars. It can be <c>null</c></param>
        /// <param name="textColor">the color of the text. It can be <c>null</c></param>
        /// <returns>the dimensions the barcode occupies</returns>
        public override Rectangle PlaceBarcode(PdfCanvas canvas, Color barColor, Color textColor)
        {
            String fullCode = this.code;

            if (this.checksumText)
            {
                fullCode = fullCode + JavaUtil.IntegerToString(GetChecksum(this.code));
            }
            float fontX = 0.0f;

            if (this.font != null)
            {
                String var10001 = this.altText != null ? this.altText : fullCode;
                fullCode = this.altText != null ? this.altText : fullCode;
                fontX    = this.font.GetWidth(var10001, this.size);
            }
            String bCode = this.code;

            if (this.generateChecksum)
            {
                bCode += GetChecksum(bCode);
            }
            int idx;

            idx = bCode.Length;
            float fullWidth  = (float)((idx + 2) * 11) * this.x + 2.0f * this.x;
            float barStartX  = 0.0f;
            float textStartX = 0.0f;

            switch (this.textAlignment)
            {
            case 1: {
                break;
            }

            case 2: {
                if (fontX > fullWidth)
                {
                    barStartX = fontX - fullWidth;
                }
                else
                {
                    textStartX = fullWidth - fontX;
                }
                break;
            }

            default: {
                if (fontX > fullWidth)
                {
                    barStartX = (fontX - fullWidth) / 2.0f;
                }
                else
                {
                    textStartX = (fullWidth - fontX) / 2.0f;
                }
                break;
            }
            }
            float barStartY  = 0.0f;
            float textStartY = 0.0f;

            if (this.font != null)
            {
                if (this.baseline <= 0.0f)
                {
                    textStartY = this.barHeight - this.baseline;
                }
                else
                {
                    textStartY = -this.GetDescender();
                    barStartY  = textStartY + this.baseline;
                }
            }
            byte[] bars = GetBarsMSI(bCode);
            if (barColor != null)
            {
                canvas.SetFillColor(barColor);
            }
            for (int k = 0; k < bars.Length; ++k)
            {
                float w = (float)bars[k] * this.x;
                if (bars[k] == 1)
                {
                    canvas.Rectangle((double)barStartX, (double)barStartY, (double)(w - this.inkSpreading), (double)this.barHeight
                                     );
                }
                barStartX += this.x;
            }
            canvas.Fill();
            if (this.font != null)
            {
                if (textColor != null)
                {
                    canvas.SetFillColor(textColor);
                }
                canvas.BeginText();
                canvas.SetFontAndSize(this.font, this.size);
                canvas.SetTextMatrix(textStartX, textStartY);
                canvas.ShowText(fullCode);
                canvas.EndText();
            }
            return(this.GetBarcodeSize());
        }