Beispiel #1
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;
     }
 }
Beispiel #2
0
 /**
  * Creates a StructureMCID using an MCID.
  * @param obj	an MCID
  */
 public StructureMCID(PdfIndirectReference pg, PdfNumber mcid)
 {
     this.pageref = pg.Number;
     this.mcid    = mcid.IntValue;
 }
Beispiel #3
0
 public void setOrientation(PdfNumber orientation)
 {
     this.orientation = orientation;
 }
Beispiel #4
0
 /**
  * Adds a point to the Point Data dictionary.
  * @param value an XPTS value
  * @param identifier
  */
 virtual public void AddXPTSValue(PdfNumber value, PtIdentifier identifier)
 {
     xpts.Add(value);
     names.Add(DecodeUnits.Decode(identifier));
 }
Beispiel #5
0
        /**
         * Removes a StructParent from the parent tree.
         * @param	PdfNumber	the number to remove
         */

        public virtual void RemoveFromParentTree(PdfNumber structParent)
        {
            parentTree.Remove(structParent.IntValue);
        }
Beispiel #6
0
            virtual public void Invoke(PdfContentStreamProcessor processor, PdfLiteral oper, List <PdfObject> operands)
            {
                PdfNumber scale = (PdfNumber)operands[0];

                processor.Gs().horizontalScaling = scale.FloatValue / 100f;
            }
        internal static Type1Font CreateFontProgram(PdfDictionary fontDictionary, FontEncoding fontEncoding, CMapToUnicode
                                                    toUnicode)
        {
            PdfName baseFontName = fontDictionary.GetAsName(PdfName.BaseFont);
            String  baseFont;

            if (baseFontName != null)
            {
                baseFont = baseFontName.GetValue();
            }
            else
            {
                baseFont = FontUtil.CreateRandomFontName();
            }
            if (!fontDictionary.ContainsKey(PdfName.FontDescriptor))
            {
                Type1Font type1StdFont;
                try {
                    //if there are no font modifiers, cached font could be used,
                    //otherwise a new instance should be created.
                    type1StdFont = (Type1Font)FontProgramFactory.CreateFont(baseFont, true);
                }
                catch (Exception) {
                    type1StdFont = null;
                }
                if (type1StdFont != null)
                {
                    return(type1StdFont);
                }
            }
            iText.Kernel.Font.DocType1Font fontProgram = new iText.Kernel.Font.DocType1Font(baseFont);
            PdfDictionary fontDesc = fontDictionary.GetAsDictionary(PdfName.FontDescriptor);

            fontProgram.subtype = fontDesc != null?fontDesc.GetAsName(PdfName.Subtype) : null;

            FillFontDescriptor(fontProgram, fontDesc);
            PdfNumber firstCharNumber = fontDictionary.GetAsNumber(PdfName.FirstChar);
            int       firstChar       = firstCharNumber != null?Math.Max(firstCharNumber.IntValue(), 0) : 0;

            int[] widths = FontUtil.ConvertSimpleWidthsArray(fontDictionary.GetAsArray(PdfName.Widths), firstChar, fontProgram
                                                             .GetMissingWidth());
            fontProgram.avgWidth = 0;
            int glyphsWithWidths = 0;

            for (int i = 0; i < 256; i++)
            {
                Glyph glyph = new Glyph(i, widths[i], fontEncoding.GetUnicode(i));
                fontProgram.codeToGlyph.Put(i, glyph);
                if (glyph.HasValidUnicode())
                {
                    //FontEncoding.codeToUnicode table has higher priority
                    if (fontEncoding.ConvertToByte(glyph.GetUnicode()) == i)
                    {
                        fontProgram.unicodeToGlyph.Put(glyph.GetUnicode(), glyph);
                    }
                }
                else
                {
                    if (toUnicode != null)
                    {
                        glyph.SetChars(toUnicode.Lookup(i));
                    }
                }
                if (widths[i] > 0)
                {
                    glyphsWithWidths++;
                    fontProgram.avgWidth += widths[i];
                }
            }
            if (glyphsWithWidths != 0)
            {
                fontProgram.avgWidth /= glyphsWithWidths;
            }
            return(fontProgram);
        }
