コード例 #1
0
ファイル: PdfGoToRemote.cs プロジェクト: nholik/Fo.Net
 static PdfGoToRemote()
 {
     DefaultDestination = new PdfArray();
     DefaultDestination.Add(new PdfNumeric(0));
     DefaultDestination.Add(PdfName.Names.XYZ);
     DefaultDestination.Add(PdfNull.Null);
     DefaultDestination.Add(PdfNull.Null);
     DefaultDestination.Add(PdfNull.Null);
 }
コード例 #2
0
ファイル: PdfResources.cs プロジェクト: nholik/Fo.Net
 static PdfResources()
 {
     DefaultProcedureSets = new PdfArray();
     DefaultProcedureSets.Add(PdfName.Names.PDF);
     DefaultProcedureSets.Add(PdfName.Names.Text);
     DefaultProcedureSets.Add(PdfName.Names.ImageB);
     DefaultProcedureSets.Add(PdfName.Names.ImageC);
     DefaultProcedureSets.Add(PdfName.Names.ImageI);
 }
コード例 #3
0
ファイル: PdfGoTo.cs プロジェクト: nholik/Fo.Net
 protected internal override void Write(PdfWriter writer)
 {
     PdfArray dest = new PdfArray();
     dest.Add(pageReference);
     dest.Add(PdfName.Names.XYZ);
     dest.Add(new PdfNumeric(xPosition));
     dest.Add(new PdfNumeric(yPosition));
     dest.Add(PdfNull.Null);
     this[PdfName.Names.D] = dest;
     base.Write(writer);
 }
コード例 #4
0
        private PdfObject CleverPdfArrayClone(PdfArray array) {
            PdfArray newArray = new PdfArray();
            for (int i = 0; i < array.Size; i++) {
                PdfObject obj = array[i];
                if (obj is PdfDictionary)
                    newArray.Add(CleverPdfDictionaryClone((PdfDictionary) obj));
                else
                    newArray.Add(obj);
            }

            return newArray;
        }
コード例 #5
0
ファイル: PdfPage.cs プロジェクト: nholik/Fo.Net
        public PdfPage(
            PdfResources resources,
            PdfContentStream contents,
            int pagewidth,
            int pageheight,
            PdfObjectId objectId)
            : base(objectId)
        {
            this[PdfName.Names.Type] = PdfName.Names.Page;
            this[PdfName.Names.Resources] = resources.GetReference();
            this[PdfName.Names.Contents] = contents.GetReference();

            PdfArray mediaBox = new PdfArray();
            mediaBox.Add(new PdfNumeric(0));
            mediaBox.Add(new PdfNumeric(0));
            mediaBox.Add(new PdfNumeric(pagewidth));
            mediaBox.Add(new PdfNumeric(pageheight));
            this[PdfName.Names.MediaBox] = mediaBox;
        }
コード例 #6
0
        private PdfArray EnsureArray(
            )
        {
            PdfDataObject baseDataObject = BaseDataObject;

            if (baseDataObject is PdfDictionary) // Merged annotation.
            {
                PdfArray widgetsArray = new PdfArray();
                {
                    PdfDictionary fieldDictionary  = (PdfDictionary)baseDataObject;
                    PdfDictionary widgetDictionary = null;
                    // Extracting widget entries from the field...
                    foreach (PdfName key in new List <PdfName>(fieldDictionary.Keys))
                    {
                        // Is it a widget entry?
                        if (key.Equals(PdfName.Type) ||
                            key.Equals(PdfName.Subtype) ||
                            key.Equals(PdfName.Rect) ||
                            key.Equals(PdfName.Contents) ||
                            key.Equals(PdfName.P) ||
                            key.Equals(PdfName.NM) ||
                            key.Equals(PdfName.M) ||
                            key.Equals(PdfName.F) ||
                            key.Equals(PdfName.BS) ||
                            key.Equals(PdfName.AP) ||
                            key.Equals(PdfName.AS) ||
                            key.Equals(PdfName.Border) ||
                            key.Equals(PdfName.C) ||
                            key.Equals(PdfName.A) ||
                            key.Equals(PdfName.AA) ||
                            key.Equals(PdfName.StructParent) ||
                            key.Equals(PdfName.OC) ||
                            key.Equals(PdfName.H) ||
                            key.Equals(PdfName.MK))
                        {
                            if (widgetDictionary == null)
                            {
                                widgetDictionary = new PdfDictionary();
                                PdfReference widgetReference = File.Register(widgetDictionary);

                                // Remove the field from the page annotations (as the widget annotation is decoupled from it)!
                                PdfArray pageAnnotationsArray = (PdfArray)((PdfDictionary)fieldDictionary.Resolve(PdfName.P)).Resolve(PdfName.Annots);
                                pageAnnotationsArray.Remove(field.BaseObject);

                                // Add the widget to the page annotations!
                                pageAnnotationsArray.Add(widgetReference);
                                // Add the widget to the field widgets!
                                widgetsArray.Add(widgetReference);
                                // Associate the field to the widget!
                                widgetDictionary[PdfName.Parent] = field.BaseObject;
                            }

                            // Transfer the entry from the field to the widget!
                            widgetDictionary[key] = fieldDictionary[key];
                            fieldDictionary.Remove(key);
                        }
                    }
                }
                BaseObject = widgetsArray;
                field.BaseDataObject[PdfName.Kids] = widgetsArray;

                baseDataObject = widgetsArray;
            }

            return((PdfArray)baseDataObject);
        }
コード例 #7
0
 PdfObject GetColorspace()
 {
     if (icc_profile != null)
     {
         if ((colorType & 2) == 0)
         {
             return(PdfName.DEVICEGRAY);
         }
         else
         {
             return(PdfName.DEVICERGB);
         }
     }
     if (gamma == 1f && !hasCHRM)
     {
         if ((colorType & 2) == 0)
         {
             return(PdfName.DEVICEGRAY);
         }
         else
         {
             return(PdfName.DEVICERGB);
         }
     }
     else
     {
         PdfArray      array = new PdfArray();
         PdfDictionary dic   = new PdfDictionary();
         if ((colorType & 2) == 0)
         {
             if (gamma == 1f)
             {
                 return(PdfName.DEVICEGRAY);
             }
             array.Add(PdfName.CALGRAY);
             dic.Put(PdfName.GAMMA, new PdfNumber(gamma));
             dic.Put(PdfName.WHITEPOINT, new PdfLiteral("[1 1 1]"));
             array.Add(dic);
         }
         else
         {
             PdfObject wp = new PdfLiteral("[1 1 1]");
             array.Add(PdfName.CALRGB);
             if (gamma != 1f)
             {
                 PdfArray  gm = new PdfArray();
                 PdfNumber n  = new PdfNumber(gamma);
                 gm.Add(n);
                 gm.Add(n);
                 gm.Add(n);
                 dic.Put(PdfName.GAMMA, gm);
             }
             if (hasCHRM)
             {
                 float    z   = yW * ((xG - xB) * yR - (xR - xB) * yG + (xR - xG) * yB);
                 float    YA  = yR * ((xG - xB) * yW - (xW - xB) * yG + (xW - xG) * yB) / z;
                 float    XA  = YA * xR / yR;
                 float    ZA  = YA * ((1 - xR) / yR - 1);
                 float    YB  = -yG * ((xR - xB) * yW - (xW - xB) * yR + (xW - xR) * yB) / z;
                 float    XB  = YB * xG / yG;
                 float    ZB  = YB * ((1 - xG) / yG - 1);
                 float    YC  = yB * ((xR - xG) * yW - (xW - xG) * yW + (xW - xR) * yG) / z;
                 float    XC  = YC * xB / yB;
                 float    ZC  = YC * ((1 - xB) / yB - 1);
                 float    XW  = XA + XB + XC;
                 float    YW  = 1;//YA+YB+YC;
                 float    ZW  = ZA + ZB + ZC;
                 PdfArray wpa = new PdfArray();
                 wpa.Add(new PdfNumber(XW));
                 wpa.Add(new PdfNumber(YW));
                 wpa.Add(new PdfNumber(ZW));
                 wp = wpa;
                 PdfArray matrix = new PdfArray();
                 matrix.Add(new PdfNumber(XA));
                 matrix.Add(new PdfNumber(YA));
                 matrix.Add(new PdfNumber(ZA));
                 matrix.Add(new PdfNumber(XB));
                 matrix.Add(new PdfNumber(YB));
                 matrix.Add(new PdfNumber(ZB));
                 matrix.Add(new PdfNumber(XC));
                 matrix.Add(new PdfNumber(YC));
                 matrix.Add(new PdfNumber(ZC));
                 dic.Put(PdfName.MATRIX, matrix);
             }
             dic.Put(PdfName.WHITEPOINT, wp);
             array.Add(dic);
         }
         return(array);
     }
 }
コード例 #8
0
        private void OutputDss(PdfDictionary dss, PdfDictionary vrim, PdfArray ocsps, PdfArray crls, PdfArray certs)
        {
            writer.AddDeveloperExtension(PdfDeveloperExtension.ESIC_1_7_EXTENSIONLEVEL5);
            PdfDictionary catalog = reader.Catalog;

            stp.MarkUsed(catalog);
            foreach (PdfName vkey in validated.Keys)
            {
                PdfArray      ocsp = new PdfArray();
                PdfArray      crl  = new PdfArray();
                PdfArray      cert = new PdfArray();
                PdfDictionary vri  = new PdfDictionary();
                foreach (byte[] b in validated[vkey].crls)
                {
                    PdfStream ps = new PdfStream(b);
                    ps.FlateCompress();
                    PdfIndirectReference iref = writer.AddToBody(ps, false).IndirectReference;
                    crl.Add(iref);
                    crls.Add(iref);
                }
                foreach (byte[] b in validated[vkey].ocsps)
                {
                    PdfStream ps = new PdfStream(b);
                    ps.FlateCompress();
                    PdfIndirectReference iref = writer.AddToBody(ps, false).IndirectReference;
                    ocsp.Add(iref);
                    ocsps.Add(iref);
                }
                foreach (byte[] b in validated[vkey].certs)
                {
                    PdfStream ps = new PdfStream(b);
                    ps.FlateCompress();
                    PdfIndirectReference iref = writer.AddToBody(ps, false).IndirectReference;
                    cert.Add(iref);
                    certs.Add(iref);
                }
                if (ocsp.Size > 0)
                {
                    vri.Put(PdfName.OCSP, writer.AddToBody(ocsp, false).IndirectReference);
                }
                if (crl.Size > 0)
                {
                    vri.Put(PdfName.CRL, writer.AddToBody(crl, false).IndirectReference);
                }
                if (cert.Size > 0)
                {
                    vri.Put(PdfName.CERT, writer.AddToBody(cert, false).IndirectReference);
                }
                vrim.Put(vkey, writer.AddToBody(vri, false).IndirectReference);
            }
            dss.Put(PdfName.VRI, writer.AddToBody(vrim, false).IndirectReference);
            if (ocsps.Size > 0)
            {
                dss.Put(PdfName.OCSPS, writer.AddToBody(ocsps, false).IndirectReference);
            }
            if (crls.Size > 0)
            {
                dss.Put(PdfName.CRLS, writer.AddToBody(crls, false).IndirectReference);
            }
            if (certs.Size > 0)
            {
                dss.Put(PdfName.CERTS, writer.AddToBody(certs, false).IndirectReference);
            }
            catalog.Put(PdfName.DSS, writer.AddToBody(dss, false).IndirectReference);
        }
コード例 #9
0
ファイル: TiffImage.cs プロジェクト: zeespogeira/itextsharp
        protected static Image GetTiffImageColor(TIFFDirectory dir, RandomAccessFileOrArray s)
        {
            int            predictor   = 1;
            TIFFLZWDecoder lzwDecoder  = null;
            int            compression = TIFFConstants.COMPRESSION_NONE;

            if (dir.IsTagPresent(TIFFConstants.TIFFTAG_COMPRESSION))
            {
                compression = (int)dir.GetFieldAsLong(TIFFConstants.TIFFTAG_COMPRESSION);
            }
            switch (compression)
            {
            case TIFFConstants.COMPRESSION_NONE:
            case TIFFConstants.COMPRESSION_LZW:
            case TIFFConstants.COMPRESSION_PACKBITS:
            case TIFFConstants.COMPRESSION_DEFLATE:
            case TIFFConstants.COMPRESSION_ADOBE_DEFLATE:
            case TIFFConstants.COMPRESSION_OJPEG:
            case TIFFConstants.COMPRESSION_JPEG:
                break;

            default:
                throw new ArgumentException(MessageLocalization.GetComposedMessage("the.compression.1.is.not.supported", compression));
            }
            int photometric = (int)dir.GetFieldAsLong(TIFFConstants.TIFFTAG_PHOTOMETRIC);

            switch (photometric)
            {
            case TIFFConstants.PHOTOMETRIC_MINISWHITE:
            case TIFFConstants.PHOTOMETRIC_MINISBLACK:
            case TIFFConstants.PHOTOMETRIC_RGB:
            case TIFFConstants.PHOTOMETRIC_SEPARATED:
            case TIFFConstants.PHOTOMETRIC_PALETTE:
                break;

            default:
                if (compression != TIFFConstants.COMPRESSION_OJPEG && compression != TIFFConstants.COMPRESSION_JPEG)
                {
                    throw new ArgumentException(MessageLocalization.GetComposedMessage("the.photometric.1.is.not.supported", photometric));
                }
                break;
            }
            float rotation = 0;

            if (dir.IsTagPresent(TIFFConstants.TIFFTAG_ORIENTATION))
            {
                int rot = (int)dir.GetFieldAsLong(TIFFConstants.TIFFTAG_ORIENTATION);
                if (rot == TIFFConstants.ORIENTATION_BOTRIGHT || rot == TIFFConstants.ORIENTATION_BOTLEFT)
                {
                    rotation = (float)Math.PI;
                }
                else if (rot == TIFFConstants.ORIENTATION_LEFTTOP || rot == TIFFConstants.ORIENTATION_LEFTBOT)
                {
                    rotation = (float)(Math.PI / 2.0);
                }
                else if (rot == TIFFConstants.ORIENTATION_RIGHTTOP || rot == TIFFConstants.ORIENTATION_RIGHTBOT)
                {
                    rotation = -(float)(Math.PI / 2.0);
                }
            }

            if (dir.IsTagPresent(TIFFConstants.TIFFTAG_PLANARCONFIG) &&
                dir.GetFieldAsLong(TIFFConstants.TIFFTAG_PLANARCONFIG) == TIFFConstants.PLANARCONFIG_SEPARATE)
            {
                throw new ArgumentException(MessageLocalization.GetComposedMessage("planar.images.are.not.supported"));
            }
            int extraSamples = 0;

            if (dir.IsTagPresent(TIFFConstants.TIFFTAG_EXTRASAMPLES))
            {
                extraSamples = 1;
            }
            int samplePerPixel = 1;

            if (dir.IsTagPresent(TIFFConstants.TIFFTAG_SAMPLESPERPIXEL)) // 1,3,4
            {
                samplePerPixel = (int)dir.GetFieldAsLong(TIFFConstants.TIFFTAG_SAMPLESPERPIXEL);
            }
            int bitsPerSample = 1;

            if (dir.IsTagPresent(TIFFConstants.TIFFTAG_BITSPERSAMPLE))
            {
                bitsPerSample = (int)dir.GetFieldAsLong(TIFFConstants.TIFFTAG_BITSPERSAMPLE);
            }
            switch (bitsPerSample)
            {
            case 1:
            case 2:
            case 4:
            case 8:
                break;

            default:
                throw new ArgumentException(MessageLocalization.GetComposedMessage("bits.per.sample.1.is.not.supported", bitsPerSample));
            }
            Image img = null;

            int h              = (int)dir.GetFieldAsLong(TIFFConstants.TIFFTAG_IMAGELENGTH);
            int w              = (int)dir.GetFieldAsLong(TIFFConstants.TIFFTAG_IMAGEWIDTH);
            int dpiX           = 0;
            int dpiY           = 0;
            int resolutionUnit = TIFFConstants.RESUNIT_INCH;

            if (dir.IsTagPresent(TIFFConstants.TIFFTAG_RESOLUTIONUNIT))
            {
                resolutionUnit = (int)dir.GetFieldAsLong(TIFFConstants.TIFFTAG_RESOLUTIONUNIT);
            }
            dpiX = GetDpi(dir.GetField(TIFFConstants.TIFFTAG_XRESOLUTION), resolutionUnit);
            dpiY = GetDpi(dir.GetField(TIFFConstants.TIFFTAG_YRESOLUTION), resolutionUnit);
            int       fillOrder      = 1;
            bool      reverse        = false;
            TIFFField fillOrderField = dir.GetField(TIFFConstants.TIFFTAG_FILLORDER);

            if (fillOrderField != null)
            {
                fillOrder = fillOrderField.GetAsInt(0);
            }
            reverse = (fillOrder == TIFFConstants.FILLORDER_LSB2MSB);
            int rowsStrip = h;

            if (dir.IsTagPresent(TIFFConstants.TIFFTAG_ROWSPERSTRIP)) //another hack for broken tiffs
            {
                rowsStrip = (int)dir.GetFieldAsLong(TIFFConstants.TIFFTAG_ROWSPERSTRIP);
            }
            if (rowsStrip <= 0 || rowsStrip > h)
            {
                rowsStrip = h;
            }
            long[] offset = GetArrayLongShort(dir, TIFFConstants.TIFFTAG_STRIPOFFSETS);
            long[] size   = GetArrayLongShort(dir, TIFFConstants.TIFFTAG_STRIPBYTECOUNTS);
            if ((size == null || (size.Length == 1 && (size[0] == 0 || size[0] + offset[0] > s.Length))) && h == rowsStrip)   // some TIFF producers are really lousy, so...
            {
                size = new long[] { s.Length - (int)offset[0] };
            }
            if (compression == TIFFConstants.COMPRESSION_LZW || compression == TIFFConstants.COMPRESSION_DEFLATE || compression == TIFFConstants.COMPRESSION_ADOBE_DEFLATE)
            {
                TIFFField predictorField = dir.GetField(TIFFConstants.TIFFTAG_PREDICTOR);
                if (predictorField != null)
                {
                    predictor = predictorField.GetAsInt(0);
                    if (predictor != 1 && predictor != 2)
                    {
                        throw new Exception(MessageLocalization.GetComposedMessage("illegal.value.for.predictor.in.tiff.file"));
                    }
                    if (predictor == 2 && bitsPerSample != 8)
                    {
                        throw new Exception(MessageLocalization.GetComposedMessage("1.bit.samples.are.not.supported.for.horizontal.differencing.predictor", bitsPerSample));
                    }
                }
            }
            if (compression == TIFFConstants.COMPRESSION_LZW)
            {
                lzwDecoder = new TIFFLZWDecoder(w, predictor, samplePerPixel);
            }
            int                   rowsLeft = h;
            MemoryStream          stream   = null;
            MemoryStream          mstream  = null;
            ZDeflaterOutputStream zip      = null;
            ZDeflaterOutputStream mzip     = null;

            if (extraSamples > 0)
            {
                mstream = new MemoryStream();
                mzip    = new ZDeflaterOutputStream(mstream);
            }

            CCITTG4Encoder g4 = null;

            if (bitsPerSample == 1 && samplePerPixel == 1 && photometric != TIFFConstants.PHOTOMETRIC_PALETTE)
            {
                g4 = new CCITTG4Encoder(w);
            }
            else
            {
                stream = new MemoryStream();
                if (compression != TIFFConstants.COMPRESSION_OJPEG && compression != TIFFConstants.COMPRESSION_JPEG)
                {
                    zip = new ZDeflaterOutputStream(stream);
                }
            }
            if (compression == TIFFConstants.COMPRESSION_OJPEG)
            {
                // Assume that the TIFFTAG_JPEGIFBYTECOUNT tag is optional, since it's obsolete and
                // is often missing

                if ((!dir.IsTagPresent(TIFFConstants.TIFFTAG_JPEGIFOFFSET)))
                {
                    throw new IOException(MessageLocalization.GetComposedMessage("missing.tag.s.for.ojpeg.compression"));
                }
                int jpegOffset = (int)dir.GetFieldAsLong(TIFFConstants.TIFFTAG_JPEGIFOFFSET);
                int jpegLength = (int)s.Length - jpegOffset;

                if (dir.IsTagPresent(TIFFConstants.TIFFTAG_JPEGIFBYTECOUNT))
                {
                    jpegLength = (int)dir.GetFieldAsLong(TIFFConstants.TIFFTAG_JPEGIFBYTECOUNT) +
                                 (int)size[0];
                }

                byte[] jpeg = new byte[Math.Min(jpegLength, s.Length - jpegOffset)];

                int posFilePointer = (int)s.FilePointer;
                posFilePointer += jpegOffset;
                s.Seek(posFilePointer);
                s.ReadFully(jpeg);
                // if quantization and/or Huffman tables are stored separately in the tiff,
                // we need to add them to the jpeg data
                TIFFField jpegtables = dir.GetField(TIFFConstants.TIFFTAG_JPEGTABLES);
                if (jpegtables != null)
                {
                    byte[] temp        = jpegtables.GetAsBytes();
                    int    tableoffset = 0;
                    int    tablelength = temp.Length;
                    // remove FFD8 from start
                    if (temp[0] == (byte)0xFF && temp[1] == (byte)0xD8)
                    {
                        tableoffset  = 2;
                        tablelength -= 2;
                    }
                    // remove FFD9 from end
                    if (temp[temp.Length - 2] == (byte)0xFF && temp[temp.Length - 1] == (byte)0xD9)
                    {
                        tablelength -= 2;
                    }
                    byte[] tables = new byte[tablelength];
                    Array.Copy(temp, tableoffset, tables, 0, tablelength);
                    // TODO insert after JFIF header, instead of at the start
                    byte[] jpegwithtables = new byte[jpeg.Length + tables.Length];
                    Array.Copy(jpeg, 0, jpegwithtables, 0, 2);
                    Array.Copy(tables, 0, jpegwithtables, 2, tables.Length);
                    Array.Copy(jpeg, 2, jpegwithtables, tables.Length + 2, jpeg.Length - 2);
                    jpeg = jpegwithtables;
                }
                img = new Jpeg(jpeg);
            }
            else if (compression == TIFFConstants.COMPRESSION_JPEG)
            {
                if (size.Length > 1)
                {
                    throw new IOException(MessageLocalization.GetComposedMessage("compression.jpeg.is.only.supported.with.a.single.strip.this.image.has.1.strips", size.Length));
                }
                byte[] jpeg = new byte[(int)size[0]];
                s.Seek(offset[0]);
                s.ReadFully(jpeg);
                img = new Jpeg(jpeg);
                if (photometric == TIFFConstants.PHOTOMETRIC_RGB)
                {
                    img.ColorTransform = 0;
                }
            }
            else
            {
                for (int k = 0; k < offset.Length; ++k)
                {
                    byte[] im = new byte[(int)size[k]];
                    s.Seek(offset[k]);
                    s.ReadFully(im);
                    int    height = Math.Min(rowsStrip, rowsLeft);
                    byte[] outBuf = null;
                    if (compression != TIFFConstants.COMPRESSION_NONE)
                    {
                        outBuf = new byte[(w * bitsPerSample * samplePerPixel + 7) / 8 * height];
                    }
                    if (reverse)
                    {
                        TIFFFaxDecoder.ReverseBits(im);
                    }
                    switch (compression)
                    {
                    case TIFFConstants.COMPRESSION_DEFLATE:
                    case TIFFConstants.COMPRESSION_ADOBE_DEFLATE:
                        Inflate(im, outBuf);
                        ApplyPredictor(outBuf, predictor, w, height, samplePerPixel);
                        break;

                    case TIFFConstants.COMPRESSION_NONE:
                        outBuf = im;
                        break;

                    case TIFFConstants.COMPRESSION_PACKBITS:
                        DecodePackbits(im, outBuf);
                        break;

                    case TIFFConstants.COMPRESSION_LZW:
                        lzwDecoder.Decode(im, outBuf, height);
                        break;
                    }
                    if (bitsPerSample == 1 && samplePerPixel == 1 && photometric != TIFFConstants.PHOTOMETRIC_PALETTE)
                    {
                        g4.Fax4Encode(outBuf, height);
                    }
                    else
                    {
                        if (extraSamples > 0)
                        {
                            ProcessExtraSamples(zip, mzip, outBuf, samplePerPixel, bitsPerSample, w, height);
                        }
                        else
                        {
                            zip.Write(outBuf, 0, outBuf.Length);
                        }
                    }
                    rowsLeft -= rowsStrip;
                }
                if (bitsPerSample == 1 && samplePerPixel == 1 && photometric != TIFFConstants.PHOTOMETRIC_PALETTE)
                {
                    img = Image.GetInstance(w, h, false, Image.CCITTG4,
                                            photometric == TIFFConstants.PHOTOMETRIC_MINISBLACK ? Image.CCITT_BLACKIS1 : 0, g4.Close());
                }
                else
                {
                    zip.Close();
                    img          = new ImgRaw(w, h, samplePerPixel - extraSamples, bitsPerSample, stream.ToArray());
                    img.Deflated = true;
                }
            }
            img.SetDpi(dpiX, dpiY);
            if (compression != TIFFConstants.COMPRESSION_OJPEG && compression != TIFFConstants.COMPRESSION_JPEG)
            {
                if (dir.IsTagPresent(TIFFConstants.TIFFTAG_ICCPROFILE))
                {
                    try {
                        TIFFField   fd       = dir.GetField(TIFFConstants.TIFFTAG_ICCPROFILE);
                        ICC_Profile icc_prof = ICC_Profile.GetInstance(fd.GetAsBytes());
                        if (samplePerPixel - extraSamples == icc_prof.NumComponents)
                        {
                            img.TagICC = icc_prof;
                        }
                    }
                    catch {
                        //empty
                    }
                }
                if (dir.IsTagPresent(TIFFConstants.TIFFTAG_COLORMAP))
                {
                    TIFFField fd      = dir.GetField(TIFFConstants.TIFFTAG_COLORMAP);
                    char[]    rgb     = fd.GetAsChars();
                    byte[]    palette = new byte[rgb.Length];
                    int       gColor  = rgb.Length / 3;
                    int       bColor  = gColor * 2;
                    for (int k = 0; k < gColor; ++k)
                    {
                        palette[k * 3]     = (byte)(rgb[k] >> 8);
                        palette[k * 3 + 1] = (byte)(rgb[k + gColor] >> 8);
                        palette[k * 3 + 2] = (byte)(rgb[k + bColor] >> 8);
                    }
                    // Colormap components are supposed to go from 0 to 655535 but,
                    // as usually, some tiff producers just put values from 0 to 255.
                    // Let's check for these broken tiffs.
                    bool colormapBroken = true;
                    for (int k = 0; k < palette.Length; ++k)
                    {
                        if (palette[k] != 0)
                        {
                            colormapBroken = false;
                            break;
                        }
                    }
                    if (colormapBroken)
                    {
                        for (int k = 0; k < gColor; ++k)
                        {
                            palette[k * 3]     = (byte)rgb[k];
                            palette[k * 3 + 1] = (byte)rgb[k + gColor];
                            palette[k * 3 + 2] = (byte)rgb[k + bColor];
                        }
                    }
                    PdfArray indexed = new PdfArray();
                    indexed.Add(PdfName.INDEXED);
                    indexed.Add(PdfName.DEVICERGB);
                    indexed.Add(new PdfNumber(gColor - 1));
                    indexed.Add(new PdfString(palette));
                    PdfDictionary additional = new PdfDictionary();
                    additional.Put(PdfName.COLORSPACE, indexed);
                    img.Additional = additional;
                }
                img.OriginalType = Image.ORIGINAL_TIFF;
            }
            if (photometric == TIFFConstants.PHOTOMETRIC_MINISWHITE)
            {
                img.Inverted = true;
            }
            if (rotation != 0)
            {
                img.InitialRotation = rotation;
            }
            if (extraSamples > 0)
            {
                mzip.Close();
                Image mimg = Image.GetInstance(w, h, 1, bitsPerSample, mstream.ToArray());
                mimg.MakeMask();
                mimg.Deflated = true;
                img.ImageMask = mimg;
            }
            return(img);
        }