Beispiel #8
0
        public void OneFile_LinksToTheNextFile_UpdatesLink(string exeFileName)
        {
            HtmlToPdfRunner runner = new HtmlToPdfRunner(exeFileName);

            string htmlFile2Contents = @"
<html>
  <head>
  </head>
  <body>
   Page 2
  </body>
</html>";

            using (TempHtmlFile htmlFile2 = new TempHtmlFile(htmlFile2Contents))
            {
                string htmlFile1Contents = $@"
<html>
  <head>
  </head>
  <body>
   Page 1
   <br/>
   <a href=""{htmlFile2.FilePath}"">Page 2</a>
  </body>
</html>";
                using (TempHtmlFile htmlFile1 = new TempHtmlFile(htmlFile1Contents))
                {
                    using (TempPdfFile pdfFile = new TempPdfFile(this.TestContext))
                    {
                        string             commandLine = $"\"{htmlFile1.FilePath}\" \"{htmlFile2.FilePath}\" \"{pdfFile.FilePath}\"";
                        HtmlToPdfRunResult result      = runner.Run(commandLine);
                        Assert.AreEqual(0, result.ExitCode, result.Output);

                        using (PdfReader pdfReader = new PdfReader(pdfFile.FilePath))
                        {
                            using (PdfDocument pdfDocument = new PdfDocument(pdfReader))
                            {
                                Assert.AreEqual(2, pdfDocument.GetNumberOfPages());

                                // get the first page
                                PdfPage pdfPage = pdfDocument.GetPage(1);

                                // get link annotations
                                List <PdfLinkAnnotation> linkAnnotations = pdfPage.GetAnnotations().OfType <PdfLinkAnnotation>().ToList();
                                Assert.AreEqual(1, linkAnnotations.Count);

                                // get the first link annotation
                                PdfLinkAnnotation linkAnnotation = linkAnnotations.ElementAt(0);
                                Assert.IsNotNull(linkAnnotation);

                                // get action
                                PdfDictionary action = linkAnnotation.GetAction();
                                Assert.IsNotNull(action);

                                // get GoTo sub-type
                                PdfName s = action.GetAsName(PdfName.S);

                                if (exeFileName == HtmlToPdfRunner.HtmlToPdfExe)
                                {
                                    Assert.AreEqual(PdfName.GoTo, s);

                                    // get destination
                                    PdfArray             destination = action.GetAsArray(PdfName.D);
                                    PdfIndirectReference destinationPageReference = destination.GetAsDictionary(0).GetIndirectReference();
                                    PdfName   zoom       = destination.GetAsName(1);
                                    PdfNumber pageOffset = destination.GetAsNumber(2);

                                    // get expected values
                                    PdfPage              pdfPage2              = pdfDocument.GetPage(2);
                                    PdfDictionary        page2Dictionary       = pdfPage2.GetPdfObject();
                                    PdfIndirectReference expectedPageReference = page2Dictionary.GetIndirectReference();
                                    PdfName              expectedZoom          = PdfName.FitH;
                                    float expectedPageOffset = pdfPage2.GetPageSize().GetTop();

                                    // assert
                                    Assert.AreEqual(expectedPageReference, destinationPageReference);
                                    Assert.AreEqual(expectedZoom, zoom);
                                    Assert.AreEqual(expectedPageOffset, pageOffset.FloatValue());
                                }
                                else if (exeFileName == HtmlToPdfRunner.WkhtmltopdfExe)
                                {
                                    Assert.AreEqual(PdfName.URI, s);

                                    PdfString uri = action.GetAsString(PdfName.URI);
                                    Assert.AreEqual(htmlFile2.FilePath, HttpUtility.UrlDecode(uri.ToString()));
                                }
                            }
                        }
                    }
                }
            }
        }
Beispiel #9
0
        internal static PdfObject CombineAttributesList(PdfObject attributesObject, int insertIndex, IList <PdfStructureAttributes
                                                                                                            > newAttributesList, PdfNumber revision)
        {
            PdfObject combinedAttributes;

            if (attributesObject is PdfDictionary)
            {
                PdfArray combinedAttributesArray = new PdfArray();
                combinedAttributesArray.Add(attributesObject);
                AddNewAttributesToAttributesArray(insertIndex, newAttributesList, revision, combinedAttributesArray);
                combinedAttributes = combinedAttributesArray;
            }
            else
            {
                if (attributesObject is PdfArray)
                {
                    PdfArray combinedAttributesArray = (PdfArray)attributesObject;
                    AddNewAttributesToAttributesArray(insertIndex, newAttributesList, revision, combinedAttributesArray);
                    combinedAttributes = combinedAttributesArray;
                }
                else
                {
                    if (newAttributesList.Count == 1)
                    {
                        if (insertIndex > 0)
                        {
                            throw new IndexOutOfRangeException();
                        }
                        combinedAttributes = newAttributesList[0].GetPdfObject();
                    }
                    else
                    {
                        combinedAttributes = new PdfArray();
                        AddNewAttributesToAttributesArray(insertIndex, newAttributesList, revision, (PdfArray)combinedAttributes);
                    }
                }
            }
            return(combinedAttributes);
        }
Beispiel #10
0
        public override int GetMcid()
        {
            PdfNumber mcidNumber = ((PdfDictionary)GetPdfObject()).GetAsNumber(PdfName.MCID);

            return(mcidNumber != null?mcidNumber.IntValue() : -1);
        }
Beispiel #11
0
 protected internal abstract void CheckPdfNumber(PdfNumber number);
Beispiel #12
0
 /**
  * The conversion factor used to multiply a value in partial units of the
  * previous number format array element to obtain a value in the units of
  * this dictionary. When this entry is in the first number format in the
  * array, its meaning (that is, what it shall be multiplied by) depends on
  * which entry in the RectilinearMeasure references the NumberFormat
  * array.
  *
  * @param n
  */
 virtual public void SetConversionFactor(PdfNumber n)
 {
     base.Put(PdfName.C, n);
 }
Beispiel #13
0
 /**
  * A positive integer that shall specify the precision or denominator of a
  * fractional amount:
  * <ul>
  * <li>
  * When the Fractional Value is {@link Fraction#DECIMAL}, this entry shall
  * be the precision of a decimal display; it shall be a multiple of 10.
  * Low-order zeros may be truncated unless FixedDenominator is true. Default
  * value: 100 (hundredths, corresponding to two decimal digits).</li>
  * <li>When the value of F is {@link Fraction#FRACTION}, this entry shall be
  * the denominator of a fractional display. The fraction may be reduced
  * unless the value of FD is true. Default value: 16.</li>
  * </ul>
  *
  * @param precision
  */
 virtual public void SetPrecision(PdfNumber precision)
 {
     base.Put(PdfName.D, precision);
 }