コード例 #10
0
        private void OutputDss(PdfDictionary dss, PdfDictionary vrim, PdfArray ocsps, PdfArray crls, PdfArray certs
                               )
        {
            PdfCatalog catalog = document.GetCatalog();

            if (document.GetPdfVersion().CompareTo(PdfVersion.PDF_2_0) < 0)
            {
                catalog.AddDeveloperExtension(PdfDeveloperExtension.ESIC_1_7_EXTENSIONLEVEL5);
            }
            foreach (PdfName vkey in validated.Keys)
            {
                PdfArray      ocsp = new PdfArray();
                PdfArray      crl  = new PdfArray();
                PdfArray      cert = new PdfArray();
                PdfDictionary vri  = new PdfDictionary();
                foreach (byte[] b in validated.Get(vkey).crls)
                {
                    PdfStream ps = new PdfStream(b);
                    ps.SetCompressionLevel(CompressionConstants.DEFAULT_COMPRESSION);
                    ps.MakeIndirect(document);
                    crl.Add(ps);
                    crls.Add(ps);
                    crls.SetModified();
                }
                foreach (byte[] b in validated.Get(vkey).ocsps)
                {
                    PdfStream ps = new PdfStream(b);
                    ps.SetCompressionLevel(CompressionConstants.DEFAULT_COMPRESSION);
                    ocsp.Add(ps);
                    ocsps.Add(ps);
                    ocsps.SetModified();
                }
                foreach (byte[] b in validated.Get(vkey).certs)
                {
                    PdfStream ps = new PdfStream(b);
                    ps.SetCompressionLevel(CompressionConstants.DEFAULT_COMPRESSION);
                    ps.MakeIndirect(document);
                    cert.Add(ps);
                    certs.Add(ps);
                    certs.SetModified();
                }
                if (ocsp.Size() > 0)
                {
                    ocsp.MakeIndirect(document);
                    vri.Put(PdfName.OCSP, ocsp);
                }
                if (crl.Size() > 0)
                {
                    crl.MakeIndirect(document);
                    vri.Put(PdfName.CRL, crl);
                }
                if (cert.Size() > 0)
                {
                    cert.MakeIndirect(document);
                    vri.Put(PdfName.Cert, cert);
                }
                vri.MakeIndirect(document);
                vrim.Put(vkey, vri);
            }
            vrim.MakeIndirect(document);
            vrim.SetModified();
            dss.Put(PdfName.VRI, vrim);
            if (ocsps.Size() > 0)
            {
                ocsps.MakeIndirect(document);
                dss.Put(PdfName.OCSPs, ocsps);
            }
            if (crls.Size() > 0)
            {
                crls.MakeIndirect(document);
                dss.Put(PdfName.CRLs, crls);
            }
            if (certs.Size() > 0)
            {
                certs.MakeIndirect(document);
                dss.Put(PdfName.Certs, certs);
            }
            dss.MakeIndirect(document);
            dss.SetModified();
            catalog.Put(PdfName.DSS, dss);
        }
コード例 #11
0
 /**
  * Adds a RichMediaInstance to the instances array of this
  * configuration.
  * @param	instance	a RichMediaInstance
  */
 public void AddInstance(RichMediaInstance instance)
 {
     instances.Add(instance);
 }
コード例 #12
0
 private static void ApplyBorderAttributes(AbstractRenderer renderer, PdfDictionary attributes) {
     bool specificBorderProperties = renderer.GetProperty<Border>(Property.BORDER_TOP) != null || renderer.GetProperty
         <Border>(Property.BORDER_RIGHT) != null || renderer.GetProperty<Border>(Property.BORDER_BOTTOM) != null
          || renderer.GetProperty<Border>(Property.BORDER_LEFT) != null;
     bool generalBorderProperties = !specificBorderProperties && renderer.GetProperty<Object>(Property.BORDER) 
         != null;
     if (generalBorderProperties) {
         Border generalBorder = renderer.GetProperty<Border>(Property.BORDER);
         Color generalBorderColor = generalBorder.GetColor();
         int borderType = generalBorder.GetBorderType();
         float borderWidth = generalBorder.GetWidth();
         if (generalBorderColor is DeviceRgb) {
             attributes.Put(PdfName.BorderColor, new PdfArray(generalBorderColor.GetColorValue()));
             attributes.Put(PdfName.BorderStyle, TransformBorderTypeToName(borderType));
             attributes.Put(PdfName.BorderThikness, new PdfNumber(borderWidth));
         }
     }
     if (specificBorderProperties) {
         PdfArray borderColors = new PdfArray();
         PdfArray borderTypes = new PdfArray();
         PdfArray borderWidths = new PdfArray();
         bool atLeastOneRgb = false;
         Border[] borders = renderer.GetBorders();
         bool allColorsEqual = true;
         bool allTypesEqual = true;
         bool allWidthsEqual = true;
         for (int i = 1; i < borders.Length; i++) {
             Border border = borders[i];
             if (border != null) {
                 if (!border.GetColor().Equals(borders[0].GetColor())) {
                     allColorsEqual = false;
                 }
                 if (border.GetWidth() != borders[0].GetWidth()) {
                     allWidthsEqual = false;
                 }
                 if (border.GetBorderType() != borders[0].GetBorderType()) {
                     allTypesEqual = false;
                 }
             }
         }
         int[] borderOrder = new int[] { 0, 1, 2, 3 };
         //TODO set depending on writing direction
         foreach (int i_1 in borderOrder) {
             if (borders[i_1] != null) {
                 if (borders[i_1].GetColor() is DeviceRgb) {
                     borderColors.Add(new PdfArray(borders[i_1].GetColor().GetColorValue()));
                     atLeastOneRgb = true;
                 }
                 else {
                     borderColors.Add(PdfNull.PDF_NULL);
                 }
                 borderTypes.Add(TransformBorderTypeToName(borders[i_1].GetBorderType()));
                 borderWidths.Add(new PdfNumber(borders[i_1].GetWidth()));
             }
             else {
                 borderColors.Add(PdfNull.PDF_NULL);
                 borderTypes.Add(PdfName.None);
                 borderWidths.Add(PdfNull.PDF_NULL);
             }
         }
         if (atLeastOneRgb) {
             if (allColorsEqual) {
                 attributes.Put(PdfName.BorderColor, borderColors.Get(0));
             }
             else {
                 attributes.Put(PdfName.BorderColor, borderColors);
             }
         }
         if (allTypesEqual) {
             attributes.Put(PdfName.BorderStyle, borderTypes.Get(0));
         }
         else {
             attributes.Put(PdfName.BorderStyle, borderTypes);
         }
         if (allWidthsEqual) {
             attributes.Put(PdfName.BorderThikness, borderWidths.Get(0));
         }
         else {
             attributes.Put(PdfName.BorderThikness, borderWidths);
         }
     }
 }
コード例 #13
0
 /**
  * Transforms value abbreviations into their corresponding real value 
  * @param key the key that the value is for
  * @param value the value that might be an abbreviation
  * @return if value is an allowed abbreviation for the key, the expanded value for that abbreviation.  Otherwise, value is returned without modification 
  */
 private static PdfObject GetAlternateValue(PdfName key, PdfObject value){
     if (key == PdfName.FILTER){
         if (value is PdfName){
             PdfName altValue;
             inlineImageFilterAbbreviationMap.TryGetValue((PdfName)value, out altValue);
             if (altValue != null)
                 return altValue;
         } else if (value is PdfArray){
             PdfArray array = ((PdfArray)value);
             PdfArray altArray = new PdfArray();
             int count = array.Size;
             for (int i = 0; i < count; i++){
                 altArray.Add(GetAlternateValue(key, array[i]));
             }
             return altArray;
         }
     } else if (key == PdfName.COLORSPACE){
         if (value is PdfName){
             PdfName altValue;
             inlineImageColorSpaceAbbreviationMap.TryGetValue((PdfName)value, out altValue);
             if (altValue != null)
                 return altValue;
         }
     }
     
     return value;
 }
コード例 #14
0
        protected internal static PdfStream CreatePdfStream(ImageData image, iText.Kernel.Pdf.Xobject.PdfImageXObject
                                                            imageMask)
        {
            PdfStream stream;

            if (image.GetOriginalType() == ImageType.RAW)
            {
                RawImageHelper.UpdateImageAttributes((RawImageData)image, null);
            }
            stream = new PdfStream(image.GetData());
            String filter = image.GetFilter();

            if (filter != null && filter.Equals("JPXDecode") && image.GetColorSpace() <= 0)
            {
                stream.SetCompressionLevel(CompressionConstants.NO_COMPRESSION);
                image.SetBpc(0);
            }
            stream.Put(PdfName.Type, PdfName.XObject);
            stream.Put(PdfName.Subtype, PdfName.Image);
            PdfDictionary decodeParms = CreateDictionaryFromMap(stream, image.GetDecodeParms());

            if (decodeParms != null)
            {
                stream.Put(PdfName.DecodeParms, decodeParms);
            }
            PdfName colorSpace;

            switch (image.GetColorSpace())
            {
            case 1: {
                colorSpace = PdfName.DeviceGray;
                break;
            }

            case 3: {
                colorSpace = PdfName.DeviceRGB;
                break;
            }

            default: {
                colorSpace = PdfName.DeviceCMYK;
                break;
            }
            }
            stream.Put(PdfName.ColorSpace, colorSpace);
            if (image.GetBpc() != 0)
            {
                stream.Put(PdfName.BitsPerComponent, new PdfNumber(image.GetBpc()));
            }
            if (image.GetFilter() != null)
            {
                stream.Put(PdfName.Filter, new PdfName(image.GetFilter()));
            }
            //TODO: return to this later
            //        if (image.getLayer() != null)
            //            put(PdfName.OC, image.getLayer().getRef());
            if (image.GetColorSpace() == -1)
            {
                stream.Remove(PdfName.ColorSpace);
            }
            PdfDictionary additional = CreateDictionaryFromMap(stream, image.GetImageAttributes());

            if (additional != null)
            {
                stream.PutAll(additional);
            }
            if (image.IsMask() && (image.GetBpc() == 1 || image.GetBpc() > 0xff))
            {
                stream.Put(PdfName.ImageMask, PdfBoolean.TRUE);
            }
            if (imageMask != null)
            {
                if (imageMask.softMask)
                {
                    stream.Put(PdfName.SMask, imageMask.GetPdfObject());
                }
                else
                {
                    if (imageMask.mask)
                    {
                        stream.Put(PdfName.Mask, imageMask.GetPdfObject());
                    }
                }
            }
            ImageData mask = image.GetImageMask();

            if (mask != null)
            {
                if (mask.IsSoftMask())
                {
                    stream.Put(PdfName.SMask, new iText.Kernel.Pdf.Xobject.PdfImageXObject(image.GetImageMask()).GetPdfObject(
                                   ));
                }
                else
                {
                    if (mask.IsMask())
                    {
                        stream.Put(PdfName.Mask, new iText.Kernel.Pdf.Xobject.PdfImageXObject(image.GetImageMask()).GetPdfObject()
                                   );
                    }
                }
            }
            if (image.GetDecode() != null)
            {
                stream.Put(PdfName.Decode, new PdfArray(image.GetDecode()));
            }
            if (image.IsMask() && image.IsInverted())
            {
                stream.Put(PdfName.Decode, new PdfArray(new float[] { 1, 0 }));
            }
            if (image.IsInterpolation())
            {
                stream.Put(PdfName.Interpolate, PdfBoolean.TRUE);
            }
            // deal with transparency
            int[] transparency = image.GetTransparency();
            if (transparency != null && !image.IsMask() && imageMask == null)
            {
                PdfArray t = new PdfArray();
                foreach (int transparencyItem in transparency)
                {
                    t.Add(new PdfNumber(transparencyItem));
                }
                stream.Put(PdfName.Mask, t);
            }
            stream.Put(PdfName.Width, new PdfNumber(image.GetWidth()));
            stream.Put(PdfName.Height, new PdfNumber(image.GetHeight()));
            return(stream);
        }
コード例 #15
0
ファイル: XRefStream.cs プロジェクト: systembugtj/bookasa
        /**
         * <summary>Serializes the xref stream entries into the stream body.</summary>
         */
        private void Flush(
            IOutputStream stream
            )
        {
            // 1. Body.
            PdfArray indexArray = new PdfArray();

            int[] entryFieldSizes = new int[]
            {
                EntryField0Size,
                GetFieldSize((int)stream.Length), // NOTE: We assume this xref stream is the last indirect object.
                EntryField2Size
            };
            {
                // Get the stream buffer!
                IBuffer body = Body;

                // Delete the old entries!
                body.SetLength(0);

                // Serializing the entries into the stream buffer...
                int prevObjectNumber = -2; // Previous-entry object number.
                foreach (XRefEntry entry in entries.Values)
                {
                    int entryNumber = entry.Number;
                    if (entryNumber - prevObjectNumber != 1) // Current subsection terminated.
                    {
                        if (indexArray.Count > 0)
                        {
                            indexArray.Add(new PdfInteger(prevObjectNumber - ((PdfInteger)indexArray[indexArray.Count - 1]).IntValue + 1));
                        }                                            // Number of entries in the previous subsection.
                        indexArray.Add(new PdfInteger(entryNumber)); // First object number in the next subsection.
                    }
                    prevObjectNumber = entryNumber;

                    switch (entry.Usage)
                    {
                    case XRefEntry.UsageEnum.Free:
                        body.Append((byte)FreeEntryType);
                        body.Append(NumberToByteArray(entry.Offset, entryFieldSizes[1]));
                        body.Append(NumberToByteArray(entry.Generation, entryFieldSizes[2]));
                        break;

                    case XRefEntry.UsageEnum.InUse:
                        body.Append((byte)InUseEntryType);
                        body.Append(NumberToByteArray(entry.Offset, entryFieldSizes[1]));
                        body.Append(NumberToByteArray(entry.Generation, entryFieldSizes[2]));
                        break;

                    case XRefEntry.UsageEnum.InUseCompressed:
                        body.Append((byte)InUseCompressedEntryType);
                        body.Append(NumberToByteArray(entry.StreamNumber, entryFieldSizes[1]));
                        body.Append(NumberToByteArray(entry.Offset, entryFieldSizes[2]));
                        break;

                    default:
                        throw new NotSupportedException();
                    }
                }
                indexArray.Add(new PdfInteger(prevObjectNumber - ((PdfInteger)indexArray[indexArray.Count - 1]).IntValue + 1)); // Number of entries in the previous subsection.
            }

            // 2. Header.
            {
                PdfDictionary header = Header;
                header[PdfName.Index] = indexArray;
                header[PdfName.Size]  = new PdfInteger(file.IndirectObjects.Count + 1);
                header[PdfName.W]     = new PdfArray(
                    new PdfInteger(entryFieldSizes[0]),
                    new PdfInteger(entryFieldSizes[1]),
                    new PdfInteger(entryFieldSizes[2])
                    );
            }
        }