Beispiel #14
0
        /// <summary>Updates current graphic state with values from extended graphic state dictionary.</summary>
        /// <param name="extGState">the wrapper around the extended graphic state dictionary</param>
        /// <param name="pdfDocument">the document to retrieve fonts from. Needed when the newly created fonts are used
        ///     </param>
        internal virtual void UpdateFromExtGState(PdfExtGState extGState, PdfDocument pdfDocument)
        {
            float?lw = extGState.GetLineWidth();

            if (lw != null)
            {
                lineWidth = (float)lw;
            }
            int?lc = extGState.GetLineCapStyle();

            if (lc != null)
            {
                lineCapStyle = (int)lc;
            }
            int?lj = extGState.GetLineJoinStyle();

            if (lj != null)
            {
                lineJoinStyle = (int)lj;
            }
            float?ml = extGState.GetMiterLimit();

            if (ml != null)
            {
                miterLimit = (float)ml;
            }
            PdfArray d = extGState.GetDashPattern();

            if (d != null)
            {
                dashPattern = d;
            }
            PdfName ri = extGState.GetRenderingIntent();

            if (ri != null)
            {
                renderingIntent = ri;
            }
            bool?op = extGState.GetStrokeOverprintFlag();

            if (op != null)
            {
                strokeOverprint = (bool)op;
            }
            op = extGState.GetFillOverprintFlag();
            if (op != null)
            {
                fillOverprint = (bool)op;
            }
            int?opm = extGState.GetOverprintMode();

            if (opm != null)
            {
                overprintMode = (int)opm;
            }
            PdfArray fnt = extGState.GetFont();

            if (fnt != null)
            {
                PdfDictionary fontDictionary = fnt.GetAsDictionary(0);
                if (this.font == null || this.font.GetPdfObject() != fontDictionary)
                {
                    this.font = pdfDocument.GetFont(fontDictionary);
                }
                PdfNumber fntSz = fnt.GetAsNumber(1);
                if (fntSz != null)
                {
                    this.fontSize = fntSz.FloatValue();
                }
            }
            PdfObject bg = extGState.GetBlackGenerationFunction();

            if (bg != null)
            {
                blackGenerationFunction = bg;
            }
            PdfObject bg2 = extGState.GetBlackGenerationFunction2();

            if (bg2 != null)
            {
                blackGenerationFunction2 = bg2;
            }
            PdfObject ucr = extGState.GetUndercolorRemovalFunction();

            if (ucr != null)
            {
                underColorRemovalFunction = ucr;
            }
            PdfObject ucr2 = extGState.GetUndercolorRemovalFunction2();

            if (ucr2 != null)
            {
                underColorRemovalFunction2 = ucr2;
            }
            PdfObject tr = extGState.GetTransferFunction();

            if (tr != null)
            {
                transferFunction = tr;
            }
            PdfObject tr2 = extGState.GetTransferFunction2();

            if (tr2 != null)
            {
                transferFunction2 = tr2;
            }
            PdfObject ht = extGState.GetHalftone();

            if (ht != null)
            {
                halftone = ht;
            }
            PdfObject local_htp = extGState.GetPdfObject().Get(PdfName.HTP);

            if (local_htp != null)
            {
                this.htp = local_htp;
            }
            float?fl = extGState.GetFlatnessTolerance();

            if (fl != null)
            {
                flatnessTolerance = (float)fl;
            }
            float?sm = extGState.GetSmothnessTolerance();

            if (sm != null)
            {
                smoothnessTolerance = sm;
            }
            bool?sa = extGState.GetAutomaticStrokeAdjustmentFlag();

            if (sa != null)
            {
                automaticStrokeAdjustment = (bool)sa;
            }
            PdfObject bm = extGState.GetBlendMode();

            if (bm != null)
            {
                blendMode = bm;
            }
            PdfObject sMask = extGState.GetSoftMask();

            if (sMask != null)
            {
                softMask = sMask;
            }
            float?ca = extGState.GetStrokeOpacity();

            if (ca != null)
            {
                strokeAlpha = (float)ca;
            }
            ca = extGState.GetFillOpacity();
            if (ca != null)
            {
                fillAlpha = (float)ca;
            }
            bool?ais = extGState.GetAlphaSourceFlag();

            if (ais != null)
            {
                alphaIsShape = (bool)ais;
            }
            bool?tk = extGState.GetTextKnockoutFlag();

            if (tk != null)
            {
                textKnockout = (bool)tk;
            }
        }
Beispiel #15
0
 /**
  * When an MCID is encountered, the parser will check the list
  * structure items and turn an annotation into an XObject if
  * necessary.
  * @param mcid	the MCID that was encountered in the content stream
  * @throws IOException
  */
 virtual protected void DealWithMcid(PdfNumber mcid)
 {
     if (mcid == null)
         return;
     StructureItem item = items[0];
     LOGGER.Info(String.Format("Encountered MCID {0} in content, comparing with {1}", mcid, item));
     switch (item.CheckMCID(pageref.Number, mcid.IntValue))
     {
         case 0:
             StructureObject obj = (StructureObject) item;
             ConvertToXObject(obj);
             LOGGER.Info("Removed structure item from stack.");
             items.RemoveAt(0);
             DealWithMcid(mcid);
             return;
         case 1:
             LOGGER.Info("Removed structure item from stack.");
             items.RemoveAt(0);
             return;
         default:
             LOGGER.Warn("MCID not found! There's probably an error in your form!");
             // hack to deal with MCIDs that are added in the wrong order
             int check;
             for (int i = 1; i < items.Count; i++)
             {
                 item = items[i];
                 check = item.CheckMCID(pageref.Number, mcid.IntValue);
                 switch (check)
                 {
                     case 1:
                         LOGGER.Info("Removed structure item from stack.");
                         items.RemoveAt(i);
                         return;
                     case 0:
                         break;
                 }
             }
             throw new DocumentException(MessageLocalization.GetComposedMessage("can.t.read.document.structure"));
     }
 }
Beispiel #16
0
        public virtual float?GetValueAsFloat()
        {
            PdfNumber num = GetPdfObject().GetAsNumber(PdfName.V);

            return(num != null ? (float?)num.FloatValue() : (float?)null);
        }
Beispiel #17
0
            private static PdfDictionary MakeType2(PdfArray domain, PdfArray range, PdfArray c0, PdfArray c1, PdfNumber
                                                   n)
            {
                PdfDictionary dictionary = new PdfDictionary();

                dictionary.Put(PdfName.FunctionType, new PdfNumber(2));
                dictionary.Put(PdfName.Domain, domain);
                if (range != null)
                {
                    dictionary.Put(PdfName.Range, range);
                }
                if (c0 != null)
                {
                    dictionary.Put(PdfName.C0, c0);
                }
                if (c1 != null)
                {
                    dictionary.Put(PdfName.C1, c1);
                }
                dictionary.Put(PdfName.N, n);
                return(dictionary);
            }
            public void Invoke(PdfContentStreamProcessor processor, PdfLiteral oper, List <PdfObject> operands)
            {
                PdfNumber rise = (PdfNumber)operands[0];

                processor.Gs().rise = rise.FloatValue;
            }
Beispiel #19
0
            virtual public void Invoke(PdfContentStreamProcessor processor, PdfLiteral oper, List <PdfObject> operands)
            {
                PdfNumber wordSpace = (PdfNumber)operands[0];

                processor.Gs().wordSpacing = wordSpace.FloatValue;
            }
            public void Invoke(PdfContentStreamProcessor processor, PdfLiteral oper, List <PdfObject> operands)
            {
                PdfNumber charSpace = (PdfNumber)operands[0];

                processor.Gs().characterSpacing = charSpace.FloatValue;
            }
Beispiel #21
0
 /**
  * A factor that shall be used to convert the largest units along the y axis
  * to the largest units along the x axis. It shall be used for calculations
  * (distance, area, and angle) where the units are be equivalent; if not
  * specified, these calculations may not be performed (which would be the
  * case in situations such as x representing time and y representing
  * temperature). Other calculations (change in x, change in y, and slope)
  * shall not require this value.
  *
  * @param cyx
  */
 public void SetCYX(PdfNumber cyx)
 {
     Put(PdfName.CYX, cyx);
 }
        public virtual byte[] Decode(byte[] b, PdfName filterName, PdfObject decodeParams, PdfDictionary streamDictionary
                                     )
        {
            PdfNumber wn = streamDictionary.GetAsNumber(PdfName.Width);
            PdfNumber hn = streamDictionary.GetAsNumber(PdfName.Height);

            if (wn == null || hn == null)
            {
                throw new PdfException(PdfException.FilterCcittfaxdecodeIsOnlySupportedForImages);
            }
            int           width     = wn.IntValue();
            int           height    = hn.IntValue();
            PdfDictionary param     = decodeParams is PdfDictionary ? (PdfDictionary)decodeParams : null;
            int           k         = 0;
            bool          blackIs1  = false;
            bool          byteAlign = false;

            if (param != null)
            {
                PdfNumber kn = param.GetAsNumber(PdfName.K);
                if (kn != null)
                {
                    k = kn.IntValue();
                }
                PdfBoolean bo = param.GetAsBoolean(PdfName.BlackIs1);
                if (bo != null)
                {
                    blackIs1 = bo.GetValue();
                }
                bo = param.GetAsBoolean(PdfName.EncodedByteAlign);
                if (bo != null)
                {
                    byteAlign = bo.GetValue();
                }
            }
            byte[] outBuf = new byte[(width + 7) / 8 * height];
            TIFFFaxDecompressor decoder = new TIFFFaxDecompressor();

            if (k == 0 || k > 0)
            {
                int tiffT4Options = k > 0 ? TIFFConstants.GROUP3OPT_2DENCODING : 0;
                tiffT4Options |= byteAlign ? TIFFConstants.GROUP3OPT_FILLBITS : 0;
                decoder.SetOptions(1, TIFFConstants.COMPRESSION_CCITTFAX3, tiffT4Options, 0);
                decoder.DecodeRaw(outBuf, b, width, height);
                if (decoder.fails > 0)
                {
                    byte[] outBuf2  = new byte[(width + 7) / 8 * height];
                    int    oldFails = decoder.fails;
                    decoder.SetOptions(1, TIFFConstants.COMPRESSION_CCITTRLE, tiffT4Options, 0);
                    decoder.DecodeRaw(outBuf2, b, width, height);
                    if (decoder.fails < oldFails)
                    {
                        outBuf = outBuf2;
                    }
                }
            }
            else
            {
                TIFFFaxDecoder deca = new TIFFFaxDecoder(1, width, height);
                deca.DecodeT6(outBuf, b, 0, height, 0);
            }
            if (!blackIs1)
            {
                int len = outBuf.Length;
                for (int t = 0; t < len; ++t)
                {
                    outBuf[t] ^= 0xff;
                }
            }
            b = outBuf;
            return(b);
        }
Beispiel #23
0
        /// <summary>Gets the maximum length of the field's text, in characters.</summary>
        /// <remarks>
        /// Gets the maximum length of the field's text, in characters.
        /// This is an optional parameter, so if it is not specified, <code>null</code> will be returned.
        /// </remarks>
        /// <returns>the current maximum text length</returns>
        public virtual int GetMaxLen()
        {
            PdfNumber number = GetPdfObject().GetAsNumber(PdfName.MaxLen);

            return(number != null?number.IntValue() : 0);
        }