コード例 #16
0
        /**
         * <summary>Parses the current PDF object [PDF:1.6:3.2].</summary>
         */
        public PdfDataObject ParsePdfObject(
            )
        {
            /*
             * NOTE: Object parsing is intrinsically a sequential operation tied to the stream pointer.
             * Calls bound towards other classes are potentially disruptive for the predictability of
             * the position of the stream pointer, so we are forced to carefully keep track of our
             * current position in order to recover its proper state after any outbound call.
             */
            do
            {
                // Which token type?
                switch (tokenType)
                {
                case TokenTypeEnum.Integer:
                    return(new PdfInteger((int)token));

                case TokenTypeEnum.Name:
                    return(new PdfName((string)token, true));

                case TokenTypeEnum.Reference:
                    /*
                     * NOTE: Curiously, PDF references are the only primitive objects that require
                     * a file reference. That's because they deal with indirect objects, which are strongly
                     * coupled with the current state of the file: so, PDF references are the fundamental
                     * bridge between the token layer and the file layer.
                     */
                    return(new PdfReference(
                               (Reference)token,
                               file
                               ));

                case TokenTypeEnum.Literal:
                    return(new PdfTextString(
                               Encoding.Encode((string)token)
                               ));

                case TokenTypeEnum.DictionaryBegin:
                    PdfDictionary dictionary = new PdfDictionary();
                    while (true)
                    {
                        // Key.
                        MoveNext(); if (tokenType == TokenTypeEnum.DictionaryEnd)
                        {
                            break;
                        }
                        PdfName key = (PdfName)ParsePdfObject();
                        // Value.
                        MoveNext();
                        PdfDirectObject value = (PdfDirectObject)ParsePdfObject();
                        // Add the current entry to the dictionary!
                        dictionary[key] = value;
                    }

                    int oldOffset = (int)stream.Position;
                    MoveNext();
                    // Is this dictionary the header of a stream object [PDF:1.6:3.2.7]?
                    if ((tokenType == TokenTypeEnum.Keyword) &&
                        token.Equals(Keyword.BeginStream))
                    {
                        // Keep track of current position!
                        long position = stream.Position;

                        // Get the stream length!

                        /*
                         * NOTE: Indirect reference resolution is an outbound call (stream pointer hazard!),
                         * so we need to recover our current position after it returns.
                         */
                        int length = ((PdfInteger)files.File.Resolve(dictionary[PdfName.Length])).RawValue;

                        // Move to the stream data beginning!
                        stream.Seek(position); SkipEOL();

                        // Copy the stream data to the instance!
                        byte[] data = new byte[length];
                        stream.Read(data);

                        MoveNext(); // Postcondition (last token should be 'endstream' keyword).

                        Object streamType = dictionary[PdfName.Type];
                        if (PdfName.ObjStm.Equals(streamType)) // Object stream [PDF:1.6:3.4.6].
                        {
                            return(new ObjectStream(
                                       dictionary,
                                       new bytes.Buffer(data),
                                       file
                                       ));
                        }
                        else if (PdfName.XRef.Equals(streamType)) // Cross-reference stream [PDF:1.6:3.4.7].
                        {
                            return(new XRefStream(
                                       dictionary,
                                       new bytes.Buffer(data),
                                       file
                                       ));
                        }
                        else // Generic stream.
                        {
                            return(new PdfStream(
                                       dictionary,
                                       new bytes.Buffer(data)
                                       ));
                        }
                    }
                    else // Stand-alone dictionary.
                    {
                        stream.Seek(oldOffset); // Restores postcondition (last token should be the dictionary end).

                        return(dictionary);
                    }

                case TokenTypeEnum.ArrayBegin:
                    PdfArray array = new PdfArray();
                    while (true)
                    {
                        // Value.
                        MoveNext(); if (tokenType == TokenTypeEnum.ArrayEnd)
                        {
                            break;
                        }
                        // Add the current item to the array!
                        array.Add((PdfDirectObject)ParsePdfObject());
                    }
                    return(array);

                case TokenTypeEnum.Real:
                    return(new PdfReal((float)token));

                case TokenTypeEnum.Boolean:
                    return(PdfBoolean.Get((bool)token));

                case TokenTypeEnum.Date:
                    return(new PdfDate((DateTime)token));

                case TokenTypeEnum.Hex:
                    return(new PdfTextString(
                               (string)token,
                               PdfString.SerializationModeEnum.Hex
                               ));

                case TokenTypeEnum.Null:
                    return(null);

                case TokenTypeEnum.Comment:
                    // NOOP: Comments are simply ignored and skipped.
                    break;

                default:
                    throw new Exception("Unknown type: " + tokenType);
                }
            } while(MoveNext());
            return(null);
        }
コード例 #17
0
ファイル: BaseParser.cs プロジェクト: alexandrvslv/pdf-clown
        /**
         * <summary>Parses the current PDF object [PDF:1.6:3.2].</summary>
         */
        public virtual PdfDataObject ParsePdfObject()
        {
            switch (TokenType)
            {
            case TokenTypeEnum.Integer:
                return(PdfInteger.Get((int)Token));

            case TokenTypeEnum.Name:
                return(new PdfName((string)Token, true));

            case TokenTypeEnum.DictionaryBegin:
            {
                PdfDictionary dictionary = new PdfDictionary();
                dictionary.Updateable = false;
                while (true)
                {
                    // Key.
                    MoveNext(); if (TokenType == TokenTypeEnum.DictionaryEnd)
                    {
                        break;
                    }
                    PdfName key = (PdfName)ParsePdfObject();
                    // Value.
                    MoveNext();
                    PdfDirectObject value = (PdfDirectObject)ParsePdfObject();
                    // Add the current entry to the dictionary!
                    if (dictionary.ContainsKey(key))
                    {
                        key = new PdfName(key.StringValue + "Dublicat");
                    }
                    dictionary[key] = value;
                }
                dictionary.Updateable = true;
                return(dictionary);
            }

            case TokenTypeEnum.ArrayBegin:
            {
                PdfArray array = new PdfArray();
                array.Updateable = false;
                while (true)
                {
                    // Value.
                    MoveNext(); if (TokenType == TokenTypeEnum.ArrayEnd)
                    {
                        break;
                    }
                    // Add the current item to the array!
                    array.Add((PdfDirectObject)ParsePdfObject());
                }
                array.Updateable = true;
                return(array);
            }

            case TokenTypeEnum.Literal:
                if (Token is DateTime)
                {
                    return(PdfDate.Get((DateTime)Token));
                }
                else
                {
                    return(new PdfTextString(Token == null ? null : Encoding.Pdf.Encode((string)Token)));
                }

            case TokenTypeEnum.Hex:
                return(new PdfTextString((string)Token, PdfString.SerializationModeEnum.Hex));

            case TokenTypeEnum.Real:
                return(PdfReal.Get((double)Token));

            case TokenTypeEnum.Boolean:
                return(PdfBoolean.Get((bool)Token));

            case TokenTypeEnum.Null:
                return(null);

            default:
                throw new PostScriptParseException(String.Format("Unknown type beginning: '{0}'", Token), this);
            }
        }
コード例 #18
0
ファイル: FunctionalTests.cs プロジェクト: salslab/LittlePdf
        public async Task WriterTest()
        {
            var documentCatalogDict = new PdfDictionary();
            var documentCatalog     = new PdfIndirectObject(documentCatalogDict);

            var infoDict = new PdfDictionary();
            var info     = new PdfIndirectObject(infoDict);

            var pageTreeDict   = new PdfDictionary();
            var pageTree       = new PdfIndirectObject(pageTreeDict);
            var pageReferences = new PdfArray();

            documentCatalogDict.Add("Type", new PdfName("Catalog"));
            documentCatalogDict.Add("Pages", new PdfIndirectObjectReference(pageTree));

            infoDict.Add("Producer", "LittlePdf");
            infoDict.Add("CreationDate", new PdfDate(DateTime.UtcNow));
            infoDict.Add("ModDate", new PdfDate(DateTime.UtcNow));
            infoDict.Add("Title", new PdfString("Test Pdf"));
            infoDict.Add("Author", new PdfString("Salil Ponde"));

            pageTreeDict.Add("Type", new PdfName("Pages"));
            pageTreeDict.Add("Kids", pageReferences);
            pageTreeDict.Add("Count", new PdfInteger(0));
            pageTreeDict.Add("MediaBox", new PdfArray(new List <PdfObject> {
                new PdfReal(0), new PdfReal(0), new PdfReal(595), new PdfReal(842)
            }));

            var font1Dict = new PdfDictionary();
            var font1     = new PdfIndirectObject(font1Dict);

            font1Dict.Add("Type", new PdfName("Font"));
            font1Dict.Add("Subtype", new PdfName("Type1"));
            font1Dict.Add("BaseFont", new PdfName("Helvetica-Oblique"));
            font1Dict.Add("Encoding", new PdfName("WinAnsiEncoding"));

            var fontsDict     = new PdfDictionary();
            var resourcesDict = new PdfDictionary();

            resourcesDict.Add("Font", fontsDict);
            fontsDict.Add("F1", new PdfIndirectObjectReference(font1));
            pageTreeDict.Add("Resources", resourcesDict);

            var pageDict = new PdfDictionary();
            var page     = new PdfIndirectObject(pageDict);

            pageReferences.Add(new PdfIndirectObjectReference(page));
            pageDict.Add("Type", new PdfName("Page"));
            pageDict.Add("Parent", new PdfIndirectObjectReference(pageTree));
            //var c = Encoding.ASCII.GetBytes("0.9 0.5 0.0 rg q 10 10 m 500 10 l 5 w [3] 0 d S Q 500 10 m 500 500 l S ");
            var c = Encoding.ASCII.GetBytes("BT /F1 24 Tf 100 742 Td (Hey, this is amazing!) Tj ET ");
            var pageContentStream = new PdfStream(c);
            var pageContent       = new PdfIndirectObject(pageContentStream);

            pageDict.Add("Contents", new PdfIndirectObjectReference(pageContent));

            var page2Dict = new PdfDictionary();
            var page2     = new PdfIndirectObject(page2Dict);

            pageReferences.Add(new PdfIndirectObjectReference(page2));
            page2Dict.Add("Type", new PdfName("Page"));
            page2Dict.Add("Parent", new PdfIndirectObjectReference(pageTree));
            page2Dict.Add("MediaBox", new PdfArray(new List <PdfObject> {
                new PdfReal(0), new PdfReal(0), new PdfReal(842), new PdfReal(595)
            }));

            // Write
            var fileName = @"c:\temp\ddd.pdf";

            File.Delete(fileName);
            var stream = File.Create(fileName);

            var writer = new PdfWriter(stream);
            await writer.WriteAsync(documentCatalog);

            await writer.WriteAsync(info);

            await writer.WriteAsync(pageTree);

            await writer.WriteAsync(font1);

            await writer.WriteAsync(page);

            await writer.WriteAsync(pageContent);

            await writer.WriteAsync(page2);

            await writer.CloseAsync(documentCatalog, info);
        }
コード例 #19
0
// ---------------------------------------------------------------------------
        public void Write(Stream stream)
        {
            // step 1
            using (Document document = new Document()) {
                // step 2
                PdfWriter writer = PdfWriter.GetInstance(document, stream);
                writer.SetTagged();
                writer.UserProperties = true;
                // step 3
                document.Open();
                // step 4
                PdfStructureTreeRoot tree = writer.StructureTreeRoot;
                PdfStructureElement  top  = new PdfStructureElement(
                    tree, new PdfName("Directors")
                    );

                Dictionary <int, PdfStructureElement> directors =
                    new Dictionary <int, PdfStructureElement>();

                int                 id;
                Director            director;
                PdfStructureElement e;
                DbProviderFactory   dbp = AdoDB.Provider;
                using (var c = dbp.CreateConnection()) {
                    c.ConnectionString = AdoDB.CS;
                    using (DbCommand cmd = c.CreateCommand()) {
                        cmd.CommandText = SELECTDIRECTORS;
                        c.Open();
                        using (var r = cmd.ExecuteReader()) {
                            while (r.Read())
                            {
                                id       = Convert.ToInt32(r["id"]);
                                director = PojoFactory.GetDirector(r);
                                e        = new PdfStructureElement(top, new PdfName("director" + id));
                                PdfDictionary userproperties = new PdfDictionary();
                                userproperties.Put(PdfName.O, PdfName.USERPROPERTIES);
                                PdfArray      properties = new PdfArray();
                                PdfDictionary property1  = new PdfDictionary();
                                property1.Put(PdfName.N, new PdfString("Name"));
                                property1.Put(PdfName.V, new PdfString(director.Name));
                                properties.Add(property1);
                                PdfDictionary property2 = new PdfDictionary();
                                property2.Put(PdfName.N, new PdfString("Given name"));
                                property2.Put(PdfName.V, new PdfString(director.GivenName));
                                properties.Add(property2);
                                PdfDictionary property3 = new PdfDictionary();
                                property3.Put(PdfName.N, new PdfString("Posters"));
                                property3.Put(PdfName.V, new PdfNumber(Convert.ToInt32(r["c"])));
                                properties.Add(property3);
                                userproperties.Put(PdfName.P, properties);
                                e.Put(PdfName.A, userproperties);
                                directors.Add(id, e);
                            }
                        }
                    }
                }

                Dictionary <Movie, int> map = new Dictionary <Movie, int>();
                for (int i = 1; i < 8; i++)
                {
                    foreach (Movie movie in PojoFactory.GetMovies(i))
                    {
                        map.Add(movie, i);
                    }
                }

                PdfContentByte canvas = writer.DirectContent;
                Image          img;
                float          x        = 11.5f;
                float          y        = 769.7f;
                string         RESOURCE = Utility.ResourcePosters;
                foreach (var entry in map.Keys)
                {
                    img = Image.GetInstance(Path.Combine(RESOURCE, entry.Imdb + ".jpg"));
                    img.ScaleToFit(1000, 60);
                    img.SetAbsolutePosition(x + (45 - img.ScaledWidth) / 2, y);
                    canvas.BeginMarkedContentSequence(directors[map[entry]]);
                    canvas.AddImage(img);
                    canvas.EndMarkedContentSequence();
                    x += 48;
                    if (x > 578)
                    {
                        x  = 11.5f;
                        y -= 84.2f;
                    }
                }
            }
        }