Beispiel #24
0
        /**
         * Parses the content of a page, replacing appearances of annotations
         * with Form XObjects.
         * @param page a page dictionary
         * @throws IOException
         */
        virtual public void Parse(PdfDictionary page, PdfIndirectReference pageref)
        {
            LOGGER.Info("Parsing page with reference " + pageref);
            // initializing member variables
            baos         = new MemoryStream();
            this.page    = page;
            this.pageref = pageref;

            structParents = page.GetAsNumber(PdfName.STRUCTPARENTS);
            if (structParents == null)
            {
                throw new DocumentException(MessageLocalization.GetComposedMessage("can.t.read.document.structure"));
            }
            annots = page.GetAsArray(PdfName.ANNOTS);
            if (annots == null)
            {
                annots = new PdfArray();
            }
            PdfDictionary resources = page.GetAsDict(PdfName.RESOURCES);

            xobjects = resources.GetAsDict(PdfName.XOBJECT);
            if (xobjects == null)
            {
                xobjects = new PdfDictionary();
                resources.Put(PdfName.XOBJECT, xobjects);
            }
            // parsing the content stream of the page
            PRStream stream = (PRStream)page.GetAsStream(PdfName.CONTENTS);

            byte[]           contentBytes = PdfReader.GetStreamBytes(stream);
            PRTokeniser      tokeniser    = new PRTokeniser(new RandomAccessFileOrArray(RASFACTORY.CreateSource(contentBytes)));
            PdfContentParser ps           = new PdfContentParser(tokeniser);
            List <PdfObject> operands     = new List <PdfObject>();

            while (ps.Parse(operands).Count > 0)
            {
                PdfLiteral opr = (PdfLiteral)operands[operands.Count - 1];
                ProcessOperator(opr, operands);
            }
            // dealing with orphans
            while (items.Count > 0 && items[0].GetPageref() == pageref.Number)
            {
                StructureItem item = items[0];
                if (item is StructureObject)
                {
                    ConvertToXObject((StructureObject)item);
                    items.RemoveAt(0);
                }
            }
            if (annots.Length == 0)
            {
                page.Remove(PdfName.ANNOTS);
            }
            else
            {
                PdfDictionary annot;
                for (int i = 0; i < annots.Size; i++)
                {
                    annot = annots.GetAsDict(i);
                    if (annot.GetAsNumber(PdfName.STRUCTPARENT) == null)
                    {
                        throw new DocumentException(MessageLocalization.GetComposedMessage("could.not.flatten.file.untagged.annotations.found"));
                    }
                }
            }
            // replacing the content stream
            baos.Flush();
            baos.Close();
            stream.SetData(baos.ToArray());
            // showing how many items are left
            LOGGER.Info(String.Format("There are {0} items left for processing", items.Count));
        }
        internal static void FillFontDescriptor(iText.Kernel.Font.DocTrueTypeFont font, PdfDictionary fontDesc)
        {
            if (fontDesc == null)
            {
                return;
            }
            PdfNumber v = fontDesc.GetAsNumber(PdfName.Ascent);

            if (v != null)
            {
                font.SetTypoAscender(v.IntValue());
            }
            v = fontDesc.GetAsNumber(PdfName.Descent);
            if (v != null)
            {
                font.SetTypoDescender(v.IntValue());
            }
            v = fontDesc.GetAsNumber(PdfName.CapHeight);
            if (v != null)
            {
                font.SetCapHeight(v.IntValue());
            }
            v = fontDesc.GetAsNumber(PdfName.XHeight);
            if (v != null)
            {
                font.SetXHeight(v.IntValue());
            }
            v = fontDesc.GetAsNumber(PdfName.ItalicAngle);
            if (v != null)
            {
                font.SetItalicAngle(v.IntValue());
            }
            v = fontDesc.GetAsNumber(PdfName.StemV);
            if (v != null)
            {
                font.SetStemV(v.IntValue());
            }
            v = fontDesc.GetAsNumber(PdfName.StemH);
            if (v != null)
            {
                font.SetStemH(v.IntValue());
            }
            v = fontDesc.GetAsNumber(PdfName.FontWeight);
            if (v != null)
            {
                font.SetFontWeight(v.IntValue());
            }
            PdfName fontStretch = fontDesc.GetAsName(PdfName.FontStretch);

            if (fontStretch != null)
            {
                font.SetFontWidth(fontStretch.GetValue());
            }
            PdfArray bboxValue = fontDesc.GetAsArray(PdfName.FontBBox);

            if (bboxValue != null)
            {
                int[] bbox = new int[4];
                bbox[0] = bboxValue.GetAsNumber(0).IntValue();
                //llx
                bbox[1] = bboxValue.GetAsNumber(1).IntValue();
                //lly
                bbox[2] = bboxValue.GetAsNumber(2).IntValue();
                //urx
                bbox[3] = bboxValue.GetAsNumber(3).IntValue();
                //ury
                if (bbox[0] > bbox[2])
                {
                    int t = bbox[0];
                    bbox[0] = bbox[2];
                    bbox[2] = t;
                }
                if (bbox[1] > bbox[3])
                {
                    int t = bbox[1];
                    bbox[1] = bbox[3];
                    bbox[3] = t;
                }
                font.SetBbox(bbox);
                // If ascender or descender in font descriptor are zero, we still want to get more or less correct valuee for
                // text extraction, stamping etc. Thus we rely on font bbox in this case
                if (font.GetFontMetrics().GetTypoAscender() == 0 && font.GetFontMetrics().GetTypoDescender() == 0)
                {
                    float maxAscent  = Math.Max(bbox[3], font.GetFontMetrics().GetTypoAscender());
                    float minDescent = Math.Min(bbox[1], font.GetFontMetrics().GetTypoDescender());
                    font.SetTypoAscender((int)(maxAscent * 1000 / (maxAscent - minDescent)));
                    font.SetTypoDescender((int)(minDescent * 1000 / (maxAscent - minDescent)));
                }
            }
            PdfString fontFamily = fontDesc.GetAsString(PdfName.FontFamily);

            if (fontFamily != null)
            {
                font.SetFontFamily(fontFamily.GetValue());
            }
            PdfNumber flagsValue = fontDesc.GetAsNumber(PdfName.Flags);

            if (flagsValue != null)
            {
                int flags = flagsValue.IntValue();
                if ((flags & 1) != 0)
                {
                    font.SetFixedPitch(true);
                }
                if ((flags & 262144) != 0)
                {
                    font.SetBold(true);
                }
            }
            PdfName[] fontFileNames = new PdfName[] { PdfName.FontFile, PdfName.FontFile2, PdfName.FontFile3 };
            foreach (PdfName fontFile in fontFileNames)
            {
                if (fontDesc.ContainsKey(fontFile))
                {
                    font.fontFileName = fontFile;
                    font.fontFile     = fontDesc.GetAsStream(fontFile);
                    break;
                }
            }
        }