コード例 #20
0
ファイル: TiffImage.cs プロジェクト: pixelia-es/RazorPDF2
        protected static Image GetTiffImageColor(TIFFDirectory dir, RandomAccessFileOrArray s)
        {
            int predictor = 1;
            TIFFLZWDecoder lzwDecoder = null;
            int compression = (int)dir.GetFieldAsLong(TIFFConstants.TIFFTAG_COMPRESSION);
            switch (compression) {
                case TIFFConstants.COMPRESSION_NONE:
                case TIFFConstants.COMPRESSION_LZW:
                case TIFFConstants.COMPRESSION_PACKBITS:
                case TIFFConstants.COMPRESSION_DEFLATE:
                case TIFFConstants.COMPRESSION_ADOBE_DEFLATE:
                case TIFFConstants.COMPRESSION_OJPEG:
                case TIFFConstants.COMPRESSION_JPEG:
                    break;
                default:
                    throw new ArgumentException("The compression " + compression + " is not supported.");
            }
            int photometric = (int)dir.GetFieldAsLong(TIFFConstants.TIFFTAG_PHOTOMETRIC);
            switch (photometric) {
                case TIFFConstants.PHOTOMETRIC_MINISWHITE:
                case TIFFConstants.PHOTOMETRIC_MINISBLACK:
                case TIFFConstants.PHOTOMETRIC_RGB:
                case TIFFConstants.PHOTOMETRIC_SEPARATED:
                case TIFFConstants.PHOTOMETRIC_PALETTE:
                    break;
                default:
                    if (compression != TIFFConstants.COMPRESSION_OJPEG && compression != TIFFConstants.COMPRESSION_JPEG)
                        throw new ArgumentException("The photometric " + photometric + " is not supported.");
                    break;
            }
            float rotation = 0;
            if (dir.IsTagPresent(TIFFConstants.TIFFTAG_ORIENTATION)) {
                int rot = (int)dir.GetFieldAsLong(TIFFConstants.TIFFTAG_ORIENTATION);
                if (rot == TIFFConstants.ORIENTATION_BOTRIGHT || rot == TIFFConstants.ORIENTATION_BOTLEFT)
                    rotation = (float)Math.PI;
                else if (rot == TIFFConstants.ORIENTATION_LEFTTOP || rot == TIFFConstants.ORIENTATION_LEFTBOT)
                    rotation = (float)(Math.PI / 2.0);
                else if (rot == TIFFConstants.ORIENTATION_RIGHTTOP || rot == TIFFConstants.ORIENTATION_RIGHTBOT)
                    rotation = -(float)(Math.PI / 2.0);
            }

            if (dir.IsTagPresent(TIFFConstants.TIFFTAG_PLANARCONFIG)
                && dir.GetFieldAsLong(TIFFConstants.TIFFTAG_PLANARCONFIG) == TIFFConstants.PLANARCONFIG_SEPARATE)
                throw new ArgumentException("Planar images are not supported.");
            if (dir.IsTagPresent(TIFFConstants.TIFFTAG_EXTRASAMPLES))
                throw new ArgumentException("Extra samples are not supported.");
            int samplePerPixel = 1;
            if (dir.IsTagPresent(TIFFConstants.TIFFTAG_SAMPLESPERPIXEL)) // 1,3,4
                samplePerPixel = (int)dir.GetFieldAsLong(TIFFConstants.TIFFTAG_SAMPLESPERPIXEL);
            int bitsPerSample = 1;
            if (dir.IsTagPresent(TIFFConstants.TIFFTAG_BITSPERSAMPLE))
                bitsPerSample = (int)dir.GetFieldAsLong(TIFFConstants.TIFFTAG_BITSPERSAMPLE);
            switch (bitsPerSample) {
                case 1:
                case 2:
                case 4:
                case 8:
                    break;
                default:
                    throw new ArgumentException("Bits per sample " + bitsPerSample + " is not supported.");
            }
            Image img = null;

            int h = (int)dir.GetFieldAsLong(TIFFConstants.TIFFTAG_IMAGELENGTH);
            int w = (int)dir.GetFieldAsLong(TIFFConstants.TIFFTAG_IMAGEWIDTH);
            int dpiX = 0;
            int dpiY = 0;
            int resolutionUnit = TIFFConstants.RESUNIT_INCH;
            if (dir.IsTagPresent(TIFFConstants.TIFFTAG_RESOLUTIONUNIT))
                resolutionUnit = (int)dir.GetFieldAsLong(TIFFConstants.TIFFTAG_RESOLUTIONUNIT);
            dpiX = GetDpi(dir.GetField(TIFFConstants.TIFFTAG_XRESOLUTION), resolutionUnit);
            dpiY = GetDpi(dir.GetField(TIFFConstants.TIFFTAG_YRESOLUTION), resolutionUnit);
            int fillOrder = 1;
            bool reverse = false;
            TIFFField fillOrderField =  dir.GetField(TIFFConstants.TIFFTAG_FILLORDER);
            if (fillOrderField != null)
                fillOrder = fillOrderField.GetAsInt(0);
            reverse = (fillOrder == TIFFConstants.FILLORDER_LSB2MSB);
            int rowsStrip = h;
            if (dir.IsTagPresent(TIFFConstants.TIFFTAG_ROWSPERSTRIP)) //another hack for broken tiffs
                rowsStrip = (int)dir.GetFieldAsLong(TIFFConstants.TIFFTAG_ROWSPERSTRIP);
            if (rowsStrip <= 0 || rowsStrip > h)
                rowsStrip = h;
            long[] offset = GetArrayLongShort(dir, TIFFConstants.TIFFTAG_STRIPOFFSETS);
            long[] size = GetArrayLongShort(dir, TIFFConstants.TIFFTAG_STRIPBYTECOUNTS);
            if ((size == null || (size.Length == 1 && (size[0] == 0 || size[0] + offset[0] > s.Length))) && h == rowsStrip) { // some TIFF producers are really lousy, so...
                size = new long[]{s.Length - (int)offset[0]};
            }
            if (compression == TIFFConstants.COMPRESSION_LZW) {
                TIFFField predictorField = dir.GetField(TIFFConstants.TIFFTAG_PREDICTOR);
                if (predictorField != null) {
                    predictor = predictorField.GetAsInt(0);
                    if (predictor != 1 && predictor != 2) {
                        throw new Exception("Illegal value for Predictor in TIFF file.");
                    }
                    if (predictor == 2 && bitsPerSample != 8) {
                        throw new Exception(bitsPerSample + "-bit samples are not supported for Horizontal differencing Predictor.");
                    }
                }
                lzwDecoder = new TIFFLZWDecoder(w, predictor,
                                                samplePerPixel);
            }
            int rowsLeft = h;
            MemoryStream stream = null;
            ZOutputStream zip = null;
            CCITTG4Encoder g4 = null;
            if (bitsPerSample == 1 && samplePerPixel == 1) {
                g4 = new CCITTG4Encoder(w);
            }
            else {
                stream = new MemoryStream();
                if (compression != TIFFConstants.COMPRESSION_OJPEG && compression != TIFFConstants.COMPRESSION_JPEG)
                    zip = new ZOutputStream(stream);
            }
            if (compression == TIFFConstants.COMPRESSION_OJPEG) {

                // Assume that the TIFFTAG_JPEGIFBYTECOUNT tag is optional, since it's obsolete and
                // is often missing

                if ((!dir.IsTagPresent(TIFFConstants.TIFFTAG_JPEGIFOFFSET))) {
                    throw new IOException("Missing tag(s) for OJPEG compression.");
                }
                int jpegOffset = (int)dir.GetFieldAsLong(TIFFConstants.TIFFTAG_JPEGIFOFFSET);
                int jpegLength = s.Length - jpegOffset;

                if (dir.IsTagPresent(TIFFConstants.TIFFTAG_JPEGIFBYTECOUNT)) {
                    jpegLength = (int)dir.GetFieldAsLong(TIFFConstants.TIFFTAG_JPEGIFBYTECOUNT) +
                        (int)size[0];
                }

                byte[] jpeg = new byte[Math.Min(jpegLength, s.Length - jpegOffset)];

                int posFilePointer = s.FilePointer;
                posFilePointer += jpegOffset;
                s.Seek(posFilePointer);
                s.ReadFully(jpeg);
                img = new Jpeg(jpeg);
            }
            else if (compression == TIFFConstants.COMPRESSION_JPEG) {
                if (size.Length > 1)
                    throw new IOException("Compression JPEG is only supported with a single strip. This image has " + size.Length + " strips.");
                byte[] jpeg = new byte[(int)size[0]];
                s.Seek(offset[0]);
                s.ReadFully(jpeg);
                img = new Jpeg(jpeg);
            }
            else {
                for (int k = 0; k < offset.Length; ++k) {
                    byte[] im = new byte[(int)size[k]];
                    s.Seek(offset[k]);
                    s.ReadFully(im);
                    int height = Math.Min(rowsStrip, rowsLeft);
                    byte[] outBuf = null;
                    if (compression != TIFFConstants.COMPRESSION_NONE)
                        outBuf = new byte[(w * bitsPerSample * samplePerPixel + 7) / 8 * height];
                    if (reverse)
                        TIFFFaxDecoder.ReverseBits(im);
                    switch (compression) {
                        case TIFFConstants.COMPRESSION_DEFLATE:
                        case TIFFConstants.COMPRESSION_ADOBE_DEFLATE:
                            Inflate(im, outBuf);
                            break;
                        case TIFFConstants.COMPRESSION_NONE:
                            outBuf = im;
                            break;
                        case TIFFConstants.COMPRESSION_PACKBITS:
                            DecodePackbits(im,  outBuf);
                            break;
                        case TIFFConstants.COMPRESSION_LZW:
                            lzwDecoder.Decode(im, outBuf, height);
                            break;
                    }
                    if (bitsPerSample == 1 && samplePerPixel == 1) {
                        g4.Fax4Encode(outBuf, height);
                    }
                    else {
                        zip.Write(outBuf, 0, outBuf.Length);
                    }
                    rowsLeft -= rowsStrip;
                }
                if (bitsPerSample == 1 && samplePerPixel == 1) {
                    img = Image.GetInstance(w, h, false, Image.CCITTG4,
                        photometric == TIFFConstants.PHOTOMETRIC_MINISBLACK ? Image.CCITT_BLACKIS1 : 0, g4.Close());
                }
                else {
                    zip.Close();
                    img = Image.GetInstance(w, h, samplePerPixel, bitsPerSample, stream.ToArray());
                    img.Deflated = true;
                }
            }
            img.SetDpi(dpiX, dpiY);
            if (compression != TIFFConstants.COMPRESSION_OJPEG && compression != TIFFConstants.COMPRESSION_JPEG) {
                if (dir.IsTagPresent(TIFFConstants.TIFFTAG_ICCPROFILE)) {
                    try {
                        TIFFField fd = dir.GetField(TIFFConstants.TIFFTAG_ICCPROFILE);
                        ICC_Profile icc_prof = ICC_Profile.GetInstance(fd.GetAsBytes());
                        if (samplePerPixel == icc_prof.NumComponents)
                            img.TagICC = icc_prof;
                    }
                    catch {
                        //empty
                    }
                }
                if (dir.IsTagPresent(TIFFConstants.TIFFTAG_COLORMAP)) {
                    TIFFField fd = dir.GetField(TIFFConstants.TIFFTAG_COLORMAP);
                    char[] rgb = fd.GetAsChars();
                    byte[] palette = new byte[rgb.Length];
                    int gColor = rgb.Length / 3;
                    int bColor = gColor * 2;
                    for (int k = 0; k < gColor; ++k) {
                        palette[k * 3] = (byte)(rgb[k] >> 8);
                        palette[k * 3 + 1] = (byte)(rgb[k + gColor] >> 8);
                        palette[k * 3 + 2] = (byte)(rgb[k + bColor] >> 8);
                    }
                    PdfArray indexed = new PdfArray();
                    indexed.Add(PdfName.INDEXED);
                    indexed.Add(PdfName.DEVICERGB);
                    indexed.Add(new PdfNumber(gColor - 1));
                    indexed.Add(new PdfString(palette));
                    PdfDictionary additional = new PdfDictionary();
                    additional.Put(PdfName.COLORSPACE, indexed);
                    img.Additional = additional;
                }
                img.OriginalType = Image.ORIGINAL_TIFF;
            }
            if (photometric == TIFFConstants.PHOTOMETRIC_MINISWHITE)
                img.Inverted = true;
            if (rotation != 0)
                img.InitialRotation = rotation;
            return img;
        }
コード例 #21
0
ファイル: PngImage.cs プロジェクト: Daoting/dt
        /// <summary>
        /// Gets the colorspace.
        /// </summary>
        /// <returns></returns>
        private PdfObjectBase GetColorspace()
        {
            if ((this.gamma == 1f) && !this.hasCHRM)
            {
                if ((this.colorType & 2) != 0)
                {
                    return(PdfName.DeviceRGB);
                }
                return(PdfName.DeviceGray);
            }
            PdfArray      array = new PdfArray();
            PdfDictionary item  = new PdfDictionary();

            if ((this.colorType & 2) == 0)
            {
                if (this.gamma == 1f)
                {
                    return(PdfName.DeviceGray);
                }
                array.Add(PdfName.CalGray);
                item.Add(PdfName.Gamma, new PdfNumber((double)this.gamma));
                item.Add(PdfName.WhitePoint, PdfArray.Convert(new int[] { 1, 1, 1 }));
                array.Add(item);
                return(array);
            }
            PdfArray array2 = PdfArray.Convert(new int[] { 1, 1, 1 });

            array.Add(PdfName.CalRGB);
            if (this.gamma != 1f)
            {
                PdfArray  array3 = new PdfArray();
                PdfNumber number = new PdfNumber((double)this.gamma);
                array3.Add(number);
                array3.Add(number);
                array3.Add(number);
                item.Add(PdfName.Gamma, array3);
            }
            if (this.hasCHRM)
            {
                float num   = this.yW * ((((this.xG - this.xB) * this.yR) - ((this.xR - this.xB) * this.yG)) + ((this.xR - this.xG) * this.yB));
                float num2  = (this.yR * ((((this.xG - this.xB) * this.yW) - ((this.xW - this.xB) * this.yG)) + ((this.xW - this.xG) * this.yB))) / num;
                float num3  = (num2 * this.xR) / this.yR;
                float num4  = num2 * (((1f - this.xR) / this.yR) - 1f);
                float num5  = (-this.yG * ((((this.xR - this.xB) * this.yW) - ((this.xW - this.xB) * this.yR)) + ((this.xW - this.xR) * this.yB))) / num;
                float num6  = (num5 * this.xG) / this.yG;
                float num7  = num5 * (((1f - this.xG) / this.yG) - 1f);
                float num8  = (this.yB * ((((this.xR - this.xG) * this.yW) - ((this.xW - this.xG) * this.yW)) + ((this.xW - this.xR) * this.yG))) / num;
                float num9  = (num8 * this.xB) / this.yB;
                float num10 = num8 * (((1f - this.xB) / this.yB) - 1f);
                float num11 = (num3 + num6) + num9;
                float num12 = (num4 + num7) + num10;
                array2 = new PdfArray {
                    new PdfNumber((double)num11),
                    new PdfNumber(1.0),
                    new PdfNumber((double)num12)
                };
                PdfArray array5 = new PdfArray {
                    new PdfNumber((double)num3),
                    new PdfNumber((double)num2),
                    new PdfNumber((double)num4),
                    new PdfNumber((double)num6),
                    new PdfNumber((double)num5),
                    new PdfNumber((double)num7),
                    new PdfNumber((double)num9),
                    new PdfNumber((double)num8),
                    new PdfNumber((double)num10)
                };
                item.Add(PdfName.Matrix, array5);
            }
            item.Add(PdfName.WhitePoint, array2);
            array.Add(item);
            return(array);
        }
コード例 #22
0
        /// <summary>
        /// Reads next frame image
        /// </summary>
        protected void ReadImage()
        {
            Ix = ReadShort();    // (sub)image position & size
            Iy = ReadShort();
            Iw = ReadShort();
            Ih = ReadShort();

            int packed = Inp.ReadByte();

            LctFlag   = (packed & 0x80) != 0;   // 1 - local color table flag
            Interlace = (packed & 0x40) != 0;   // 2 - interlace flag
            // 3 - sort flag
            // 4-5 - reserved
            LctSize = 2 << (packed & 7);        // 6-8 - local color table size
            MBpc    = NewBpc(MGbpc);
            if (LctFlag)
            {
                MCurrTable = ReadColorTable((packed & 7) + 1);   // read table
                MBpc       = NewBpc((packed & 7) + 1);
            }
            else
            {
                MCurrTable = MGlobalTable;
            }
            if (Transparency && TransIndex >= MCurrTable.Length / 3)
            {
                Transparency = false;
            }
            if (Transparency && MBpc == 1)
            { // Acrobat 5.05 doesn't like this combination
                byte[] tp = new byte[12];
                Array.Copy(MCurrTable, 0, tp, 0, 6);
                MCurrTable = tp;
                MBpc       = 2;
            }
            bool skipZero = DecodeImageData();   // decode pixel data

            if (!skipZero)
            {
                Skip();
            }

            Image img = null;

            img = new ImgRaw(Iw, Ih, 1, MBpc, MOut);
            PdfArray colorspace = new PdfArray();

            colorspace.Add(PdfName.Indexed);
            colorspace.Add(PdfName.Devicergb);
            int len = MCurrTable.Length;

            colorspace.Add(new PdfNumber(len / 3 - 1));
            colorspace.Add(new PdfString(MCurrTable));
            PdfDictionary ad = new PdfDictionary();

            ad.Put(PdfName.Colorspace, colorspace);
            img.Additional = ad;
            if (Transparency)
            {
                img.Transparency = new[] { TransIndex, TransIndex };
            }
            img.OriginalType = Image.ORIGINAL_GIF;
            img.OriginalData = FromData;
            img.Url          = FromUrl;
            GifFrame gf = new GifFrame();

            gf.Image = img;
            gf.Ix    = Ix;
            gf.Iy    = Iy;
            Frames.Add(gf);   // add image to frame list

            //ResetFrame();
        }
コード例 #23
0
ファイル: Comparer.cs プロジェクト: m1skipper/PDFPublisher
        //--------------------------------------------------------------------------------------------------
        void MarkText(List <TextItem> items, int iPosition, int iCount, PdfStamper stamper, BaseColor color, int iPageAdd = 0, string stComment = null)
        {
            const string stTittle = "PDFCompare";

            if (iCount == 0)
            {
                float rWidth, rPosition;
                if (iPosition >= items.Count)
                {
                    iPosition = items.Count - 1;
                    rWidth    = (items[iPosition].MaxY - items[iPosition].MinY) / 5;
                    rPosition = items[iPosition].MaxX;
                }
                else
                {
                    rWidth    = (items[iPosition].MaxY - items[iPosition].MinY) / 5;
                    rPosition = items[iPosition].MinX - rWidth;
                }
                Rectangle     rect      = new Rectangle(rPosition, items[iPosition].MaxY, rPosition + rWidth, items[iPosition].MinY);
                float[]       quad      = { rect.Left, rect.Bottom, rect.Right, rect.Bottom, rect.Left, rect.Top, rect.Right, rect.Top };
                PdfAnnotation highlight = PdfAnnotation.CreateMarkup(stamper.Writer, rect, stComment, PdfAnnotation.MARKUP_HIGHLIGHT, quad);
                highlight.Color = color;
                highlight.Title = stTittle;
                stamper.AddAnnotation(highlight, items[iPosition].Page + iPageAdd);
            }
            else
            {
                while (iCount > 0 && items[iPosition].IsImage)
                {
                    TextItem  item       = items[iPosition];
                    Rectangle rect       = new Rectangle(item.MinX, item.MaxY, item.MaxX, item.MinY);
                    PdfArray  vertices   = new PdfArray();
                    float     rHalfWidth = 4;
                    vertices.Add(new PdfNumber(item.MinX - rHalfWidth));
                    vertices.Add(new PdfNumber(item.MinY - rHalfWidth));
                    vertices.Add(new PdfNumber(item.MaxX + rHalfWidth));
                    vertices.Add(new PdfNumber(item.MinY - rHalfWidth));
                    vertices.Add(new PdfNumber(item.MaxX + rHalfWidth));
                    vertices.Add(new PdfNumber(item.MaxY + rHalfWidth));
                    vertices.Add(new PdfNumber(item.MinX - rHalfWidth));
                    vertices.Add(new PdfNumber(item.MaxY + rHalfWidth));
                    vertices.Add(new PdfNumber(item.MinX - rHalfWidth));
                    vertices.Add(new PdfNumber(item.MinY - rHalfWidth));
                    PdfAnnotation highlight = PdfAnnotation.CreatePolygonPolyline(stamper.Writer, rect, stComment, true, vertices);
                    highlight.Color  = color;
                    highlight.Title  = stTittle;
                    highlight.Border = new PdfBorderArray(0, 0, rHalfWidth * 2);
                    stamper.AddAnnotation(highlight, item.Page + iPageAdd);
                    iPosition++;
                    iCount--;
                }
                if (iCount == 0)
                {
                    return;
                }
                int i;
                for (i = iPosition; i < iPosition + iCount; i++)
                {
                    if (items[i].IsImage)
                    {
                        MarkText(items, iPosition, i - iPosition, stamper, color, iPageAdd, stComment);
                        MarkText(items, i, 1, stamper, color, iPageAdd, stComment);
                        if (i + 1 >= iPosition + iCount)
                        {
                            return;
                        }
                        iCount   -= (i - iPosition) + 1;
                        iPosition = i + 1;
                    }
                }
                if (!items[iPosition].IsNewLine)
                {
                    i = iPosition;
                    while (i < iPosition + iCount - 1 && !items[i + 1].IsNewLine)
                    {
                        i++;
                    }
                    Rectangle     rect      = new Rectangle(items[iPosition].MinX, items[iPosition].MaxY, items[i].MaxX, items[iPosition].MinY);
                    float[]       quad      = { rect.Left, rect.Bottom, rect.Right, rect.Bottom, rect.Left, rect.Top, rect.Right, rect.Top };
                    PdfAnnotation highlight = PdfAnnotation.CreateMarkup(stamper.Writer, rect, stComment, PdfAnnotation.MARKUP_HIGHLIGHT, quad);
                    highlight.Color = color;
                    highlight.Title = stTittle;
                    stamper.AddAnnotation(highlight, items[iPosition].Page + iPageAdd);
                    iCount   -= (i - iPosition) + 1;
                    iPosition = i + 1;
                }
                if (iCount == 0)
                {
                    return;
                }
                if (items.Count > iPosition + iCount && !items[iPosition + iCount].IsNewLine)
                {
                    i = iPosition + iCount - 1;
                    while (!items[i].IsNewLine)
                    {
                        i--;
                    }
                    Rectangle     rect      = new Rectangle(items[i].MinX, items[i].MaxY, items[i = iPosition + iCount - 1].MaxX, items[i].MinY);
                    float[]       quad      = { rect.Left, rect.Bottom, rect.Right, rect.Bottom, rect.Left, rect.Top, rect.Right, rect.Top };
                    PdfAnnotation highlight = PdfAnnotation.CreateMarkup(stamper.Writer, rect, stComment, PdfAnnotation.MARKUP_HIGHLIGHT, quad);
                    highlight.Color = color;
                    highlight.Title = stTittle;
                    stamper.AddAnnotation(highlight, items[iPosition].Page + iPageAdd);
                    iCount -= iPosition + iCount - i;
                }
                if (iCount == 0)
                {
                    return;
                }
                i = iPosition;
                float rMinX = items[iPosition].MinX;
                float rMaxX = items[iPosition].MaxX;
                while (i < iPosition + iCount)
                {
                    i++;
                    if (i == iPosition + iCount || items[iPosition].Page != items[i].Page)
                    {
                        Rectangle     rect      = new Rectangle(rMinX, items[iPosition].MaxY, rMaxX, items[i - 1].MinY);
                        float[]       quad      = { rect.Left, rect.Bottom, rect.Right, rect.Bottom, rect.Left, rect.Top, rect.Right, rect.Top };
                        PdfAnnotation highlight = PdfAnnotation.CreateMarkup(stamper.Writer, rect, stComment, PdfAnnotation.MARKUP_HIGHLIGHT, quad);
                        highlight.Color = color;
                        highlight.Title = stTittle;
                        stamper.AddAnnotation(highlight, items[iPosition].Page + iPageAdd);
                        iCount   -= i - iPosition;
                        iPosition = i;
                        if (iCount == 0)
                        {
                            return;
                        }
                        rMinX = items[iPosition].MinX;
                        rMaxX = items[iPosition].MaxX;
                    }
                    if (items[i].MinX < rMinX)
                    {
                        rMinX = items[i].MinX;
                    }
                    if (items[i].MaxX > rMaxX)
                    {
                        rMaxX = items[i].MaxX;
                    }
                }

                /*
                 * for(i = iPosition; i < iPosition + iCount; i++)
                 * {
                 *      TextItem item = items[i];
                 *      Rectangle rect = new Rectangle(item.MinX, item.MaxY, item.MaxX, item.MinY);
                 *      float[] quad = { rect.Left, rect.Bottom, rect.Right, rect.Bottom, rect.Left, rect.Top, rect.Right, rect.Top };
                 *      PdfAnnotation highlight = PdfAnnotation.CreateMarkup(stamper.Writer, rect, stComment, PdfAnnotation.MARKUP_HIGHLIGHT, quad);
                 *      highlight.Color = color;
                 *      highlight.Title = stTittle;
                 *      stamper.AddAnnotation(highlight, item.Page + iPageAdd);
                 * }
                 */
            }
        }
コード例 #24
0
ファイル: PageStamper.cs プロジェクト: n9/pdfclown
        public void Flush(
            )
        {
            // Ensuring that there's room for the new content chunks inside the page's content stream...
              /*
            NOTE: This specialized stamper is optimized for content insertion without modifying
            existing content representations, leveraging the peculiar feature of page structures
            to express their content streams as arrays of data streams.
              */
              PdfArray streams;
              {
            PdfDirectObject contentsObject = page.BaseDataObject[PdfName.Contents];
            PdfDataObject contentsDataObject = PdfObject.Resolve(contentsObject);
            // Single data stream?
            if(contentsDataObject is PdfStream)
            {
              /*
            NOTE: Content stream MUST be expressed as an array of data streams in order to host
            background- and foreground-stamped contents.
              */
              streams = new PdfArray();
              streams.Add(contentsObject);
              page.BaseDataObject[PdfName.Contents] = streams;
            }
            else
            {streams = (PdfArray)contentsDataObject;}
              }

              // Background.
              // Serialize the content!
              background.Flush();
              // Insert the serialized content into the page's content stream!
              streams.Insert(0, background.Scanner.Contents.BaseObject);

              // Foreground.
              // Serialize the content!
              foreground.Flush();
              // Append the serialized content into the page's content stream!
              streams.Add(foreground.Scanner.Contents.BaseObject);
        }
コード例 #25
0
ファイル: CompositeFont.cs プロジェクト: evertop/PDFClown
        /**
         * <summary>Creates the character code mapping for composite fonts.</summary>
         */
        private void Load_CreateEncoding(
            PdfDictionary font,
            PdfDictionary cidFont
            )
        {
            /*
             * NOTE: Composite fonts map text shown by content stream strings through a 2-level encoding
             * scheme:
             *  character code -> CID (character index) -> GID (glyph index)
             * This works for rendering purposes, but if we want our text data to be intrinsically meaningful,
             * we need a further mapping towards some standard character identification scheme (Unicode):
             *  Unicode <- character code -> CID -> GID
             * Such mapping may be provided by a known CID collection or (in case of custom encodings like
             * Identity-H) by an explicit ToUnicode CMap.
             * CID -> GID mapping is typically identity, that is CIDS correspond to GIDS, so we don't bother
             * about that. Our base encoding is Identity-H, that is character codes correspond to CIDs;
             * however, sometimes a font maps multiple Unicode codepoints to the same GID (for example, the
             * hyphen glyph may be associated to the hyphen (\u2010) and minus (\u002D) symbols), breaking
             * the possibility to recover their original Unicode values once represented as character codes
             * in content stream strings. In this case, we are forced to remap the exceeding codes and
             * generate an explicit CMap (TODO: I tried to emit a differential CMap using the usecmap
             * operator in order to import Identity-H as base encoding, but it failed in several engines
             * (including Acrobat, Ghostscript, Poppler, whilst it surprisingly worked with pdf.js), so we
             * have temporarily to stick with full CMaps).
             */

            // Encoding [PDF:1.7:5.6.1,5.6.4].
            PdfDirectObject encodingObject = PdfName.IdentityH;
            SortedDictionary <ByteArray, int> sortedCodes;

            {
                codes = new BiDictionary <ByteArray, int>(glyphIndexes.Count);
                int         lastRemappedCharCodeValue = 0;
                IList <int> removedGlyphIndexKeys     = null;
                foreach (KeyValuePair <int, int> glyphIndexEntry in glyphIndexes.ToList())
                {
                    int       glyphIndex = glyphIndexEntry.Value;
                    ByteArray charCode   = new ByteArray(new byte[]
                    {
                        (byte)((glyphIndex >> 8) & 0xFF),
                        (byte)(glyphIndex & 0xFF)
                    });

                    // Checking for multiple Unicode codepoints which map to the same glyph index...

                    /*
                     * NOTE: In case the same glyph index maps to multiple Unicode codepoints, we are forced to
                     * alter the identity encoding creating distinct cmap entries for the exceeding codepoints.
                     */
                    if (codes.ContainsKey(charCode))
                    {
                        if (glyphIndex == 0) // .notdef glyph already mapped.
                        {
                            if (removedGlyphIndexKeys == null)
                            {
                                removedGlyphIndexKeys = new List <int>();
                            }
                            removedGlyphIndexKeys.Add(glyphIndexEntry.Key);
                            continue;
                        }

                        // Assigning the new character code...

                        /*
                         * NOTE: As our base encoding is identity, we have to look for a value that doesn't
                         * collide with existing glyph indices.
                         */
                        while (glyphIndexes.ContainsValue(++lastRemappedCharCodeValue))
                        {
                            ;
                        }
                        charCode.Data[0] = (byte)((lastRemappedCharCodeValue >> 8) & 0xFF);
                        charCode.Data[1] = (byte)(lastRemappedCharCodeValue & 0xFF);
                    }
                    else if (glyphIndex == 0) // .notdef glyph.
                    {
                        DefaultCode = glyphIndexEntry.Key;
                    }

                    codes[charCode] = glyphIndexEntry.Key;
                }
                if (removedGlyphIndexKeys != null)
                {
                    foreach (int removedGlyphIndexKey in removedGlyphIndexKeys)
                    {
                        glyphIndexes.Remove(removedGlyphIndexKey);
                    }
                }
                sortedCodes = new SortedDictionary <ByteArray, int>(codes);
                if (lastRemappedCharCodeValue > 0) // Custom encoding.
                {
                    string         cmapName   = "Custom";
                    bytes::IBuffer cmapBuffer = CMapBuilder.Build(
                        CMapBuilder.EntryTypeEnum.CID,
                        cmapName,
                        sortedCodes,
                        delegate(KeyValuePair <ByteArray, int> codeEntry)
                        { return(glyphIndexes[codeEntry.Value]); }
                        );
                    encodingObject = File.Register(
                        new PdfStream(
                            new PdfDictionary(
                                new PdfName[]
                    {
                        PdfName.Type,
                        PdfName.CMapName,
                        PdfName.CIDSystemInfo
                    },
                                new PdfDirectObject[]
                    {
                        PdfName.CMap,
                        new PdfName(cmapName),
                        new PdfDictionary(
                            new PdfName[]
                        {
                            PdfName.Registry,
                            PdfName.Ordering,
                            PdfName.Supplement
                        },
                            new PdfDirectObject[]
                        {
                            PdfTextString.Get("Adobe"),
                            PdfTextString.Get("Identity"),
                            PdfInteger.Get(0)
                        }
                            )
                    }
                                ),
                            cmapBuffer
                            )
                        );
                }
            }
            font[PdfName.Encoding]       = encodingObject;   // Character-code-to-CID mapping.
            cidFont[PdfName.CIDToGIDMap] = PdfName.Identity; // CID-to-glyph-index mapping.

            // ToUnicode [PDF:1.6:5.9.2].
            PdfDirectObject toUnicodeObject = null;

            {
                bytes::IBuffer toUnicodeBuffer = CMapBuilder.Build(
                    CMapBuilder.EntryTypeEnum.BaseFont,
                    null,
                    sortedCodes,
                    delegate(KeyValuePair <ByteArray, int> codeEntry)
                    { return(codeEntry.Value); }
                    );
                toUnicodeObject = File.Register(new PdfStream(toUnicodeBuffer));
            }
            font[PdfName.ToUnicode] = toUnicodeObject; // Character-code-to-Unicode mapping.

            // Glyph widths.
            PdfArray widthsObject = new PdfArray();

            {
                int      lastGlyphIndex            = -10;
                PdfArray lastGlyphWidthRangeObject = null;
                foreach (int glyphIndex in glyphIndexes.Values.OrderBy(x => x).ToList())
                {
                    int width;
                    if (!glyphWidths.TryGetValue(glyphIndex, out width))
                    {
                        width = 0;
                    }
                    if (glyphIndex - lastGlyphIndex != 1)
                    {
                        widthsObject.Add(PdfInteger.Get(glyphIndex));
                        widthsObject.Add(lastGlyphWidthRangeObject = new PdfArray());
                    }
                    lastGlyphWidthRangeObject.Add(PdfInteger.Get(width));
                    lastGlyphIndex = glyphIndex;
                }
            }
            cidFont[PdfName.W] = widthsObject; // Glyph widths.
        }
コード例 #26
0
        protected internal virtual void FlushFontData(String fontName, PdfName subtype)
        {
            GetPdfObject().Put(PdfName.Subtype, subtype);
            if (fontName != null && fontName.Length > 0)
            {
                GetPdfObject().Put(PdfName.BaseFont, new PdfName(fontName));
            }
            int firstChar;
            int lastChar;

            for (firstChar = 0; firstChar < 256; ++firstChar)
            {
                if (shortTag[firstChar] != 0)
                {
                    break;
                }
            }
            for (lastChar = 255; lastChar >= firstChar; --lastChar)
            {
                if (shortTag[lastChar] != 0)
                {
                    break;
                }
            }
            if (firstChar > 255)
            {
                firstChar = 255;
                lastChar  = 255;
            }
            if (!IsSubset() || !IsEmbedded())
            {
                firstChar = 0;
                lastChar  = shortTag.Length - 1;
                for (int k = 0; k < shortTag.Length; ++k)
                {
                    // remove unsupported by encoding values in case custom encoding.
                    // save widths information in case standard pdf encodings (winansi or macroman)
                    if (fontEncoding.CanDecode(k))
                    {
                        shortTag[k] = 1;
                    }
                    else
                    {
                        if (!fontEncoding.HasDifferences() && fontProgram.GetGlyphByCode(k) != null)
                        {
                            shortTag[k] = 1;
                        }
                        else
                        {
                            shortTag[k] = 0;
                        }
                    }
                }
            }
            if (fontEncoding.HasDifferences())
            {
                // trim range of symbols
                for (int k = firstChar; k <= lastChar; ++k)
                {
                    if (!FontEncoding.NOTDEF.Equals(fontEncoding.GetDifference(k)))
                    {
                        firstChar = k;
                        break;
                    }
                }
                for (int k = lastChar; k >= firstChar; --k)
                {
                    if (!FontEncoding.NOTDEF.Equals(fontEncoding.GetDifference(k)))
                    {
                        lastChar = k;
                        break;
                    }
                }
                PdfDictionary enc = new PdfDictionary();
                enc.Put(PdfName.Type, PdfName.Encoding);
                PdfArray diff = new PdfArray();
                bool     gap  = true;
                for (int k = firstChar; k <= lastChar; ++k)
                {
                    if (shortTag[k] != 0)
                    {
                        if (gap)
                        {
                            diff.Add(new PdfNumber(k));
                            gap = false;
                        }
                        diff.Add(new PdfName(fontEncoding.GetDifference(k)));
                    }
                    else
                    {
                        gap = true;
                    }
                }
                enc.Put(PdfName.Differences, diff);
                GetPdfObject().Put(PdfName.Encoding, enc);
            }
            else
            {
                if (!fontEncoding.IsFontSpecific())
                {
                    GetPdfObject().Put(PdfName.Encoding, PdfEncodings.CP1252.Equals(fontEncoding.GetBaseEncoding()) ? PdfName.
                                       WinAnsiEncoding : PdfName.MacRomanEncoding);
                }
            }
            if (IsForceWidthsOutput() || !IsBuiltInFont() || fontEncoding.HasDifferences())
            {
                GetPdfObject().Put(PdfName.FirstChar, new PdfNumber(firstChar));
                GetPdfObject().Put(PdfName.LastChar, new PdfNumber(lastChar));
                PdfArray wd = new PdfArray();
                for (int k = firstChar; k <= lastChar; ++k)
                {
                    if (shortTag[k] == 0)
                    {
                        wd.Add(new PdfNumber(0));
                    }
                    else
                    {
                        //prevent lost of widths info
                        int   uni   = fontEncoding.GetUnicode(k);
                        Glyph glyph = uni > -1 ? GetGlyph(uni) : fontProgram.GetGlyphByCode(k);
                        wd.Add(new PdfNumber(GetGlyphWidth(glyph)));
                    }
                }
                GetPdfObject().Put(PdfName.Widths, wd);
            }
            PdfDictionary fontDescriptor = !IsBuiltInFont() ? GetFontDescriptor(fontName) : null;

            if (fontDescriptor != null)
            {
                GetPdfObject().Put(PdfName.FontDescriptor, fontDescriptor);
                if (fontDescriptor.GetIndirectReference() != null)
                {
                    fontDescriptor.Flush();
                }
            }
        }
コード例 #27
0
        private static PdfDictionary CopyObject(PdfDictionary source, ICollection <PdfObject> objectsToCopy, PdfDocument
                                                toDocument, IDictionary <PdfDictionary, PdfDictionary> page2page, bool copyFromDestDocument)
        {
            PdfDictionary copied;

            if (copyFromDestDocument)
            {
                copied = source.Clone(ignoreKeysForCopy);
                if (source.IsIndirect())
                {
                    copied.MakeIndirect(toDocument);
                }
            }
            else
            {
                copied = source.CopyTo(toDocument, ignoreKeysForCopy, true);
            }
            if (source.ContainsKey(PdfName.Obj))
            {
                PdfDictionary obj = source.GetAsDictionary(PdfName.Obj);
                if (!copyFromDestDocument && obj != null)
                {
                    // Link annotations could be not added to the toDocument, so we need to identify this case.
                    // When obj.copyTo is called, and annotation was already copied, we would get this already created copy.
                    // If it was already copied and added, /P key would be set. Otherwise /P won't be set.
                    obj = obj.CopyTo(toDocument, iText.IO.Util.JavaUtil.ArraysAsList(PdfName.P), false);
                    copied.Put(PdfName.Obj, obj);
                }
            }
            PdfDictionary pg = source.GetAsDictionary(PdfName.Pg);

            if (pg != null)
            {
                //TODO It is possible, that pg will not be present in the page2page map. Consider the situation,
                // that we want to copy structElem because it has marked content dictionary reference, which belongs to the page from page2page,
                // but the structElem itself has /Pg which value could be arbitrary page.
                copied.Put(PdfName.Pg, page2page.Get(pg));
            }
            PdfObject k = source.Get(PdfName.K);

            if (k != null)
            {
                if (k.IsArray())
                {
                    PdfArray kArr   = (PdfArray)k;
                    PdfArray newArr = new PdfArray();
                    for (int i = 0; i < kArr.Size(); i++)
                    {
                        PdfObject copiedKid = CopyObjectKid(kArr.Get(i), copied, objectsToCopy, toDocument, page2page, copyFromDestDocument
                                                            );
                        if (copiedKid != null)
                        {
                            newArr.Add(copiedKid);
                        }
                    }
                    // TODO new array may be empty or with single element
                    copied.Put(PdfName.K, newArr);
                }
                else
                {
                    PdfObject copiedKid = CopyObjectKid(k, copied, objectsToCopy, toDocument, page2page, copyFromDestDocument);
                    if (copiedKid != null)
                    {
                        copied.Put(PdfName.K, copiedKid);
                    }
                }
            }
            return(copied);
        }
コード例 #28
0
        private static PdfDictionary CopyObject(PdfDictionary source, PdfDictionary destPage, bool parentChangePg,
                                                StructureTreeCopier.StructElemCopyingParams copyingParams)
        {
            PdfDictionary copied;

            if (copyingParams.IsCopyFromDestDocument())
            {
                //TODO: detect wether object is needed to be cloned at all
                copied = source.Clone(ignoreKeysForClone);
                if (source.IsIndirect())
                {
                    copied.MakeIndirect(copyingParams.GetToDocument());
                }
                PdfDictionary pg = source.GetAsDictionary(PdfName.Pg);
                if (pg != null)
                {
                    if (copyingParams.IsCopyFromDestDocument())
                    {
                        if (pg != destPage)
                        {
                            copied.Put(PdfName.Pg, destPage);
                            parentChangePg = true;
                        }
                        else
                        {
                            parentChangePg = false;
                        }
                    }
                }
            }
            else
            {
                copied = source.CopyTo(copyingParams.GetToDocument(), ignoreKeysForCopy, true);
                PdfDictionary obj = source.GetAsDictionary(PdfName.Obj);
                if (obj != null)
                {
                    // Link annotations could be not added to the toDocument, so we need to identify this case.
                    // When obj.copyTo is called, and annotation was already copied, we would get this already created copy.
                    // If it was already copied and added, /P key would be set. Otherwise /P won't be set.
                    obj = obj.CopyTo(copyingParams.GetToDocument(), JavaUtil.ArraysAsList(PdfName.P), false);
                    copied.Put(PdfName.Obj, obj);
                }
                PdfDictionary nsDict = source.GetAsDictionary(PdfName.NS);
                if (nsDict != null)
                {
                    PdfDictionary copiedNsDict = CopyNamespaceDict(nsDict, copyingParams);
                    copied.Put(PdfName.NS, copiedNsDict);
                }
                PdfDictionary pg = source.GetAsDictionary(PdfName.Pg);
                if (pg != null)
                {
                    PdfDictionary pageAnalog = copyingParams.GetPage2page().Get(pg);
                    if (pageAnalog == null)
                    {
                        pageAnalog     = destPage;
                        parentChangePg = true;
                    }
                    else
                    {
                        parentChangePg = false;
                    }
                    copied.Put(PdfName.Pg, pageAnalog);
                }
            }
            PdfObject k = source.Get(PdfName.K);

            if (k != null)
            {
                if (k.IsArray())
                {
                    PdfArray kArr   = (PdfArray)k;
                    PdfArray newArr = new PdfArray();
                    for (int i = 0; i < kArr.Size(); i++)
                    {
                        PdfObject copiedKid = CopyObjectKid(kArr.Get(i), copied, destPage, parentChangePg, copyingParams);
                        if (copiedKid != null)
                        {
                            newArr.Add(copiedKid);
                        }
                    }
                    if (!newArr.IsEmpty())
                    {
                        if (newArr.Size() == 1)
                        {
                            copied.Put(PdfName.K, newArr.Get(0));
                        }
                        else
                        {
                            copied.Put(PdfName.K, newArr);
                        }
                    }
                }
                else
                {
                    PdfObject copiedKid = CopyObjectKid(k, copied, destPage, parentChangePg, copyingParams);
                    if (copiedKid != null)
                    {
                        copied.Put(PdfName.K, copiedKid);
                    }
                }
            }
            return(copied);
        }
コード例 #29
0
 PdfObject getColorspace()
 {
     if (_iccProfile != null)
     {
         if ((_colorType & 2) == 0)
         {
             return(PdfName.Devicegray);
         }
         else
         {
             return(PdfName.Devicergb);
         }
     }
     if (_gamma.ApproxEquals(1f) && !_hasChrm)
     {
         if ((_colorType & 2) == 0)
         {
             return(PdfName.Devicegray);
         }
         else
         {
             return(PdfName.Devicergb);
         }
     }
     else
     {
         PdfArray      array = new PdfArray();
         PdfDictionary dic   = new PdfDictionary();
         if ((_colorType & 2) == 0)
         {
             if (_gamma.ApproxEquals(1f))
             {
                 return(PdfName.Devicegray);
             }
             array.Add(PdfName.Calgray);
             dic.Put(PdfName.Gamma, new PdfNumber(_gamma));
             dic.Put(PdfName.Whitepoint, new PdfLiteral("[1 1 1]"));
             array.Add(dic);
         }
         else
         {
             PdfObject wp = new PdfLiteral("[1 1 1]");
             array.Add(PdfName.Calrgb);
             if (_gamma.ApproxNotEqual(1f))
             {
                 PdfArray  gm = new PdfArray();
                 PdfNumber n  = new PdfNumber(_gamma);
                 gm.Add(n);
                 gm.Add(n);
                 gm.Add(n);
                 dic.Put(PdfName.Gamma, gm);
             }
             if (_hasChrm)
             {
                 float    z   = _yW * ((_xG - _xB) * _yR - (_xR - _xB) * _yG + (_xR - _xG) * _yB);
                 float    ya  = _yR * ((_xG - _xB) * _yW - (_xW - _xB) * _yG + (_xW - _xG) * _yB) / z;
                 float    xa  = ya * _xR / _yR;
                 float    za  = ya * ((1 - _xR) / _yR - 1);
                 float    yb  = -_yG * ((_xR - _xB) * _yW - (_xW - _xB) * _yR + (_xW - _xR) * _yB) / z;
                 float    xb  = yb * _xG / _yG;
                 float    zb  = yb * ((1 - _xG) / _yG - 1);
                 float    yc  = _yB * ((_xR - _xG) * _yW - (_xW - _xG) * _yW + (_xW - _xR) * _yG) / z;
                 float    xc  = yc * _xB / _yB;
                 float    zc  = yc * ((1 - _xB) / _yB - 1);
                 float    xw  = xa + xb + xc;
                 float    yw  = 1;//YA+YB+YC;
                 float    zw  = za + zb + zc;
                 PdfArray wpa = new PdfArray();
                 wpa.Add(new PdfNumber(xw));
                 wpa.Add(new PdfNumber(yw));
                 wpa.Add(new PdfNumber(zw));
                 wp = wpa;
                 PdfArray matrix = new PdfArray();
                 matrix.Add(new PdfNumber(xa));
                 matrix.Add(new PdfNumber(ya));
                 matrix.Add(new PdfNumber(za));
                 matrix.Add(new PdfNumber(xb));
                 matrix.Add(new PdfNumber(yb));
                 matrix.Add(new PdfNumber(zb));
                 matrix.Add(new PdfNumber(xc));
                 matrix.Add(new PdfNumber(yc));
                 matrix.Add(new PdfNumber(zc));
                 dic.Put(PdfName.Matrix, matrix);
             }
             dic.Put(PdfName.Whitepoint, wp);
             array.Add(dic);
         }
         return(array);
     }
 }