Beispiel #26
0
        /**
         * Converts an annotation structure item to a Form XObject annotation.
         * @param item the structure item
         * @throws IOException
         */
        virtual protected void ConvertToXObject(StructureObject item)
        {
            PdfDictionary structElem = item.GetStructElem();

            if (structElem == null)
            {
                return;
            }
            PdfDictionary dict = item.GetObjAsDict();

            if (dict == null || !dict.CheckType(PdfName.ANNOT))
            {
                return;
            }
            PdfDictionary ap = dict.GetAsDict(PdfName.AP);

            if (ap == null)
            {
                return;
            }
            PdfNumber structParent = dict.GetAsNumber(PdfName.STRUCTPARENT);

            if (structParent == null)
            {
                return;
            }
            PdfStream stream = ap.GetAsStream(PdfName.N);

            if (stream == null)
            {
                return;
            }
            stream.Put(PdfName.STRUCTPARENT, structParent);
            PdfIndirectReference xobjr = ap.GetAsIndirectObject(PdfName.N);

            if (xobjr == null)
            {
                return;
            }
            // remove the annotation from the page
            for (int i = 0; i < annots.Length; i++)
            {
                PdfIndirectReference annotref = annots.GetAsIndirectObject(i);
                if (item.GetObjRef().Number == annotref.Number)
                {
                    annots.Remove(i);
                    break;
                }
            }
            // replace the existing attributes by a PrintField attribute
            PdfDictionary attribute = new PdfDictionary();

            attribute.Put(PdfName.O, PdfName.PRINTFIELD);
            PdfString description = dict.GetAsString(PdfName.TU);

            if (description == null)
            {
                description = dict.GetAsString(PdfName.T);
            }
            if (PdfName.BTN.Equals(dict.Get(PdfName.FT)))
            {
                PdfNumber fflags = dict.GetAsNumber(PdfName.FF);
                if (fflags != null)
                {
                    int ff = fflags.IntValue;
                    if ((ff & PdfFormField.FF_PUSHBUTTON) != 0)
                    {
                        attribute.Put(PdfName.ROLE, PdfName.PB);
                    }
                    // I don't think the condition below will ever be true
                    if ((ff & PdfFormField.FF_RADIO) != 0)
                    {
                        attribute.Put(PdfName.ROLE, PdfName.rb);
                    }
                    else
                    {
                        attribute.Put(PdfName.ROLE, PdfName.CB);
                    }
                }
            }
            else
            {
                attribute.Put(PdfName.ROLE, PdfName.TV);
            }
            attribute.Put(PdfName.DESC, description);
            // Updating the values of the StructElem dictionary
            PdfString t = structElem.GetAsString(PdfName.T);

            if (t == null || t.ToString().Trim().Length == 0)
            {
                structElem.Put(PdfName.T, dict.GetAsString(PdfName.T));
            }
            structElem.Put(PdfName.A, attribute);
            structElem.Put(PdfName.S, PdfName.P);
            structElem.Put(PdfName.PG, pageref);
            // Defining a new MCID
            int mcid = items.ProcessMCID(structParents, item.GetRef());

            LOGGER.Info("Using MCID " + mcid);
            structElem.Put(PdfName.K, new PdfNumber(mcid));
            // removing the annotation from the parent tree
            items.RemoveFromParentTree(structParent);
            // Adding the XObject to the page
            PdfName xobj = new PdfName("XObj" + structParent.IntValue);

            LOGGER.Info("Creating XObject with name " + xobj);
            xobjects.Put(xobj, xobjr);
            PdfArray array = dict.GetAsArray(PdfName.RECT);
            // Getting the position of the annotation
            Rectangle rect = new Rectangle(
                array.GetAsNumber(0).FloatValue, array.GetAsNumber(1).FloatValue,
                array.GetAsNumber(2).FloatValue, array.GetAsNumber(3).FloatValue);

            rect.Normalize();
            // A Do operator is forbidden inside a text block
            if (inText && !btWrite)
            {
                LOGGER.Debug("Introducing extra ET");
                byte[] bytes = Encoding.ASCII.GetBytes("ET\n");
                baos.Write(bytes, 0, bytes.Length);
                etExtra = true;
            }
            // Writing the marked-content sequence with the Do operator
            // Note that the position assumes that the CTM wasn't changed in the graphics state
            // TODO: do the math if the CTM did change!
            ByteBuffer buf = new ByteBuffer();

            buf.Append("/P <</MCID ");
            buf.Append(mcid);
            buf.Append(">> BDC\n");
            buf.Append("q 1 0 0 1 ");
            buf.Append(rect.Left.ToString(CultureInfo.InvariantCulture));
            buf.Append(" ");
            buf.Append(rect.Bottom.ToString(CultureInfo.InvariantCulture));
            buf.Append(" cm ");
            buf.Append(xobj.GetBytes());
            buf.Append(" Do Q\n");
            buf.Append("EMC\n");
            buf.Flush();
            buf.WriteTo(baos);
            // if we were inside a text block, we've introduced an ET, so we'll need to write a BT
            if (inText)
            {
                btWrite = true;
            }
        }