コード例 #30
0
        /**
         * Reads next frame image
         */
        protected void ReadImage()
        {
            ix = ReadShort();    // (sub)image position & size
            iy = ReadShort();
            iw = ReadShort();
            ih = ReadShort();

            int packed = inp.ReadByte();

            lctFlag   = (packed & 0x80) != 0;   // 1 - local color table flag
            interlace = (packed & 0x40) != 0;   // 2 - interlace flag
            // 3 - sort flag
            // 4-5 - reserved
            lctSize = 2 << (packed & 7);        // 6-8 - local color table size
            m_bpc   = NewBpc(m_gbpc);
            if (lctFlag)
            {
                m_curr_table = ReadColorTable((packed & 7) + 1);   // read table
                m_bpc        = NewBpc((packed & 7) + 1);
            }
            else
            {
                m_curr_table = m_global_table;
            }
            if (transparency && transIndex >= m_curr_table.Length / 3)
            {
                transparency = false;
            }
            if (transparency && m_bpc == 1)   // Acrobat 5.05 doesn't like this combination
            {
                byte[] tp = new byte[12];
                Array.Copy(m_curr_table, 0, tp, 0, 6);
                m_curr_table = tp;
                m_bpc        = 2;
            }
            bool skipZero = DecodeImageData();   // decode pixel data

            if (!skipZero)
            {
                Skip();
            }

            Image img = null;

            img = new ImgRaw(iw, ih, 1, m_bpc, m_out);
            PdfArray colorspace = new PdfArray();

            colorspace.Add(PdfName.INDEXED);
            colorspace.Add(PdfName.DEVICERGB);
            int len = m_curr_table.Length;

            colorspace.Add(new PdfNumber(len / 3 - 1));
            colorspace.Add(new PdfString(m_curr_table));
            PdfDictionary ad = new PdfDictionary();

            ad.Put(PdfName.COLORSPACE, colorspace);
            img.Additional = ad;
            if (transparency)
            {
                img.Transparency = new int[] { transIndex, transIndex };
            }
            img.OriginalType = Image.ORIGINAL_GIF;
            img.OriginalData = fromData;
            img.Url          = fromUrl;
            GifFrame gf = new GifFrame();

            gf.image = img;
            gf.ix    = ix;
            gf.iy    = iy;
            frames.Add(gf);   // add image to frame list

            //ResetFrame();
        }
コード例 #31
0
        void readPng()
        {
            for (int i = 0; i < Pngid.Length; i++)
            {
                if (Pngid[i] != _isp.ReadByte())
                {
                    throw new IOException("File is not a valid PNG.");
                }
            }
            byte[] buffer = new byte[Transfersize];
            while (true)
            {
                int    len    = GetInt(_isp);
                string marker = GetString(_isp);
                if (len < 0 || !checkMarker(marker))
                {
                    throw new IOException("Corrupted PNG file.");
                }
                if (IDAT.Equals(marker))
                {
                    int size;
                    while (len != 0)
                    {
                        size = _isp.Read(buffer, 0, Math.Min(len, Transfersize));
                        if (size <= 0)
                        {
                            return;
                        }
                        _idat.Write(buffer, 0, size);
                        len -= size;
                    }
                }
                else if (tRNS.Equals(marker))
                {
                    switch (_colorType)
                    {
                    case 0:
                        if (len >= 2)
                        {
                            len -= 2;
                            int gray = GetWord(_isp);
                            if (_bitDepth == 16)
                            {
                                _transRedGray = gray;
                            }
                            else
                            {
                                _additional.Put(PdfName.Mask, new PdfLiteral("[" + gray + " " + gray + "]"));
                            }
                        }
                        break;

                    case 2:
                        if (len >= 6)
                        {
                            len -= 6;
                            int red   = GetWord(_isp);
                            int green = GetWord(_isp);
                            int blue  = GetWord(_isp);
                            if (_bitDepth == 16)
                            {
                                _transRedGray = red;
                                _transGreen   = green;
                                _transBlue    = blue;
                            }
                            else
                            {
                                _additional.Put(PdfName.Mask, new PdfLiteral("[" + red + " " + red + " " + green + " " + green + " " + blue + " " + blue + "]"));
                            }
                        }
                        break;

                    case 3:
                        if (len > 0)
                        {
                            _trans = new byte[len];
                            for (int k = 0; k < len; ++k)
                            {
                                _trans[k] = (byte)_isp.ReadByte();
                            }
                            len = 0;
                        }
                        break;
                    }
                    Utilities.Skip(_isp, len);
                }
                else if (IHDR.Equals(marker))
                {
                    _width  = GetInt(_isp);
                    _height = GetInt(_isp);

                    _bitDepth          = _isp.ReadByte();
                    _colorType         = _isp.ReadByte();
                    _compressionMethod = _isp.ReadByte();
                    _filterMethod      = _isp.ReadByte();
                    _interlaceMethod   = _isp.ReadByte();
                }
                else if (PLTE.Equals(marker))
                {
                    if (_colorType == 3)
                    {
                        PdfArray colorspace = new PdfArray();
                        colorspace.Add(PdfName.Indexed);
                        colorspace.Add(getColorspace());
                        colorspace.Add(new PdfNumber(len / 3 - 1));
                        ByteBuffer colortable = new ByteBuffer();
                        while ((len--) > 0)
                        {
                            colortable.Append_i(_isp.ReadByte());
                        }
                        colorspace.Add(new PdfString(_colorTable = colortable.ToByteArray()));
                        _additional.Put(PdfName.Colorspace, colorspace);
                    }
                    else
                    {
                        Utilities.Skip(_isp, len);
                    }
                }
                else if (pHYs.Equals(marker))
                {
                    int dx   = GetInt(_isp);
                    int dy   = GetInt(_isp);
                    int unit = _isp.ReadByte();
                    if (unit == 1)
                    {
                        _dpiX = (int)(dx * 0.0254f + 0.5f);
                        _dpiY = (int)(dy * 0.0254f + 0.5f);
                    }
                    else
                    {
                        if (dy != 0)
                        {
                            _xyRatio = dx / (float)dy;
                        }
                    }
                }
                else if (cHRM.Equals(marker))
                {
                    _xW      = GetInt(_isp) / 100000f;
                    _yW      = GetInt(_isp) / 100000f;
                    _xR      = GetInt(_isp) / 100000f;
                    _yR      = GetInt(_isp) / 100000f;
                    _xG      = GetInt(_isp) / 100000f;
                    _yG      = GetInt(_isp) / 100000f;
                    _xB      = GetInt(_isp) / 100000f;
                    _yB      = GetInt(_isp) / 100000f;
                    _hasChrm = !(Math.Abs(_xW) < 0.0001f || Math.Abs(_yW) < 0.0001f || Math.Abs(_xR) < 0.0001f || Math.Abs(_yR) < 0.0001f || Math.Abs(_xG) < 0.0001f || Math.Abs(_yG) < 0.0001f || Math.Abs(_xB) < 0.0001f || Math.Abs(_yB) < 0.0001f);
                }
                else if (sRGB.Equals(marker))
                {
                    int ri = _isp.ReadByte();
                    _intent  = _intents[ri];
                    _gamma   = 2.2f;
                    _xW      = 0.3127f;
                    _yW      = 0.329f;
                    _xR      = 0.64f;
                    _yR      = 0.33f;
                    _xG      = 0.3f;
                    _yG      = 0.6f;
                    _xB      = 0.15f;
                    _yB      = 0.06f;
                    _hasChrm = true;
                }
                else if (gAMA.Equals(marker))
                {
                    int gm = GetInt(_isp);
                    if (gm != 0)
                    {
                        _gamma = 100000f / gm;
                        if (!_hasChrm)
                        {
                            _xW      = 0.3127f;
                            _yW      = 0.329f;
                            _xR      = 0.64f;
                            _yR      = 0.33f;
                            _xG      = 0.3f;
                            _yG      = 0.6f;
                            _xB      = 0.15f;
                            _yB      = 0.06f;
                            _hasChrm = true;
                        }
                    }
                }
                else if (iCCP.Equals(marker))
                {
                    do
                    {
                        --len;
                    } while (_isp.ReadByte() != 0);
                    _isp.ReadByte();
                    --len;
                    byte[] icccom = new byte[len];
                    int    p      = 0;
                    while (len > 0)
                    {
                        int r = _isp.Read(icccom, p, len);
                        if (r < 0)
                        {
                            throw new IOException("Premature end of file.");
                        }
                        p   += r;
                        len -= r;
                    }
                    byte[] iccp = PdfReader.FlateDecode(icccom, true);
                    icccom = null;
                    try
                    {
                        _iccProfile = IccProfile.GetInstance(iccp);
                    }
                    catch
                    {
                        _iccProfile = null;
                    }
                }
                else if (IEND.Equals(marker))
                {
                    break;
                }
                else
                {
                    Utilities.Skip(_isp, len);
                }
                Utilities.Skip(_isp, 4);
            }
        }
コード例 #32
0
        void ReadPng()
        {
            for (int i = 0; i < PNGID.Length; i++)
            {
                if (PNGID[i] != isp.ReadByte())
                {
                    throw new IOException(MessageLocalization.GetComposedMessage("file.is.not.a.valid.png"));
                }
            }
            byte[] buffer = new byte[TRANSFERSIZE];
            while (true)
            {
                int    len    = GetInt(isp);
                String marker = GetString(isp);
                if (len < 0 || !CheckMarker(marker))
                {
                    throw new IOException(MessageLocalization.GetComposedMessage("corrupted.png.file"));
                }
                if (IDAT.Equals(marker))
                {
                    int size;
                    while (len != 0)
                    {
                        size = isp.Read(buffer, 0, Math.Min(len, TRANSFERSIZE));
                        if (size <= 0)
                        {
                            return;
                        }
                        idat.Write(buffer, 0, size);
                        len -= size;
                    }
                }
                else if (tRNS.Equals(marker))
                {
                    switch (colorType)
                    {
                    case 0:
                        if (len >= 2)
                        {
                            len -= 2;
                            int gray = GetWord(isp);
                            if (bitDepth == 16)
                            {
                                transRedGray = gray;
                            }
                            else
                            {
                                additional.Put(PdfName.MASK, new PdfLiteral("[" + gray + " " + gray + "]"));
                            }
                        }
                        break;

                    case 2:
                        if (len >= 6)
                        {
                            len -= 6;
                            int red   = GetWord(isp);
                            int green = GetWord(isp);
                            int blue  = GetWord(isp);
                            if (bitDepth == 16)
                            {
                                transRedGray = red;
                                transGreen   = green;
                                transBlue    = blue;
                            }
                            else
                            {
                                additional.Put(PdfName.MASK, new PdfLiteral("[" + red + " " + red + " " + green + " " + green + " " + blue + " " + blue + "]"));
                            }
                        }
                        break;

                    case 3:
                        if (len > 0)
                        {
                            trans = new byte[len];
                            for (int k = 0; k < len; ++k)
                            {
                                trans[k] = (byte)isp.ReadByte();
                            }
                            len = 0;
                        }
                        break;
                    }
                    Utilities.Skip(isp, len);
                }
                else if (IHDR.Equals(marker))
                {
                    width  = GetInt(isp);
                    height = GetInt(isp);

                    bitDepth          = isp.ReadByte();
                    colorType         = isp.ReadByte();
                    compressionMethod = isp.ReadByte();
                    filterMethod      = isp.ReadByte();
                    interlaceMethod   = isp.ReadByte();
                }
                else if (PLTE.Equals(marker))
                {
                    if (colorType == 3)
                    {
                        PdfArray colorspace = new PdfArray();
                        colorspace.Add(PdfName.INDEXED);
                        colorspace.Add(GetColorspace());
                        colorspace.Add(new PdfNumber(len / 3 - 1));
                        ByteBuffer colortable = new ByteBuffer();
                        while ((len--) > 0)
                        {
                            colortable.Append_i(isp.ReadByte());
                        }
                        colorspace.Add(new PdfString(colorTable = colortable.ToByteArray()));
                        additional.Put(PdfName.COLORSPACE, colorspace);
                    }
                    else
                    {
                        Utilities.Skip(isp, len);
                    }
                }
                else if (pHYs.Equals(marker))
                {
                    int dx   = GetInt(isp);
                    int dy   = GetInt(isp);
                    int unit = isp.ReadByte();
                    if (unit == 1)
                    {
                        dpiX = (int)((float)dx * 0.0254f + 0.5f);
                        dpiY = (int)((float)dy * 0.0254f + 0.5f);
                    }
                    else
                    {
                        if (dy != 0)
                        {
                            XYRatio = (float)dx / (float)dy;
                        }
                    }
                }
                else if (cHRM.Equals(marker))
                {
                    xW      = (float)GetInt(isp) / 100000f;
                    yW      = (float)GetInt(isp) / 100000f;
                    xR      = (float)GetInt(isp) / 100000f;
                    yR      = (float)GetInt(isp) / 100000f;
                    xG      = (float)GetInt(isp) / 100000f;
                    yG      = (float)GetInt(isp) / 100000f;
                    xB      = (float)GetInt(isp) / 100000f;
                    yB      = (float)GetInt(isp) / 100000f;
                    hasCHRM = !(Math.Abs(xW) < 0.0001f || Math.Abs(yW) < 0.0001f || Math.Abs(xR) < 0.0001f || Math.Abs(yR) < 0.0001f || Math.Abs(xG) < 0.0001f || Math.Abs(yG) < 0.0001f || Math.Abs(xB) < 0.0001f || Math.Abs(yB) < 0.0001f);
                }
                else if (sRGB.Equals(marker))
                {
                    int ri = isp.ReadByte();
                    intent  = intents[ri];
                    gamma   = 2.2f;
                    xW      = 0.3127f;
                    yW      = 0.329f;
                    xR      = 0.64f;
                    yR      = 0.33f;
                    xG      = 0.3f;
                    yG      = 0.6f;
                    xB      = 0.15f;
                    yB      = 0.06f;
                    hasCHRM = true;
                }
                else if (gAMA.Equals(marker))
                {
                    int gm = GetInt(isp);
                    if (gm != 0)
                    {
                        gamma = 100000f / (float)gm;
                        if (!hasCHRM)
                        {
                            xW      = 0.3127f;
                            yW      = 0.329f;
                            xR      = 0.64f;
                            yR      = 0.33f;
                            xG      = 0.3f;
                            yG      = 0.6f;
                            xB      = 0.15f;
                            yB      = 0.06f;
                            hasCHRM = true;
                        }
                    }
                }
                else if (iCCP.Equals(marker))
                {
                    do
                    {
                        --len;
                    } while (isp.ReadByte() != 0);
                    isp.ReadByte();
                    --len;
                    byte[] icccom = new byte[len];
                    int    p      = 0;
                    while (len > 0)
                    {
                        int r = isp.Read(icccom, p, len);
                        if (r < 0)
                        {
                            throw new IOException(MessageLocalization.GetComposedMessage("premature.end.of.file"));
                        }
                        p   += r;
                        len -= r;
                    }
                    byte[] iccp = PdfReader.FlateDecode(icccom, true);
                    icccom = null;
                    try {
                        icc_profile = ICC_Profile.GetInstance(iccp);
                    }
                    catch {
                        icc_profile = null;
                    }
                }
                else if (IEND.Equals(marker))
                {
                    break;
                }
                else
                {
                    Utilities.Skip(isp, len);
                }
                Utilities.Skip(isp, 4);
            }
        }
コード例 #33
0
        protected static Image GetTiffImageColor(TIFFDirectory dir, RandomAccessFileOrArray s)
        {
            int            predictor   = 1;
            TIFFLZWDecoder lzwDecoder  = null;
            int            compression = (int)dir.GetFieldAsLong(TIFFConstants.TIFFTAG_COMPRESSION);

            switch (compression)
            {
            case TIFFConstants.COMPRESSION_NONE:
            case TIFFConstants.COMPRESSION_LZW:
            case TIFFConstants.COMPRESSION_PACKBITS:
            case TIFFConstants.COMPRESSION_DEFLATE:
            case TIFFConstants.COMPRESSION_ADOBE_DEFLATE:
            case TIFFConstants.COMPRESSION_OJPEG:
            case TIFFConstants.COMPRESSION_JPEG:
                break;

            default:
                throw new ArgumentException("The compression " + compression + " is not supported.");
            }
            int photometric = (int)dir.GetFieldAsLong(TIFFConstants.TIFFTAG_PHOTOMETRIC);

            switch (photometric)
            {
            case TIFFConstants.PHOTOMETRIC_MINISWHITE:
            case TIFFConstants.PHOTOMETRIC_MINISBLACK:
            case TIFFConstants.PHOTOMETRIC_RGB:
            case TIFFConstants.PHOTOMETRIC_SEPARATED:
            case TIFFConstants.PHOTOMETRIC_PALETTE:
                break;

            default:
                if (compression != TIFFConstants.COMPRESSION_OJPEG && compression != TIFFConstants.COMPRESSION_JPEG)
                {
                    throw new ArgumentException("The photometric " + photometric + " is not supported.");
                }
                break;
            }
            float rotation = 0;

            if (dir.IsTagPresent(TIFFConstants.TIFFTAG_ORIENTATION))
            {
                int rot = (int)dir.GetFieldAsLong(TIFFConstants.TIFFTAG_ORIENTATION);
                if (rot == TIFFConstants.ORIENTATION_BOTRIGHT || rot == TIFFConstants.ORIENTATION_BOTLEFT)
                {
                    rotation = (float)Math.PI;
                }
                else if (rot == TIFFConstants.ORIENTATION_LEFTTOP || rot == TIFFConstants.ORIENTATION_LEFTBOT)
                {
                    rotation = (float)(Math.PI / 2.0);
                }
                else if (rot == TIFFConstants.ORIENTATION_RIGHTTOP || rot == TIFFConstants.ORIENTATION_RIGHTBOT)
                {
                    rotation = -(float)(Math.PI / 2.0);
                }
            }

            if (dir.IsTagPresent(TIFFConstants.TIFFTAG_PLANARCONFIG) &&
                dir.GetFieldAsLong(TIFFConstants.TIFFTAG_PLANARCONFIG) == TIFFConstants.PLANARCONFIG_SEPARATE)
            {
                throw new ArgumentException("Planar images are not supported.");
            }
            if (dir.IsTagPresent(TIFFConstants.TIFFTAG_EXTRASAMPLES))
            {
                throw new ArgumentException("Extra samples are not supported.");
            }
            int samplePerPixel = 1;

            if (dir.IsTagPresent(TIFFConstants.TIFFTAG_SAMPLESPERPIXEL)) // 1,3,4
            {
                samplePerPixel = (int)dir.GetFieldAsLong(TIFFConstants.TIFFTAG_SAMPLESPERPIXEL);
            }
            int bitsPerSample = 1;

            if (dir.IsTagPresent(TIFFConstants.TIFFTAG_BITSPERSAMPLE))
            {
                bitsPerSample = (int)dir.GetFieldAsLong(TIFFConstants.TIFFTAG_BITSPERSAMPLE);
            }
            switch (bitsPerSample)
            {
            case 1:
            case 2:
            case 4:
            case 8:
                break;

            default:
                throw new ArgumentException("Bits per sample " + bitsPerSample + " is not supported.");
            }
            Image img = null;

            int h              = (int)dir.GetFieldAsLong(TIFFConstants.TIFFTAG_IMAGELENGTH);
            int w              = (int)dir.GetFieldAsLong(TIFFConstants.TIFFTAG_IMAGEWIDTH);
            int dpiX           = 0;
            int dpiY           = 0;
            int resolutionUnit = TIFFConstants.RESUNIT_INCH;

            if (dir.IsTagPresent(TIFFConstants.TIFFTAG_RESOLUTIONUNIT))
            {
                resolutionUnit = (int)dir.GetFieldAsLong(TIFFConstants.TIFFTAG_RESOLUTIONUNIT);
            }
            dpiX = GetDpi(dir.GetField(TIFFConstants.TIFFTAG_XRESOLUTION), resolutionUnit);
            dpiY = GetDpi(dir.GetField(TIFFConstants.TIFFTAG_YRESOLUTION), resolutionUnit);
            int       fillOrder      = 1;
            bool      reverse        = false;
            TIFFField fillOrderField = dir.GetField(TIFFConstants.TIFFTAG_FILLORDER);

            if (fillOrderField != null)
            {
                fillOrder = fillOrderField.GetAsInt(0);
            }
            reverse = (fillOrder == TIFFConstants.FILLORDER_LSB2MSB);
            int rowsStrip = h;

            if (dir.IsTagPresent(TIFFConstants.TIFFTAG_ROWSPERSTRIP)) //another hack for broken tiffs
            {
                rowsStrip = (int)dir.GetFieldAsLong(TIFFConstants.TIFFTAG_ROWSPERSTRIP);
            }
            if (rowsStrip <= 0 || rowsStrip > h)
            {
                rowsStrip = h;
            }
            long[] offset = GetArrayLongShort(dir, TIFFConstants.TIFFTAG_STRIPOFFSETS);
            long[] size   = GetArrayLongShort(dir, TIFFConstants.TIFFTAG_STRIPBYTECOUNTS);
            if ((size == null || (size.Length == 1 && (size[0] == 0 || size[0] + offset[0] > s.Length))) && h == rowsStrip)   // some TIFF producers are really lousy, so...
            {
                size = new long[] { s.Length - (int)offset[0] };
            }
            if (compression == TIFFConstants.COMPRESSION_LZW)
            {
                TIFFField predictorField = dir.GetField(TIFFConstants.TIFFTAG_PREDICTOR);
                if (predictorField != null)
                {
                    predictor = predictorField.GetAsInt(0);
                    if (predictor != 1 && predictor != 2)
                    {
                        throw new Exception("Illegal value for Predictor in TIFF file.");
                    }
                    if (predictor == 2 && bitsPerSample != 8)
                    {
                        throw new Exception(bitsPerSample + "-bit samples are not supported for Horizontal differencing Predictor.");
                    }
                }
                lzwDecoder = new TIFFLZWDecoder(w, predictor,
                                                samplePerPixel);
            }
            int                   rowsLeft = h;
            MemoryStream          stream   = null;
            ZDeflaterOutputStream zip      = null;
            CCITTG4Encoder        g4       = null;

            if (bitsPerSample == 1 && samplePerPixel == 1)
            {
                g4 = new CCITTG4Encoder(w);
            }
            else
            {
                stream = new MemoryStream();
                if (compression != TIFFConstants.COMPRESSION_OJPEG && compression != TIFFConstants.COMPRESSION_JPEG)
                {
                    zip = new ZDeflaterOutputStream(stream);
                }
            }
            if (compression == TIFFConstants.COMPRESSION_OJPEG)
            {
                // Assume that the TIFFTAG_JPEGIFBYTECOUNT tag is optional, since it's obsolete and
                // is often missing

                if ((!dir.IsTagPresent(TIFFConstants.TIFFTAG_JPEGIFOFFSET)))
                {
                    throw new IOException("Missing tag(s) for OJPEG compression.");
                }
                int jpegOffset = (int)dir.GetFieldAsLong(TIFFConstants.TIFFTAG_JPEGIFOFFSET);
                int jpegLength = s.Length - jpegOffset;

                if (dir.IsTagPresent(TIFFConstants.TIFFTAG_JPEGIFBYTECOUNT))
                {
                    jpegLength = (int)dir.GetFieldAsLong(TIFFConstants.TIFFTAG_JPEGIFBYTECOUNT) +
                                 (int)size[0];
                }

                byte[] jpeg = new byte[Math.Min(jpegLength, s.Length - jpegOffset)];

                int posFilePointer = s.FilePointer;
                posFilePointer += jpegOffset;
                s.Seek(posFilePointer);
                s.ReadFully(jpeg);
                img = new Jpeg(jpeg);
            }
            else if (compression == TIFFConstants.COMPRESSION_JPEG)
            {
                if (size.Length > 1)
                {
                    throw new IOException("Compression JPEG is only supported with a single strip. This image has " + size.Length + " strips.");
                }
                byte[] jpeg = new byte[(int)size[0]];
                s.Seek(offset[0]);
                s.ReadFully(jpeg);
                img = new Jpeg(jpeg);
            }
            else
            {
                for (int k = 0; k < offset.Length; ++k)
                {
                    byte[] im = new byte[(int)size[k]];
                    s.Seek(offset[k]);
                    s.ReadFully(im);
                    int    height = Math.Min(rowsStrip, rowsLeft);
                    byte[] outBuf = null;
                    if (compression != TIFFConstants.COMPRESSION_NONE)
                    {
                        outBuf = new byte[(w * bitsPerSample * samplePerPixel + 7) / 8 * height];
                    }
                    if (reverse)
                    {
                        TIFFFaxDecoder.ReverseBits(im);
                    }
                    switch (compression)
                    {
                    case TIFFConstants.COMPRESSION_DEFLATE:
                    case TIFFConstants.COMPRESSION_ADOBE_DEFLATE:
                        Inflate(im, outBuf);
                        break;

                    case TIFFConstants.COMPRESSION_NONE:
                        outBuf = im;
                        break;

                    case TIFFConstants.COMPRESSION_PACKBITS:
                        DecodePackbits(im, outBuf);
                        break;

                    case TIFFConstants.COMPRESSION_LZW:
                        lzwDecoder.Decode(im, outBuf, height);
                        break;
                    }
                    if (bitsPerSample == 1 && samplePerPixel == 1)
                    {
                        g4.Fax4Encode(outBuf, height);
                    }
                    else
                    {
                        zip.Write(outBuf, 0, outBuf.Length);
                    }
                    rowsLeft -= rowsStrip;
                }
                if (bitsPerSample == 1 && samplePerPixel == 1)
                {
                    img = Image.GetInstance(w, h, false, Image.CCITTG4,
                                            photometric == TIFFConstants.PHOTOMETRIC_MINISBLACK ? Image.CCITT_BLACKIS1 : 0, g4.Close());
                }
                else
                {
                    zip.Close();
                    img          = Image.GetInstance(w, h, samplePerPixel, bitsPerSample, stream.ToArray());
                    img.Deflated = true;
                }
            }
            img.SetDpi(dpiX, dpiY);
            if (compression != TIFFConstants.COMPRESSION_OJPEG && compression != TIFFConstants.COMPRESSION_JPEG)
            {
                if (dir.IsTagPresent(TIFFConstants.TIFFTAG_ICCPROFILE))
                {
                    try {
                        TIFFField   fd       = dir.GetField(TIFFConstants.TIFFTAG_ICCPROFILE);
                        ICC_Profile icc_prof = ICC_Profile.GetInstance(fd.GetAsBytes());
                        if (samplePerPixel == icc_prof.NumComponents)
                        {
                            img.TagICC = icc_prof;
                        }
                    }
                    catch {
                        //empty
                    }
                }
                if (dir.IsTagPresent(TIFFConstants.TIFFTAG_COLORMAP))
                {
                    TIFFField fd      = dir.GetField(TIFFConstants.TIFFTAG_COLORMAP);
                    char[]    rgb     = fd.GetAsChars();
                    byte[]    palette = new byte[rgb.Length];
                    int       gColor  = rgb.Length / 3;
                    int       bColor  = gColor * 2;
                    for (int k = 0; k < gColor; ++k)
                    {
                        palette[k * 3]     = (byte)(rgb[k] >> 8);
                        palette[k * 3 + 1] = (byte)(rgb[k + gColor] >> 8);
                        palette[k * 3 + 2] = (byte)(rgb[k + bColor] >> 8);
                    }
                    PdfArray indexed = new PdfArray();
                    indexed.Add(PdfName.INDEXED);
                    indexed.Add(PdfName.DEVICERGB);
                    indexed.Add(new PdfNumber(gColor - 1));
                    indexed.Add(new PdfString(palette));
                    PdfDictionary additional = new PdfDictionary();
                    additional.Put(PdfName.COLORSPACE, indexed);
                    img.Additional = additional;
                }
                img.OriginalType = Image.ORIGINAL_TIFF;
            }
            if (photometric == TIFFConstants.PHOTOMETRIC_MINISWHITE)
            {
                img.Inverted = true;
            }
            if (rotation != 0)
            {
                img.InitialRotation = rotation;
            }
            return(img);
        }
コード例 #34
0
        virtual public PdfArray RotateAnnotations(PdfWriter writer, Rectangle pageSize)
        {
            PdfArray array       = new PdfArray();
            int      rotation    = pageSize.Rotation % 360;
            int      currentPage = writer.CurrentPageNumber;

            for (int k = 0; k < annotations.Count; ++k)
            {
                PdfAnnotation dic  = annotations[k];
                int           page = dic.PlaceInPage;
                if (page > currentPage)
                {
                    delayedAnnotations.Add(dic);
                    continue;
                }
                if (dic.IsForm())
                {
                    if (!dic.IsUsed())
                    {
                        Dictionary <PdfTemplate, object> templates = dic.Templates;
                        if (templates != null)
                        {
                            acroForm.AddFieldTemplates(templates);
                        }
                    }
                    PdfFormField field = (PdfFormField)dic;
                    if (field.Parent == null)
                    {
                        acroForm.AddDocumentField(field.IndirectReference);
                    }
                }
                if (dic.IsAnnotation())
                {
                    array.Add(dic.IndirectReference);
                    if (!dic.IsUsed())
                    {
                        PdfArray     tmp = dic.GetAsArray(PdfName.RECT);
                        PdfRectangle rect;
                        if (tmp.Size == 4)
                        {
                            rect = new PdfRectangle(tmp.GetAsNumber(0).FloatValue, tmp.GetAsNumber(1).FloatValue, tmp.GetAsNumber(2).FloatValue, tmp.GetAsNumber(3).FloatValue);
                        }
                        else
                        {
                            rect = new PdfRectangle(tmp.GetAsNumber(0).FloatValue, tmp.GetAsNumber(1).FloatValue);
                        }
                        if (rect != null)
                        {
                            switch (rotation)
                            {
                            case 90:
                                dic.Put(PdfName.RECT, new PdfRectangle(
                                            pageSize.Top - rect.Bottom,
                                            rect.Left,
                                            pageSize.Top - rect.Top,
                                            rect.Right));
                                break;

                            case 180:
                                dic.Put(PdfName.RECT, new PdfRectangle(
                                            pageSize.Right - rect.Left,
                                            pageSize.Top - rect.Bottom,
                                            pageSize.Right - rect.Right,
                                            pageSize.Top - rect.Top));
                                break;

                            case 270:
                                dic.Put(PdfName.RECT, new PdfRectangle(
                                            rect.Bottom,
                                            pageSize.Right - rect.Left,
                                            rect.Top,
                                            pageSize.Right - rect.Right));
                                break;
                            }
                        }
                    }
                }
                if (!dic.IsUsed())
                {
                    dic.SetUsed();
                    writer.AddToBody(dic, dic.IndirectReference);
                }
            }
            return(array);
        }
コード例 #35
0
        /// <summary>Fills the underlying PdfDictionary object with the current layers and their settings.</summary>
        /// <remarks>
        /// Fills the underlying PdfDictionary object with the current layers and their settings.
        /// Note that it completely regenerates the dictionary, so your direct changes to the dictionary
        /// will not take any affect.
        /// </remarks>
        /// <returns>the resultant dictionary</returns>
        public virtual PdfObject FillDictionary()
        {
            PdfArray gr = new PdfArray();

            foreach (PdfLayer layer in layers)
            {
                if (layer.GetTitle() == null)
                {
                    gr.Add(layer.GetIndirectReference());
                }
            }
            GetPdfObject().Put(PdfName.OCGs, gr);
            // Save radio groups.
            PdfArray      rbGroups = null;
            PdfDictionary d        = GetPdfObject().GetAsDictionary(PdfName.D);

            if (d != null)
            {
                rbGroups = d.GetAsArray(PdfName.RBGroups);
            }
            d = new PdfDictionary();
            if (rbGroups != null)
            {
                d.Put(PdfName.RBGroups, rbGroups);
            }
            d.Put(PdfName.Name, new PdfString(CreateUniqueName(), PdfEncodings.UNICODE_BIG));
            GetPdfObject().Put(PdfName.D, d);
            IList <PdfLayer> docOrder = new List <PdfLayer>(layers);

            for (int i = 0; i < docOrder.Count; i++)
            {
                PdfLayer layer = docOrder[i];
                if (layer.GetParent() != null)
                {
                    docOrder.Remove(layer);
                    i--;
                }
            }
            PdfArray order = new PdfArray();

            foreach (Object element in docOrder)
            {
                PdfLayer layer = (PdfLayer)element;
                GetOCGOrder(order, layer);
            }
            d.Put(PdfName.Order, order);
            PdfArray off = new PdfArray();

            foreach (Object element in layers)
            {
                PdfLayer layer = (PdfLayer)element;
                if (layer.GetTitle() == null && !layer.IsOn())
                {
                    off.Add(layer.GetIndirectReference());
                }
            }
            if (off.Size() > 0)
            {
                d.Put(PdfName.OFF, off);
            }
            else
            {
                d.Remove(PdfName.OFF);
            }
            PdfArray locked = new PdfArray();

            foreach (PdfLayer layer in layers)
            {
                if (layer.GetTitle() == null && layer.IsLocked())
                {
                    locked.Add(layer.GetIndirectReference());
                }
            }
            if (locked.Size() > 0)
            {
                d.Put(PdfName.Locked, locked);
            }
            else
            {
                d.Remove(PdfName.Locked);
            }
            d.Remove(PdfName.AS);
            AddASEvent(PdfName.View, PdfName.Zoom);
            AddASEvent(PdfName.View, PdfName.View);
            AddASEvent(PdfName.Print, PdfName.Print);
            AddASEvent(PdfName.Export, PdfName.Export);
            return(GetPdfObject());
        }
コード例 #36
0
        private static PdfStream CreatePdfStream(ImageData image, iText.Kernel.Pdf.Xobject.PdfImageXObject imageMask
                                                 )
        {
            PdfStream stream;

            if (image.GetOriginalType() == ImageType.RAW)
            {
                RawImageHelper.UpdateImageAttributes((RawImageData)image, null);
            }
            stream = new PdfStream(image.GetData());
            String filter = image.GetFilter();

            if (filter != null && filter.Equals("JPXDecode") && image.GetColorSpace() <= 0)
            {
                stream.SetCompressionLevel(CompressionConstants.NO_COMPRESSION);
                image.SetBpc(0);
            }
            stream.Put(PdfName.Type, PdfName.XObject);
            stream.Put(PdfName.Subtype, PdfName.Image);
            PdfDictionary decodeParms = CreateDictionaryFromMap(stream, image.GetDecodeParms());

            if (decodeParms != null)
            {
                stream.Put(PdfName.DecodeParms, decodeParms);
            }
            PdfName colorSpace;

            switch (image.GetColorSpace())
            {
            case 1: {
                colorSpace = PdfName.DeviceGray;
                break;
            }

            case 3: {
                colorSpace = PdfName.DeviceRGB;
                break;
            }

            default: {
                colorSpace = PdfName.DeviceCMYK;
                break;
            }
            }
            stream.Put(PdfName.ColorSpace, colorSpace);
            if (image.GetBpc() != 0)
            {
                stream.Put(PdfName.BitsPerComponent, new PdfNumber(image.GetBpc()));
            }
            if (image.GetFilter() != null)
            {
                stream.Put(PdfName.Filter, new PdfName(image.GetFilter()));
            }
            //TODO: return to this later
            //        if (image.getLayer() != null)
            //            put(PdfName.OC, image.getLayer().getRef());
            if (image.GetColorSpace() == -1)
            {
                stream.Remove(PdfName.ColorSpace);
            }
            PdfDictionary additional = CreateDictionaryFromMap(stream, image.GetImageAttributes());

            if (additional != null)
            {
                stream.PutAll(additional);
            }
            IccProfile iccProfile = image.GetProfile();

            if (iccProfile != null)
            {
                PdfStream iccProfileStream   = PdfCieBasedCs.IccBased.GetIccProfileStream(iccProfile);
                PdfArray  iccBasedColorSpace = new PdfArray();
                iccBasedColorSpace.Add(PdfName.ICCBased);
                iccBasedColorSpace.Add(iccProfileStream);
                PdfObject colorSpaceObject          = stream.Get(PdfName.ColorSpace);
                bool      iccProfileShouldBeApplied = true;
                if (colorSpaceObject != null)
                {
                    PdfColorSpace cs = PdfColorSpace.MakeColorSpace(colorSpaceObject);
                    if (cs == null)
                    {
                        LogManager.GetLogger(typeof(iText.Kernel.Pdf.Xobject.PdfImageXObject)).Error(iText.IO.LogMessageConstant.IMAGE_HAS_INCORRECT_OR_UNSUPPORTED_COLOR_SPACE_OVERRIDDEN_BY_ICC_PROFILE
                                                                                                     );
                    }
                    else
                    {
                        if (cs is PdfSpecialCs.Indexed)
                        {
                            PdfColorSpace baseCs = ((PdfSpecialCs.Indexed)cs).GetBaseCs();
                            if (baseCs == null)
                            {
                                LogManager.GetLogger(typeof(iText.Kernel.Pdf.Xobject.PdfImageXObject)).Error(iText.IO.LogMessageConstant.IMAGE_HAS_INCORRECT_OR_UNSUPPORTED_BASE_COLOR_SPACE_IN_INDEXED_COLOR_SPACE_OVERRIDDEN_BY_ICC_PROFILE
                                                                                                             );
                            }
                            else
                            {
                                if (baseCs.GetNumberOfComponents() != iccProfile.GetNumComponents())
                                {
                                    LogManager.GetLogger(typeof(iText.Kernel.Pdf.Xobject.PdfImageXObject)).Error(iText.IO.LogMessageConstant.IMAGE_HAS_ICC_PROFILE_WITH_INCOMPATIBLE_NUMBER_OF_COLOR_COMPONENTS_COMPARED_TO_BASE_COLOR_SPACE_IN_INDEXED_COLOR_SPACE
                                                                                                                 );
                                    iccProfileShouldBeApplied = false;
                                }
                                else
                                {
                                    iccProfileStream.Put(PdfName.Alternate, baseCs.GetPdfObject());
                                }
                            }
                            if (iccProfileShouldBeApplied)
                            {
                                ((PdfArray)colorSpaceObject).Set(1, iccBasedColorSpace);
                                iccProfileShouldBeApplied = false;
                            }
                        }
                        else
                        {
                            if (cs.GetNumberOfComponents() != iccProfile.GetNumComponents())
                            {
                                LogManager.GetLogger(typeof(iText.Kernel.Pdf.Xobject.PdfImageXObject)).Error(iText.IO.LogMessageConstant.IMAGE_HAS_ICC_PROFILE_WITH_INCOMPATIBLE_NUMBER_OF_COLOR_COMPONENTS_COMPARED_TO_COLOR_SPACE
                                                                                                             );
                                iccProfileShouldBeApplied = false;
                            }
                            else
                            {
                                iccProfileStream.Put(PdfName.Alternate, colorSpaceObject);
                            }
                        }
                    }
                }
                if (iccProfileShouldBeApplied)
                {
                    stream.Put(PdfName.ColorSpace, iccBasedColorSpace);
                }
            }
            if (image.IsMask() && (image.GetBpc() == 1 || image.GetBpc() > 0xff))
            {
                stream.Put(PdfName.ImageMask, PdfBoolean.TRUE);
            }
            if (imageMask != null)
            {
                if (imageMask.softMask)
                {
                    stream.Put(PdfName.SMask, imageMask.GetPdfObject());
                }
                else
                {
                    if (imageMask.mask)
                    {
                        stream.Put(PdfName.Mask, imageMask.GetPdfObject());
                    }
                }
            }
            ImageData mask = image.GetImageMask();

            if (mask != null)
            {
                if (mask.IsSoftMask())
                {
                    stream.Put(PdfName.SMask, new iText.Kernel.Pdf.Xobject.PdfImageXObject(image.GetImageMask()).GetPdfObject(
                                   ));
                }
                else
                {
                    if (mask.IsMask())
                    {
                        stream.Put(PdfName.Mask, new iText.Kernel.Pdf.Xobject.PdfImageXObject(image.GetImageMask()).GetPdfObject()
                                   );
                    }
                }
            }
            if (image.GetDecode() != null)
            {
                stream.Put(PdfName.Decode, new PdfArray(image.GetDecode()));
            }
            if (image.IsMask() && image.IsInverted())
            {
                stream.Put(PdfName.Decode, new PdfArray(new float[] { 1, 0 }));
            }
            if (image.IsInterpolation())
            {
                stream.Put(PdfName.Interpolate, PdfBoolean.TRUE);
            }
            // deal with transparency
            int[] transparency = image.GetTransparency();
            if (transparency != null && !image.IsMask() && imageMask == null)
            {
                PdfArray t = new PdfArray();
                foreach (int transparencyItem in transparency)
                {
                    t.Add(new PdfNumber(transparencyItem));
                }
                stream.Put(PdfName.Mask, t);
            }
            stream.Put(PdfName.Width, new PdfNumber(image.GetWidth()));
            stream.Put(PdfName.Height, new PdfNumber(image.GetHeight()));
            return(stream);
        }