Beispiel #27
0
        /// <summary>
        /// A code specifying the form of quadding (justification) that is used in displaying the annotation's text:
        /// 0 - Left-justified, 1 - Centered, 2 - Right-justified.
        /// </summary>
        /// <remarks>
        /// A code specifying the form of quadding (justification) that is used in displaying the annotation's text:
        /// 0 - Left-justified, 1 - Centered, 2 - Right-justified. Default value: 0 (left-justified).
        /// </remarks>
        /// <returns>a code specifying the form of quadding (justification), returns the default value if not explicitly specified.
        ///     </returns>
        public virtual int GetJustification()
        {
            PdfNumber q = GetPdfObject().GetAsNumber(PdfName.Q);

            return(q == null ? 0 : q.IntValue());
        }
Beispiel #28
0
 public PdfMcrNumber(PdfNumber pdfObject, PdfStructElem parent)
     : base(pdfObject, parent)
 {
 }
        private void FillFields(AcroFields acroFields)
        {
            var fields = new LinkedDictionary <string, AcroFields.Item>();

            typeof(AcroFields).GetField("fields", BindingFlags.Instance | BindingFlags.NonPublic).SetValue(acroFields, fields);

            PdfDictionary top = (PdfDictionary)GetPdfObjectRelease(Catalog.Get(PdfName.ACROFORM));

            if (top == null)
            {
                return;
            }
            PdfArray arrfds = (PdfArray)GetPdfObjectRelease(top.Get(PdfName.FIELDS));

            if (arrfds == null || arrfds.Size == 0)
            {
                return;
            }
            for (int k = 1; k <= NumberOfPages; ++k)
            {
                PdfDictionary page   = GetPageNRelease(k);
                PdfArray      annots = (PdfArray)GetPdfObjectRelease(page.Get(PdfName.ANNOTS), page);
                if (annots == null)
                {
                    continue;
                }
                for (int j = 0; j < annots.Size; ++j)
                {
                    PdfDictionary annot = annots.GetAsDict(j);
                    if (annot == null)
                    {
                        ReleaseLastXrefPartial(annots.GetAsIndirectObject(j));
                        continue;
                    }
                    if (!PdfName.WIDGET.Equals(annot.GetAsName(PdfName.SUBTYPE)))
                    {
                        ReleaseLastXrefPartial(annots.GetAsIndirectObject(j));
                        continue;
                    }
                    PdfDictionary widget = annot;
                    PdfDictionary dic    = new PdfDictionary();
                    dic.Merge(annot);
                    string        name  = string.Empty;
                    PdfDictionary value = null;
                    PdfObject     lastV = null;
                    while (annot != null)
                    {
                        dic.Merge(annot);
                        PdfString t = annot.GetAsString(PdfName.T);
                        if (t != null)
                        {
                            name = t.ToUnicodeString() + "." + name;
                        }
                        if (lastV == null && annot.Get(PdfName.V) != null)
                        {
                            lastV = GetPdfObjectRelease(annot.Get(PdfName.V));
                        }
                        if (value == null && t != null)
                        {
                            value = annot;
                            if (annot.Get(PdfName.V) == null && lastV != null)
                            {
                                value.Put(PdfName.V, lastV);
                            }
                        }
                        annot = annot.GetAsDict(PdfName.PARENT);
                    }
                    if (name.Length > 0)
                    {
                        name = name.Substring(0, name.Length - 1);
                    }
                    AcroFields.Item item;
                    if (!fields.TryGetValue(name, out item))
                    {
                        item         = new AcroFields.Item();
                        fields[name] = item;
                    }
                    var addValueMethod = item.GetType().GetMethod("AddValue", BindingFlags.Instance | BindingFlags.NonPublic);
                    if (value == null)
                    {
                        addValueMethod.Invoke(item, new object[] { widget });
                    }
                    else
                    {
                        addValueMethod.Invoke(item, new object[] { value });
                    }
                    item.GetType().GetMethod("AddWidget", BindingFlags.Instance | BindingFlags.NonPublic).Invoke(item, new object[] { widget });
                    item.GetType().GetMethod("AddWidgetRef", BindingFlags.Instance | BindingFlags.NonPublic).Invoke(item, new object[] { annots.GetAsIndirectObject(j) });                     // must be a reference
                    if (top != null)
                    {
                        dic.MergeDifferent(top);
                    }
                    item.GetType().GetMethod("AddMerged", BindingFlags.Instance | BindingFlags.NonPublic).Invoke(item, new object[] { dic });
                    item.GetType().GetMethod("AddPage", BindingFlags.Instance | BindingFlags.NonPublic).Invoke(item, new object[] { k });
                    item.GetType().GetMethod("AddTabOrder", BindingFlags.Instance | BindingFlags.NonPublic).Invoke(item, new object[] { j });
                }
            }
            // some tools produce invisible signatures without an entry in the page annotation array
            // look for a single level annotation
            PdfNumber sigFlags = top.GetAsNumber(PdfName.SIGFLAGS);

            if (sigFlags == null || (sigFlags.IntValue & 1) != 1)
            {
                return;
            }
            for (int j = 0; j < arrfds.Size; ++j)
            {
                PdfDictionary annot = arrfds.GetAsDict(j);
                if (annot == null)
                {
                    ReleaseLastXrefPartial(arrfds.GetAsIndirectObject(j));
                    continue;
                }
                if (!PdfName.WIDGET.Equals(annot.GetAsName(PdfName.SUBTYPE)))
                {
                    ReleaseLastXrefPartial(arrfds.GetAsIndirectObject(j));
                    continue;
                }
                PdfArray kids = (PdfArray)GetPdfObjectRelease(annot.Get(PdfName.KIDS));
                if (kids != null)
                {
                    continue;
                }
                PdfDictionary dic = new PdfDictionary();
                dic.Merge(annot);
                PdfString t = annot.GetAsString(PdfName.T);
                if (t == null)
                {
                    continue;
                }
                string name = t.ToUnicodeString();
                if (fields.ContainsKey(name))
                {
                    continue;
                }
                var item = new AcroFields.Item();
                fields[name] = item;
                item.GetType().GetMethod("AddValue", BindingFlags.Instance | BindingFlags.NonPublic).Invoke(item, new object[] { dic });
                item.GetType().GetMethod("AddWidget", BindingFlags.Instance | BindingFlags.NonPublic).Invoke(item, new object[] { dic });
                item.GetType().GetMethod("AddWidgetRef", BindingFlags.Instance | BindingFlags.NonPublic).Invoke(item, new object[] { arrfds.GetAsIndirectObject(j) });                 // must be a reference
                item.GetType().GetMethod("AddMerged", BindingFlags.Instance | BindingFlags.NonPublic).Invoke(item, new object[] { dic });
                item.GetType().GetMethod("AddPage", BindingFlags.Instance | BindingFlags.NonPublic).Invoke(item, new object[] { -1 });
                item.GetType().GetMethod("AddTabOrder", BindingFlags.Instance | BindingFlags.NonPublic).Invoke(item, new object[] { -1 });
            }
        }