コード例 #37
0
 private void OutputDss(PdfDictionary dss, PdfDictionary vrim, PdfArray ocsps, PdfArray crls, PdfArray certs) {
     writer.AddDeveloperExtension(PdfDeveloperExtension.ESIC_1_7_EXTENSIONLEVEL5);
     PdfDictionary catalog = reader.Catalog;
     stp.MarkUsed(catalog);
     foreach (PdfName vkey in validated.Keys) {
         PdfArray ocsp = new PdfArray();
         PdfArray crl = new PdfArray();
         PdfArray cert = new PdfArray();
         PdfDictionary vri = new PdfDictionary();
         foreach (byte[] b in validated[vkey].crls) {
             PdfStream ps = new PdfStream(b);
             ps.FlateCompress();
             PdfIndirectReference iref = writer.AddToBody(ps, false).IndirectReference;
             crl.Add(iref);
             crls.Add(iref);
         }
         foreach (byte[] b in validated[vkey].ocsps) {
             PdfStream ps = new PdfStream(b);
             ps.FlateCompress();
             PdfIndirectReference iref = writer.AddToBody(ps, false).IndirectReference;
             ocsp.Add(iref);
             ocsps.Add(iref);
         }
         foreach (byte[] b in validated[vkey].certs) {
             PdfStream ps = new PdfStream(b);
             ps.FlateCompress();
             PdfIndirectReference iref = writer.AddToBody(ps, false).IndirectReference;
             cert.Add(iref);
             certs.Add(iref);
         }
         if (ocsp.Size > 0)
             vri.Put(PdfName.OCSP, writer.AddToBody(ocsp, false).IndirectReference);
         if (crl.Size > 0)
             vri.Put(PdfName.CRL, writer.AddToBody(crl, false).IndirectReference);
         if (cert.Size > 0)
             vri.Put(PdfName.CERT, writer.AddToBody(cert, false).IndirectReference);
         vrim.Put(vkey, writer.AddToBody(vri, false).IndirectReference);
     }
     dss.Put(PdfName.VRI, writer.AddToBody(vrim, false).IndirectReference);
     if (ocsps.Size > 0)
         dss.Put(PdfName.OCSPS, writer.AddToBody(ocsps, false).IndirectReference);
     if (crls.Size > 0)
         dss.Put(PdfName.CRLS, writer.AddToBody(crls, false).IndirectReference);
     if (certs.Size > 0)
         dss.Put(PdfName.CERTS, writer.AddToBody(certs, false).IndirectReference);
     catalog.Put(PdfName.DSS, writer.AddToBody(dss, false).IndirectReference);
 }
コード例 #38
0
ファイル: PngImage.cs プロジェクト: pixelia-es/RazorPDF2
        void ReadPng()
        {
            for (int i = 0; i < PNGID.Length; i++) {
                if (PNGID[i] != isp.ReadByte())	{
                    throw new IOException("File is not a valid PNG.");
                }
            }
            byte[] buffer = new byte[TRANSFERSIZE];
            while (true) {
                int len = GetInt(isp);
                String marker = GetString(isp);
                if (len < 0 || !CheckMarker(marker))
                    throw new IOException("Corrupted PNG file.");
                if (IDAT.Equals(marker)) {
                    int size;
                    while (len != 0) {
                        size = isp.Read(buffer, 0, Math.Min(len, TRANSFERSIZE));
                        if (size <= 0)
                            return;
                        idat.Write(buffer, 0, size);
                        len -= size;
                    }
                }
                else if (tRNS.Equals(marker)) {
                    switch (colorType) {
                        case 0:
                            if (len >= 2) {
                                len -= 2;
                                int gray = GetWord(isp);
                                if (bitDepth == 16)
                                    transRedGray = gray;
                                else
                                    additional.Put(PdfName.MASK, new PdfLiteral("["+gray+" "+gray+"]"));
                            }
                            break;
                        case 2:
                            if (len >= 6) {
                                len -= 6;
                                int red = GetWord(isp);
                                int green = GetWord(isp);
                                int blue = GetWord(isp);
                                if (bitDepth == 16) {
                                    transRedGray = red;
                                    transGreen = green;
                                    transBlue = blue;
                                }
                                else
                                    additional.Put(PdfName.MASK, new PdfLiteral("["+red+" "+red+" "+green+" "+green+" "+blue+" "+blue+"]"));
                            }
                            break;
                        case 3:
                            if (len > 0) {
                                trans = new byte[len];
                                for (int k = 0; k < len; ++k)
                                    trans[k] = (byte)isp.ReadByte();
                                len = 0;
                            }
                            break;
                    }
                    Utilities.Skip(isp, len);
                }
                else if (IHDR.Equals(marker)) {
                    width = GetInt(isp);
                    height = GetInt(isp);

                    bitDepth = isp.ReadByte();
                    colorType = isp.ReadByte();
                    compressionMethod = isp.ReadByte();
                    filterMethod = isp.ReadByte();
                    interlaceMethod = isp.ReadByte();
                }
                else if (PLTE.Equals(marker)) {
                    if (colorType == 3) {
                        PdfArray colorspace = new PdfArray();
                        colorspace.Add(PdfName.INDEXED);
                        colorspace.Add(GetColorspace());
                        colorspace.Add(new PdfNumber(len / 3 - 1));
                        ByteBuffer colortable = new ByteBuffer();
                        while ((len--) > 0) {
                            colortable.Append_i(isp.ReadByte());
                        }
                        colorspace.Add(new PdfString(colorTable = colortable.ToByteArray()));
                        additional.Put(PdfName.COLORSPACE, colorspace);
                    }
                    else {
                        Utilities.Skip(isp, len);
                    }
                }
                else if (pHYs.Equals(marker)) {
                    int dx = GetInt(isp);
                    int dy = GetInt(isp);
                    int unit = isp.ReadByte();
                    if (unit == 1) {
                        dpiX = (int)((float)dx * 0.0254f + 0.5f);
                        dpiY = (int)((float)dy * 0.0254f + 0.5f);
                    }
                    else {
                        if (dy != 0)
                            XYRatio = (float)dx / (float)dy;
                    }
                }
                else if (cHRM.Equals(marker)) {
                    xW = (float)GetInt(isp) / 100000f;
                    yW = (float)GetInt(isp) / 100000f;
                    xR = (float)GetInt(isp) / 100000f;
                    yR = (float)GetInt(isp) / 100000f;
                    xG = (float)GetInt(isp) / 100000f;
                    yG = (float)GetInt(isp) / 100000f;
                    xB = (float)GetInt(isp) / 100000f;
                    yB = (float)GetInt(isp) / 100000f;
                    hasCHRM = !(Math.Abs(xW)<0.0001f||Math.Abs(yW)<0.0001f||Math.Abs(xR)<0.0001f||Math.Abs(yR)<0.0001f||Math.Abs(xG)<0.0001f||Math.Abs(yG)<0.0001f||Math.Abs(xB)<0.0001f||Math.Abs(yB)<0.0001f);
                }
                else if (sRGB.Equals(marker)) {
                    int ri = isp.ReadByte();
                    intent = intents[ri];
                    gamma = 2.2f;
                    xW = 0.3127f;
                    yW = 0.329f;
                    xR = 0.64f;
                    yR = 0.33f;
                    xG = 0.3f;
                    yG = 0.6f;
                    xB = 0.15f;
                    yB = 0.06f;
                    hasCHRM = true;
                }
                else if (gAMA.Equals(marker)) {
                    int gm = GetInt(isp);
                    if (gm != 0) {
                        gamma = 100000f / (float)gm;
                        if (!hasCHRM) {
                            xW = 0.3127f;
                            yW = 0.329f;
                            xR = 0.64f;
                            yR = 0.33f;
                            xG = 0.3f;
                            yG = 0.6f;
                            xB = 0.15f;
                            yB = 0.06f;
                            hasCHRM = true;
                        }
                    }
                }
                else if (iCCP.Equals(marker)) {
                    do {
                        --len;
                    } while (isp.ReadByte() != 0);
                    isp.ReadByte();
                    --len;
                    byte[] icccom = new byte[len];
                    int p = 0;
                    while (len > 0) {
                        int r = isp.Read(icccom, p, len);
                        if (r < 0)
                            throw new IOException("Premature end of file.");
                        p += r;
                        len -= r;
                    }
                    byte[] iccp = PdfReader.FlateDecode(icccom, true);
                    icccom = null;
                    try {
                        icc_profile = ICC_Profile.GetInstance(iccp);
                    }
                    catch {
                        icc_profile = null;
                    }
                }
                else if (IEND.Equals(marker)) {
                    break;
                }
                else {
                    Utilities.Skip(isp, len);
                }
                Utilities.Skip(isp, 4);
            }
        }
コード例 #39
0
ファイル: PngImage.cs プロジェクト: pixelia-es/RazorPDF2
 PdfObject GetColorspace()
 {
     if (icc_profile != null) {
         if ((colorType & 2) == 0)
             return PdfName.DEVICEGRAY;
         else
             return PdfName.DEVICERGB;
     }
     if (gamma == 1f && !hasCHRM) {
         if ((colorType & 2) == 0)
             return PdfName.DEVICEGRAY;
         else
             return PdfName.DEVICERGB;
     }
     else {
         PdfArray array = new PdfArray();
         PdfDictionary dic = new PdfDictionary();
         if ((colorType & 2) == 0) {
             if (gamma == 1f)
                 return PdfName.DEVICEGRAY;
             array.Add(PdfName.CALGRAY);
             dic.Put(PdfName.GAMMA, new PdfNumber(gamma));
             dic.Put(PdfName.WHITEPOINT, new PdfLiteral("[1 1 1]"));
             array.Add(dic);
         }
         else {
             PdfObject wp = new PdfLiteral("[1 1 1]");
             array.Add(PdfName.CALRGB);
             if (gamma != 1f) {
                 PdfArray gm = new PdfArray();
                 PdfNumber n = new PdfNumber(gamma);
                 gm.Add(n);
                 gm.Add(n);
                 gm.Add(n);
                 dic.Put(PdfName.GAMMA, gm);
             }
             if (hasCHRM) {
                 float z = yW*((xG-xB)*yR-(xR-xB)*yG+(xR-xG)*yB);
                 float YA = yR*((xG-xB)*yW-(xW-xB)*yG+(xW-xG)*yB)/z;
                 float XA = YA*xR/yR;
                 float ZA = YA*((1-xR)/yR-1);
                 float YB = -yG*((xR-xB)*yW-(xW-xB)*yR+(xW-xR)*yB)/z;
                 float XB = YB*xG/yG;
                 float ZB = YB*((1-xG)/yG-1);
                 float YC = yB*((xR-xG)*yW-(xW-xG)*yW+(xW-xR)*yG)/z;
                 float XC = YC*xB/yB;
                 float ZC = YC*((1-xB)/yB-1);
                 float XW = XA+XB+XC;
                 float YW = 1;//YA+YB+YC;
                 float ZW = ZA+ZB+ZC;
                 PdfArray wpa = new PdfArray();
                 wpa.Add(new PdfNumber(XW));
                 wpa.Add(new PdfNumber(YW));
                 wpa.Add(new PdfNumber(ZW));
                 wp = wpa;
                 PdfArray matrix = new PdfArray();
                 matrix.Add(new PdfNumber(XA));
                 matrix.Add(new PdfNumber(YA));
                 matrix.Add(new PdfNumber(ZA));
                 matrix.Add(new PdfNumber(XB));
                 matrix.Add(new PdfNumber(YB));
                 matrix.Add(new PdfNumber(ZB));
                 matrix.Add(new PdfNumber(XC));
                 matrix.Add(new PdfNumber(YC));
                 matrix.Add(new PdfNumber(ZC));
                 dic.Put(PdfName.MATRIX, matrix);
             }
             dic.Put(PdfName.WHITEPOINT, wp);
             array.Add(dic);
         }
         return array;
     }
 }
コード例 #40
0
 public void SetMatrix(float a, float b, float c, float d, float e, float f) {
     matrix = new PdfArray();
     matrix.Add(new PdfNumber(a));
     matrix.Add(new PdfNumber(b));
     matrix.Add(new PdfNumber(c));
     matrix.Add(new PdfNumber(d));
     matrix.Add(new PdfNumber(e));
     matrix.Add(new PdfNumber(f));
 }
コード例 #41
0
ファイル: CompositeFont.cs プロジェクト: n9/pdfclown
        /**
          <summary>Creates the character code mapping for composite fonts.</summary>
        */
        private void Load_CreateEncoding(
            PdfDictionary font,
            PdfDictionary cidFont
            )
        {
            // CMap [PDF:1.6:5.6.4].
              bytes::Buffer cmapBuffer = new bytes::Buffer();
              cmapBuffer.Append(
            "%!PS-Adobe-3.0 Resource-CMap\n"
              + "%%DocumentNeededResources: ProcSet (CIDInit)\n"
              + "%%IncludeResource: ProcSet (CIDInit)\n"
              + "%%BeginResource: CMap (Adobe-Identity-UCS)\n"
              + "%%Title: (Adobe-Identity-UCS Adobe Identity 0)\n"
              + "%%Version: 1\n"
              + "%%EndComments\n"
              + "/CIDInit /ProcSet findresource begin\n"
              + "12 dict begin\n"
              + "begincmap\n"
              + "/CIDSystemInfo\n"
              + "3 dict dup begin\n"
              + "/Registry (Adobe) def\n"
              + "/Ordering (Identity) def\n"
              + "/Supplement 0 def\n"
              + "end def\n"
              + "/CMapName /Adobe-Identity-UCS def\n"
              + "/CMapVersion 1 def\n"
              + "/CMapType 0 def\n"
              + "/WMode 0 def\n"
              + "2 begincodespacerange\n"
              + "<20> <20>\n"
              + "<0000> <19FF>\n"
              + "endcodespacerange\n"
              + glyphIndexes.Count + " begincidchar\n"
            );
              // ToUnicode [PDF:1.6:5.9.2].
              bytes::Buffer toUnicodeBuffer = new bytes::Buffer();
              toUnicodeBuffer.Append(
            "/CIDInit /ProcSet findresource begin\n"
              + "12 dict begin\n"
              + "begincmap\n"
              + "/CIDSystemInfo\n"
              + "<< /Registry (Adobe)\n"
              + "/Ordering (UCS)\n"
              + "/Supplement 0\n"
              + ">> def\n"
              + "/CMapName /Adobe-Identity-UCS def\n"
              + "/CMapVersion 10.001 def\n"
              + "/CMapType 2 def\n"
              + "2 begincodespacerange\n"
              + "<20> <20>\n"
              + "<0000> <19FF>\n"
              + "endcodespacerange\n"
              + glyphIndexes.Count + " beginbfchar\n"
            );
              // CIDToGIDMap [PDF:1.6:5.6.3].
              bytes::Buffer gIdBuffer = new bytes::Buffer();
              gIdBuffer.Append((byte)0);
              gIdBuffer.Append((byte)0);
              int code = 0;
              codes = new BiDictionary<ByteArray,int>(glyphIndexes.Count);
              PdfArray widthsObject = new PdfArray(glyphWidths.Count);
              foreach(KeyValuePair<int,int> glyphIndexEntry in glyphIndexes)
              {
            // Character code (unicode to codepoint) entry.
            code++;
            byte[] charCode = (glyphIndexEntry.Key == 32
              ? new byte[]{32}
              : new byte[]
            {
              (byte)((code >> 8) & 0xFF),
              (byte)(code & 0xFF)
            });
            codes[new ByteArray(charCode)] = glyphIndexEntry.Key;

            // CMap entry.
            cmapBuffer.Append("<");
            toUnicodeBuffer.Append("<");
            for(int charCodeBytesIndex = 0,
            charCodeBytesLength = charCode.Length;
              charCodeBytesIndex < charCodeBytesLength;
              charCodeBytesIndex++
              )
            {
              string hex = ((int)charCode[charCodeBytesIndex]).ToString("X2");
              cmapBuffer.Append(hex);
              toUnicodeBuffer.Append(hex);
            }
            cmapBuffer.Append("> " + code + "\n");
            toUnicodeBuffer.Append("> <" + glyphIndexEntry.Key.ToString("X4") + ">\n");

            // CID-to-GID entry.
            int glyphIndex = glyphIndexEntry.Value;
            gIdBuffer.Append((byte)((glyphIndex >> 8) & 0xFF));
            gIdBuffer.Append((byte)(glyphIndex & 0xFF));

            // Width.
            int width;
            if(!glyphWidths.TryGetValue(glyphIndex, out width))
            {width = 0;}
            else if(width > 1000)
            {width = 1000;}
            widthsObject.Add(PdfInteger.Get(width));
              }
              cmapBuffer.Append(
            "endcidchar\n"
              + "endcmap\n"
              + "CMapName currentdict /CMap defineresource pop\n"
              + "end\n"
              + "end\n"
              + "%%EndResource\n"
              + "%%EOF"
            );
              PdfStream cmapStream = new PdfStream(cmapBuffer);
              PdfDictionary cmapHead = cmapStream.Header;
              cmapHead[PdfName.Type] = PdfName.CMap;
              cmapHead[PdfName.CMapName] = new PdfName("Adobe-Identity-UCS");
              cmapHead[PdfName.CIDSystemInfo] = new PdfDictionary(
            new PdfName[]
            {
              PdfName.Registry,
              PdfName.Ordering,
              PdfName.Supplement
            },
            new PdfDirectObject[]
            {
              new PdfTextString("Adobe"),
              new PdfTextString("Identity"),
              PdfInteger.Get(0)
            }
            ); // Generic predefined CMap (Identity-H/V (Adobe-Identity-0)) [PDF:1.6:5.6.4].
              font[PdfName.Encoding] = File.Register(cmapStream);

              PdfStream gIdStream = new PdfStream(gIdBuffer);
              cidFont[PdfName.CIDToGIDMap] = File.Register(gIdStream);

              cidFont[PdfName.W] = new PdfArray(new PdfDirectObject[]{PdfInteger.Get(1),widthsObject});

              toUnicodeBuffer.Append(
            "endbfchar\n"
              + "endcmap\n"
              + "CMapName currentdict /CMap defineresource pop\n"
              + "end\n"
              + "end\n"
            );
              PdfStream toUnicodeStream = new PdfStream(toUnicodeBuffer);
              font[PdfName.ToUnicode] = File.Register(toUnicodeStream);
        }
コード例 #42
0
ファイル: BaseParser.cs プロジェクト: josuecorrea/DanfeSharp
   /**
     <summary>Parses the current PDF object [PDF:1.6:3.2].</summary>
   */
   public virtual PdfDataObject ParsePdfObject(
 )
   {
       switch(TokenType)
         {
       case TokenTypeEnum.Integer:
         return PdfInteger.Get((int)Token);
       case TokenTypeEnum.Name:
         return new PdfName((string)Token,true);
       case TokenTypeEnum.DictionaryBegin:
       {
         PdfDictionary dictionary = new PdfDictionary();
         dictionary.Updateable = false;
         while(true)
         {
       // Key.
       MoveNext(); if(TokenType == TokenTypeEnum.DictionaryEnd) break;
       PdfName key = (PdfName)ParsePdfObject();
       // Value.
       MoveNext();
       PdfDirectObject value = (PdfDirectObject)ParsePdfObject();
       // Add the current entry to the dictionary!
       dictionary[key] = value;
         }
         dictionary.Updateable = true;
         return dictionary;
       }
       case TokenTypeEnum.ArrayBegin:
       {
         PdfArray array = new PdfArray();
         array.Updateable = false;
         while(true)
         {
       // Value.
       MoveNext(); if(TokenType == TokenTypeEnum.ArrayEnd) break;
       // Add the current item to the array!
       array.Add((PdfDirectObject)ParsePdfObject());
         }
         array.Updateable = true;
         return array;
       }
       case TokenTypeEnum.Literal:
         if(Token is DateTime)
       return PdfDate.Get((DateTime)Token);
         else
       return new PdfTextString(
         Encoding.Pdf.Encode((string)Token)
         );
       case TokenTypeEnum.Hex:
         return new PdfTextString(
       (string)Token,
       PdfString.SerializationModeEnum.Hex
       );
       case TokenTypeEnum.Real:
         return PdfReal.Get((double)Token);
       case TokenTypeEnum.Boolean:
         return PdfBoolean.Get((bool)Token);
       case TokenTypeEnum.Null:
         return null;
       default:
         throw new Exception("Unknown type: " + TokenType);
         }
   }
コード例 #43
0
ファイル: PdfPages.cs プロジェクト: leofidus/itext7-dotnet
 public virtual void AddPage(PdfDictionary page)
 {
     kids.Add(page);
     IncrementCount();
     page.Put(PdfName.Parent, GetPdfObject());
 }
コード例 #44
0
ファイル: BmpImage.cs プロジェクト: red-gate/iTextSharp-4.1.6
 private Image IndexedModel(byte[] bdata, int bpc, int paletteEntries) {
     Image img = new ImgRaw(width, height, 1, bpc, bdata);
     PdfArray colorspace = new PdfArray();
     colorspace.Add(PdfName.INDEXED);
     colorspace.Add(PdfName.DEVICERGB);
     byte[] np = GetPalette(paletteEntries);
     int len = np.Length;
     colorspace.Add(new PdfNumber(len / 3 - 1));
     colorspace.Add(new PdfString(np));
     PdfDictionary ad = new PdfDictionary();
     ad.Put(PdfName.COLORSPACE, colorspace);
     img.Additional = ad;
     return img;
 }
コード例 #45
0
ファイル: PointData.cs プロジェクト: mohsenmetn/itextsharp
 /**
  * Adds a point to the Point Data dictionary.
  * @param value an XPTS value
  * @param identifier
  */
 public void AddXPTSValue(PdfNumber value, PtIdentifier identifier)
 {
     xpts.Add(value);
     names.Add(DecodeUnits.Decode(identifier));
 }