Beispiel #30
0
            virtual public void Invoke(PdfContentStreamProcessor processor, PdfLiteral oper, List <PdfObject> operands)
            {
                PdfNumber render = (PdfNumber)operands[0];

                processor.Gs().renderMode = render.IntValue;
            }
Beispiel #31
0
 /**
  * Parses the content of a page, replacing appearances of annotations
  * with Form XObjects.
  * @param page a page dictionary
  * @throws IOException
  */
 virtual public void Parse(PdfDictionary page, PdfIndirectReference pageref) {
     LOGGER.Info("Parsing page with reference " + pageref);
     // initializing member variables
     baos = new MemoryStream();
     this.page = page;
     this.pageref = pageref;
     
     structParents = page.GetAsNumber(PdfName.STRUCTPARENTS);
     if(structParents == null)
         throw new DocumentException(MessageLocalization.GetComposedMessage("can.t.read.document.structure"));
     annots = page.GetAsArray(PdfName.ANNOTS);
     if(annots == null)
         annots = new PdfArray();
     PdfDictionary resources = page.GetAsDict(PdfName.RESOURCES);
     xobjects = resources.GetAsDict(PdfName.XOBJECT);
     if (xobjects == null) {
         xobjects = new PdfDictionary();
         resources.Put(PdfName.XOBJECT, xobjects);
     }
     // parsing the content stream of the page
     PRStream stream = (PRStream) page.GetAsStream(PdfName.CONTENTS);
     byte[] contentBytes = PdfReader.GetStreamBytes(stream);
     PRTokeniser tokeniser = new PRTokeniser(new RandomAccessFileOrArray(RASFACTORY.CreateSource(contentBytes)));
     PdfContentParser ps = new PdfContentParser(tokeniser);
     List<PdfObject> operands = new List<PdfObject>();
     while (ps.Parse(operands).Count > 0) {
         PdfLiteral opr = (PdfLiteral) operands[operands.Count - 1];
         ProcessOperator(opr, operands);
     }
     // dealing with orphans
     while (items.Count > 0 && items[0].GetPageref() == pageref.Number) {
         StructureItem item = items[0];
         if (item is StructureObject) {
             ConvertToXObject((StructureObject) item);
             items.RemoveAt(0);
         }
     }
     if(annots.Length == 0) {
         page.Remove(PdfName.ANNOTS);
     }
     else {
         PdfDictionary annot;
         for(int i = 0; i < annots.Size; i++) {
             annot = annots.GetAsDict(i);
             if(annot.GetAsNumber(PdfName.STRUCTPARENT) == null)
                 throw new DocumentException(MessageLocalization.GetComposedMessage("could.not.flatten.file.untagged.annotations.found"));
         }
     }
     // replacing the content stream
     baos.Flush();
     baos.Close();
     stream.SetData(baos.ToArray());
     // showing how many items are left
     LOGGER.Info(String.Format("There are {0} items left for processing", items.Count));
 }
Beispiel #32
0
            virtual public void Invoke(PdfContentStreamProcessor processor, PdfLiteral oper, List <PdfObject> operands)
            {
                PdfNumber leading = (PdfNumber)operands[0];

                processor.Gs().leading = leading.FloatValue;
            }
Beispiel #33
0
 /**
  * Creates a StructureMCID using an MCID.
  * @param obj	an MCID
  */
 public StructureMCID(PdfIndirectReference pg, PdfNumber mcid) {
     this.pageref = pg.Number;
     this.mcid = mcid.IntValue;
 }
Beispiel #34
0
 public Type2(PdfArray domain, PdfArray range, PdfArray c0, PdfArray c1, PdfNumber n)
     : this(MakeType2(domain, range, c0, c1, n))
 {
 }