예제 #1
0
        internal PdfTrueTypeFont(PdfDictionary fontDictionary)
            : base(fontDictionary)
        {
            newFont      = false;
            subset       = false;
            fontEncoding = DocFontEncoding.CreateDocFontEncoding(fontDictionary.Get(PdfName.Encoding), toUnicode);
            PdfName baseFontName = fontDictionary.GetAsName(PdfName.BaseFont);

            // Section 9.6.3 (ISO-32000-1): A TrueType font dictionary may contain the same entries as a Type 1 font
            // dictionary (see Table 111), with these differences...
            // Section 9.6.2.2. (ISO-32000-1) associate standard fonts with Type1 fonts but there does not
            // seem to be a strict requirement on the subtype
            // Cases when a font with /TrueType subtype has base font which is one of the Standard 14 fonts
            // does not seem to be forbidden and it's handled by many PDF tools, so we handle it here as well
            if (baseFontName != null && StandardFonts.IsStandardFont(baseFontName.GetValue()) && !fontDictionary.ContainsKey
                    (PdfName.FontDescriptor) && !fontDictionary.ContainsKey(PdfName.Widths))
            {
                try {
                    fontProgram = FontProgramFactory.CreateFont(baseFontName.GetValue(), true);
                }
                catch (System.IO.IOException e) {
                    throw new PdfException(PdfException.IoExceptionWhileCreatingFont, e);
                }
            }
            else
            {
                fontProgram = DocTrueTypeFont.CreateFontProgram(fontDictionary, fontEncoding, toUnicode);
            }
            embedded = fontProgram is IDocFontProgram && ((IDocFontProgram)fontProgram).GetFontFile() != null;
        }
예제 #2
0
        /*
         * Unembeds a font dictionary.
         */
        public void UnembedTTF(PdfDictionary dict)
        {
            // Ignore all dictionaries that aren't font dictionaries
            if (!PdfName.Font.Equals(dict.GetAsName(PdfName.Type)))
            {
                return;
            }

            // Only TTF fonts should be removed
            if (dict.GetAsDictionary(PdfName.FontFile2) != null)
            {
                return;
            }

            // Check if a subset was used (in which case we remove the prefix)
            PdfName baseFont = dict.GetAsName(PdfName.BaseFont);

            if (Encoding.UTF8.GetBytes(baseFont.GetValue())[6] == '+')
            {
                baseFont = new PdfName(baseFont.GetValue().Substring(7));
                dict.Put(PdfName.BaseFont, baseFont);
            }

            // Check if there's a font descriptor
            PdfDictionary fontDescriptor = dict.GetAsDictionary(PdfName.FontDescriptor);

            if (fontDescriptor == null)
            {
                return;
            }

            // Replace the fontname and remove the font file
            fontDescriptor.Put(PdfName.FontName, baseFont);
            fontDescriptor.Remove(PdfName.FontFile2);
        }
예제 #3
0
 protected internal override void CheckPdfName(PdfName name)
 {
     if (name.GetValue().Length > GetMaxNameLength())
     {
         throw new PdfAConformanceException(PdfAConformanceException.PDF_NAME_IS_TOO_LONG);
     }
 }
예제 #4
0
        protected internal override void CheckAction(PdfDictionary action)
        {
            if (IsAlreadyChecked(action))
            {
                return;
            }
            PdfName s = action.GetAsName(PdfName.S);

            if (GetForbiddenActions().Contains(s))
            {
                throw new PdfAConformanceException(PdfAConformanceException._0_ACTIONS_ARE_NOT_ALLOWED).SetMessageParams(s
                                                                                                                         .GetValue());
            }
            if (s.Equals(PdfName.Named))
            {
                PdfName n = action.GetAsName(PdfName.N);
                if (n != null && !GetAllowedNamedActions().Contains(n))
                {
                    throw new PdfAConformanceException(PdfAConformanceException.NAMED_ACTION_TYPE_0_IS_NOT_ALLOWED).SetMessageParams
                              (n.GetValue());
                }
            }
            if (s.Equals(PdfName.SetState) || s.Equals(PdfName.NoOp))
            {
                throw new PdfAConformanceException(PdfAConformanceException.DEPRECATED_SETSTATE_AND_NOOP_ACTIONS_ARE_NOT_ALLOWED
                                                   );
            }
        }
예제 #5
0
        protected internal override void CheckAction(PdfDictionary action)
        {
            if (IsAlreadyChecked(action))
            {
                return;
            }
            PdfName s = action.GetAsName(PdfName.S);

            if (GetForbiddenActions().Contains(s))
            {
                throw new PdfAConformanceException(PdfAConformanceException._1ActionsAreNotAllowed).SetMessageParams(s.GetValue
                                                                                                                         ());
            }
            if (s.Equals(PdfName.Named))
            {
                PdfName n = action.GetAsName(PdfName.N);
                if (n != null && !GetAllowedNamedActions().Contains(n))
                {
                    throw new PdfAConformanceException(PdfAConformanceException.NamedActionType1IsNotAllowed).SetMessageParams
                              (n.GetValue());
                }
            }
            if (s.Equals(PdfName.SetState) || s.Equals(PdfName.NoOp))
            {
                throw new PdfAConformanceException(PdfAConformanceException.DeprecatedSetStateAndNoOpActionsAreNotAllowed);
            }
        }
        public virtual String GetAttributeAsEnum(String attributeName)
        {
            PdfName name    = PdfStructTreeRoot.ConvertRoleToPdfName(attributeName);
            PdfName attrVal = GetPdfObject().GetAsName(name);

            return(attrVal != null?attrVal.GetValue() : null);
        }
예제 #7
0
        public virtual void ResourcesTest1()
        {
            PdfDocument  document  = new PdfDocument(new PdfWriter(new MemoryStream()));
            PdfPage      page      = document.AddNewPage();
            PdfExtGState egs1      = new PdfExtGState();
            PdfExtGState egs2      = new PdfExtGState();
            PdfResources resources = page.GetResources();
            PdfName      n1        = resources.AddExtGState(egs1);

            NUnit.Framework.Assert.AreEqual("Gs1", n1.GetValue());
            PdfName n2 = resources.AddExtGState(egs2);

            NUnit.Framework.Assert.AreEqual("Gs2", n2.GetValue());
            n1 = resources.AddExtGState(egs1);
            NUnit.Framework.Assert.AreEqual("Gs1", n1.GetValue());
            document.Close();
        }
        // Note as stated by spec the desscription and file display
        // shall not be derived from the encrypted payload's actual file name
        // to avoid potential disclosure of sensitive information
        public static String GenerateDescription(PdfEncryptedPayload ep)
        {
            String  result  = "This embedded file is encrypted using " + ep.GetSubtype().GetValue();
            PdfName version = ep.GetVersion();

            if (version != null)
            {
                result += " , version: " + version.GetValue();
            }
            return(result);
        }
예제 #9
0
        /// <summary>gets the /Name of the person signing the document.</summary>
        /// <returns>name of the person signing the document.</returns>
        public virtual String GetName()
        {
            PdfString nameStr  = GetPdfObject().GetAsString(PdfName.Name);
            PdfName   nameName = GetPdfObject().GetAsName(PdfName.Name);

            if (nameStr != null)
            {
                return(nameStr.ToUnicodeString());
            }
            else
            {
                return(nameName != null?nameName.GetValue() : null);
            }
        }
예제 #10
0
        private DocTrueTypeFont(PdfDictionary fontDictionary)
            : base()
        {
            PdfName baseFontName = fontDictionary.GetAsName(PdfName.BaseFont);

            if (baseFontName != null)
            {
                SetFontName(baseFontName.GetValue());
            }
            else
            {
                SetFontName(FontUtil.CreateRandomFontName());
            }
            subtype = fontDictionary.GetAsName(PdfName.Subtype);
        }
예제 #11
0
        public virtual void ResourcesTest2()
        {
            MemoryStream baos      = new MemoryStream();
            PdfWriter    writer    = new PdfWriter(baos);
            PdfDocument  document  = new PdfDocument(writer);
            PdfPage      page      = document.AddNewPage();
            PdfExtGState egs1      = new PdfExtGState();
            PdfExtGState egs2      = new PdfExtGState();
            PdfResources resources = page.GetResources();

            resources.AddExtGState(egs1);
            resources.AddExtGState(egs2);
            document.Close();
            PdfReader reader = new PdfReader(new MemoryStream(baos.ToArray()));

            document  = new PdfDocument(reader, new PdfWriter(new ByteArrayOutputStream()));
            page      = document.GetPage(1);
            resources = page.GetResources();
            ICollection <PdfName> names = resources.GetResourceNames();

            NUnit.Framework.Assert.AreEqual(2, names.Count);
            String[] expectedNames = new String[] { "Gs1", "Gs2" };
            int      i             = 0;

            foreach (PdfName name in names)
            {
                NUnit.Framework.Assert.AreEqual(expectedNames[i++], name.GetValue());
            }
            PdfExtGState egs3 = new PdfExtGState();
            PdfName      n3   = resources.AddExtGState(egs3);

            NUnit.Framework.Assert.AreEqual("Gs3", n3.GetValue());
            PdfDictionary egsResources = page.GetPdfObject().GetAsDictionary(PdfName.Resources).GetAsDictionary(PdfName
                                                                                                                .ExtGState);
            PdfObject e1 = egsResources.Get(new PdfName("Gs1"), false);
            PdfName   n1 = resources.AddExtGState(e1);

            NUnit.Framework.Assert.AreEqual("Gs1", n1.GetValue());
            PdfObject e2 = egsResources.Get(new PdfName("Gs2"));
            PdfName   n2 = resources.AddExtGState(e2);

            NUnit.Framework.Assert.AreEqual("Gs2", n2.GetValue());
            PdfObject e4 = (PdfObject)e2.Clone();
            PdfName   n4 = resources.AddExtGState(e4);

            NUnit.Framework.Assert.AreEqual("Gs4", n4.GetValue());
            document.Close();
        }
예제 #12
0
        public virtual void TestInheritedResourcesUpdate()
        {
            PdfDocument pdfDoc = new PdfDocument(new PdfReader(sourceFolder + "simpleInheritedResources.pdf"), new PdfWriter
                                                     (destinationFolder + "updateInheritedResources.pdf").SetCompressionLevel(CompressionConstants.NO_COMPRESSION
                                                                                                                              ));
            PdfName newGsName = pdfDoc.GetPage(1).GetResources().AddExtGState(new PdfExtGState().SetLineWidth(30));
            int     gsCount   = pdfDoc.GetPage(1).GetResources().GetResource(PdfName.ExtGState).Size();

            pdfDoc.Close();
            String compareResult = new CompareTool().CompareByContent(destinationFolder + "updateInheritedResources.pdf"
                                                                      , sourceFolder + "cmp_" + "updateInheritedResources.pdf", destinationFolder, "diff");

            NUnit.Framework.Assert.AreEqual(3, gsCount);
            NUnit.Framework.Assert.AreEqual("Gs3", newGsName.GetValue());
            NUnit.Framework.Assert.IsNull(compareResult);
        }
예제 #13
0
        private void WrapAllKidsInTag(PdfStructElem parent, PdfName wrapTagRole, PdfNamespace wrapTagNs)
        {
            int            kidsNum    = parent.GetKids().Count;
            TagTreePointer tagPointer = new TagTreePointer(parent, document);

            tagPointer.AddTag(0, wrapTagRole.GetValue());
            if (context.TargetTagStructureVersionIs2())
            {
                tagPointer.GetProperties().SetNamespace(wrapTagNs);
            }
            TagTreePointer newParentOfKids = new TagTreePointer(tagPointer);

            tagPointer.MoveToParent();
            for (int i = 0; i < kidsNum; ++i)
            {
                tagPointer.RelocateKid(1, newParentOfKids);
            }
        }
예제 #14
0
        internal static IDictionary <String, PdfName> LoadNames()
        {
            FieldInfo[] fields = typeof(PdfName).GetFields(BindingFlags.Public | BindingFlags.Static | BindingFlags.DeclaredOnly);
            IDictionary <String, PdfName> staticNames = new Dictionary <String, PdfName>(fields.Length);

            try {
                for (int fldIdx = 0; fldIdx < fields.Length; ++fldIdx)
                {
                    FieldInfo curFld = fields[fldIdx];
                    if (curFld.FieldType.Equals(typeof(PdfName)))
                    {
                        PdfName name = (PdfName)curFld.GetValue(null);
                        staticNames[name.GetValue()] = name;
                    }
                }
            } catch {
                return(null);
            }
            return(staticNames);
        }
예제 #15
0
 protected internal virtual void InspectKid(IStructureNode kid)
 {
     try {
         if (kid is PdfStructElem)
         {
             PdfStructElem structElemKid = (PdfStructElem)kid;
             PdfName       s             = structElemKid.GetRole();
             String        tagN          = s.GetValue();
             String        tag           = FixTagName(tagN);
             @out.Write("<");
             @out.Write(tag);
             InspectAttributes(structElemKid);
             @out.Write(">" + Environment.NewLine);
             PdfString alt = (structElemKid).GetAlt();
             if (alt != null)
             {
                 @out.Write("<alt><![CDATA[");
                 @out.Write(iText.IO.Util.StringUtil.ReplaceAll(alt.GetValue(), "[\\000]*", ""));
                 @out.Write("]]></alt>" + Environment.NewLine);
             }
             InspectKids(structElemKid.GetKids());
             @out.Write("</");
             @out.Write(tag);
             @out.Write(">" + Environment.NewLine);
         }
         else
         {
             if (kid is PdfMcr)
             {
                 ParseTag((PdfMcr)kid);
             }
             else
             {
                 @out.Write(" <flushedKid/> ");
             }
         }
     }
     catch (System.IO.IOException e) {
         throw new iText.IO.IOException(iText.IO.IOException.UnknownIOException, e);
     }
 }
예제 #16
0
 private static void FillBaseEncoding(iText.Kernel.Font.DocFontEncoding fontEncoding, PdfName baseEncodingName
                                      , bool fillStandardEncoding)
 {
     if (baseEncodingName != null)
     {
         fontEncoding.baseEncoding = baseEncodingName.GetValue();
     }
     if (PdfName.MacRomanEncoding.Equals(baseEncodingName) || PdfName.WinAnsiEncoding.Equals(baseEncodingName) ||
         PdfName.Symbol.Equals(baseEncodingName) || PdfName.ZapfDingbats.Equals(baseEncodingName))
     {
         String enc = PdfEncodings.WINANSI;
         if (PdfName.MacRomanEncoding.Equals(baseEncodingName))
         {
             enc = PdfEncodings.MACROMAN;
         }
         else
         {
             if (PdfName.Symbol.Equals(baseEncodingName))
             {
                 enc = PdfEncodings.SYMBOL;
             }
             else
             {
                 if (PdfName.ZapfDingbats.Equals(baseEncodingName))
                 {
                     enc = PdfEncodings.ZAPFDINGBATS;
                 }
             }
         }
         fontEncoding.baseEncoding = enc;
         fontEncoding.FillNamedEncoding();
     }
     else
     {
         if (fillStandardEncoding)
         {
             fontEncoding.FillStandardEncoding();
         }
     }
 }
예제 #17
0
 private static void FillBaseEncoding(iText.Kernel.Font.DocFontEncoding fontEncoding, PdfName baseEncodingName
                                      )
 {
     if (baseEncodingName != null)
     {
         fontEncoding.baseEncoding = baseEncodingName.GetValue();
     }
     if (PdfName.MacRomanEncoding.Equals(baseEncodingName) || PdfName.WinAnsiEncoding.Equals(baseEncodingName) ||
         PdfName.Symbol.Equals(baseEncodingName) || PdfName.ZapfDingbats.Equals(baseEncodingName))
     {
         String enc = PdfEncodings.WINANSI;
         if (PdfName.MacRomanEncoding.Equals(baseEncodingName))
         {
             enc = PdfEncodings.MACROMAN;
         }
         else
         {
             if (PdfName.Symbol.Equals(baseEncodingName))
             {
                 enc = PdfEncodings.SYMBOL;
             }
             else
             {
                 if (PdfName.ZapfDingbats.Equals(baseEncodingName))
                 {
                     enc = PdfEncodings.ZAPFDINGBATS;
                 }
             }
         }
         fontEncoding.baseEncoding = enc;
         fontEncoding.FillNamedEncoding();
     }
     else
     {
         // Actually, font's built in encoding should be used if font file is embedded
         // and standard encoding should be used otherwise
         fontEncoding.FillStandardEncoding();
     }
 }
예제 #18
0
        private void FillFontDescriptor(PdfDictionary fontDesc)
        {
            if (fontDesc == null)
            {
                return;
            }
            PdfNumber v = fontDesc.GetAsNumber(PdfName.ItalicAngle);

            if (v != null)
            {
                SetItalicAngle(v.IntValue());
            }
            v = fontDesc.GetAsNumber(PdfName.FontWeight);
            if (v != null)
            {
                SetFontWeight(v.IntValue());
            }
            PdfName fontStretch = fontDesc.GetAsName(PdfName.FontStretch);

            if (fontStretch != null)
            {
                SetFontStretch(fontStretch.GetValue());
            }
            PdfName fontName = fontDesc.GetAsName(PdfName.FontName);

            if (fontName != null)
            {
                SetFontName(fontName.GetValue());
            }
            PdfString fontFamily = fontDesc.GetAsString(PdfName.FontFamily);

            if (fontFamily != null)
            {
                SetFontFamily(fontFamily.GetValue());
            }
        }
예제 #19
0
        public FlowDocument Get_Highlighted_Text(string filenamePath)
        {
            FlowDocument doc = new FlowDocument();
            int          pageTo;
            bool         hasAnnot = false;

            try
            {
                using (PdfReader reader = new PdfReader(filenamePath))
                {
                    PdfDocument pdfDoc = new PdfDocument(reader);
                    pageTo = pdfDoc.GetNumberOfPages();
                    for (int i = 1; i <= pageTo; i++)
                    {
                        PdfPage page = pdfDoc.GetPage(i);
                        IList <iText.Kernel.Pdf.Annot.PdfAnnotation> annots = page.GetAnnotations();

                        if (annots.Count > 0)
                        {
                            hasAnnot = true;
                            Paragraph paragraph = new Paragraph();

                            paragraph.Inlines.Clear();
                            paragraph.Inlines.Add("------- Page:");
                            paragraph.Inlines.Add($"{i.ToString()}");
                            paragraph.Inlines.Add($"-------{Environment.NewLine}");
                            doc.Blocks.Add(paragraph);

                            foreach (iText.Kernel.Pdf.Annot.PdfAnnotation annot in annots)

                            {
                                Paragraph paragraph_annot = new Paragraph();
                                //Get Annotation from PDF File
                                PdfString annot_Text = annot.GetContents();
                                PdfName   subType    = annot.GetSubtype();
                                if (annot_Text != null)
                                {
                                    paragraph_annot.Inlines.Add(new Run($"{subType.GetValue()}")
                                    {
                                        FontWeight = FontWeights.Bold
                                    });
                                    paragraph_annot.Inlines.Add($":{Environment.NewLine}");
                                    paragraph_annot.Inlines.Add($"{annot_Text.ToUnicodeString()}{Environment.NewLine}");
                                    doc.Blocks.Add(paragraph_annot);
                                }
                            }
                        }
                    }
                    if (hasAnnot)
                    {
                        FileInfo  file            = new FileInfo(filenamePath);
                        Paragraph paragraph_title = new Paragraph();
                        paragraph_title.Inlines.Add(new Run(file.Name)
                        {
                            FontWeight = FontWeights.Bold
                        });
                        doc.Blocks.InsertBefore(doc.Blocks.FirstBlock, paragraph_title);
                    }
                    else
                    {
                        FileInfo  file            = new FileInfo(filenamePath);
                        Paragraph paragraph_title = new Paragraph();
                        paragraph_title.Inlines.Add($"There are no highlights or comments in: {Environment.NewLine} {file.Name}");
                        doc.Blocks.Add(paragraph_title);
                    }
                    //MessageBox.Show(annot_string);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }

            return(doc);
        }
예제 #20
0
        /// <summary>Creates a Type 3 font based on an existing font dictionary, which must be an indirect object.</summary>
        /// <param name="fontDictionary">a dictionary of type <c>/Font</c>, must have an indirect reference.</param>
        internal PdfType3Font(PdfDictionary fontDictionary)
            : base(fontDictionary)
        {
            subset       = true;
            embedded     = true;
            fontProgram  = new Type3Font(false);
            fontEncoding = DocFontEncoding.CreateDocFontEncoding(fontDictionary.Get(PdfName.Encoding), toUnicode);
            PdfDictionary charProcsDic    = GetPdfObject().GetAsDictionary(PdfName.CharProcs);
            PdfArray      fontMatrixArray = GetPdfObject().GetAsArray(PdfName.FontMatrix);

            if (GetPdfObject().ContainsKey(PdfName.FontBBox))
            {
                PdfArray fontBBox = GetPdfObject().GetAsArray(PdfName.FontBBox);
                fontProgram.GetFontMetrics().SetBbox(fontBBox.GetAsNumber(0).IntValue(), fontBBox.GetAsNumber(1).IntValue(
                                                         ), fontBBox.GetAsNumber(2).IntValue(), fontBBox.GetAsNumber(3).IntValue());
            }
            else
            {
                fontProgram.GetFontMetrics().SetBbox(0, 0, 0, 0);
            }
            int firstChar = NormalizeFirstLastChar(fontDictionary.GetAsNumber(PdfName.FirstChar), 0);
            int lastChar  = NormalizeFirstLastChar(fontDictionary.GetAsNumber(PdfName.LastChar), 255);

            for (int i = firstChar; i <= lastChar; i++)
            {
                shortTag[i] = 1;
            }
            int[]    widths     = FontUtil.ConvertSimpleWidthsArray(fontDictionary.GetAsArray(PdfName.Widths), firstChar, 0);
            double[] fontMatrix = new double[6];
            for (int i = 0; i < fontMatrixArray.Size(); i++)
            {
                fontMatrix[i] = ((PdfNumber)fontMatrixArray.Get(i)).GetValue();
            }
            SetFontMatrix(fontMatrix);
            if (toUnicode != null && toUnicode.HasByteMappings() && fontEncoding.HasDifferences())
            {
                for (int i = 0; i < 256; i++)
                {
                    int     unicode   = fontEncoding.GetUnicode(i);
                    PdfName glyphName = new PdfName(fontEncoding.GetDifference(i));
                    if (unicode != -1 && !FontEncoding.NOTDEF.Equals(glyphName.GetValue()) && charProcsDic.ContainsKey(glyphName
                                                                                                                       ))
                    {
                        ((Type3Font)GetFontProgram()).AddGlyph(i, unicode, widths[i], null, new Type3Glyph(charProcsDic.GetAsStream
                                                                                                               (glyphName), GetDocument()));
                    }
                }
            }
            IDictionary <int, int?> unicodeToCode = null;

            if (toUnicode != null)
            {
                try {
                    unicodeToCode = toUnicode.CreateReverseMapping();
                }
                catch (Exception) {
                }
            }
            foreach (PdfName glyphName in charProcsDic.KeySet())
            {
                int unicode = AdobeGlyphList.NameToUnicode(glyphName.GetValue());
                int code    = -1;
                if (fontEncoding.CanEncode(unicode))
                {
                    code = fontEncoding.ConvertToByte(unicode);
                }
                else
                {
                    if (unicodeToCode != null && unicodeToCode.ContainsKey(unicode))
                    {
                        code = (int)unicodeToCode.Get(unicode);
                    }
                }
                if (code != -1 && GetFontProgram().GetGlyphByCode(code) == null)
                {
                    ((Type3Font)GetFontProgram()).AddGlyph(code, unicode, widths[code], null, new Type3Glyph(charProcsDic.GetAsStream
                                                                                                                 (glyphName), GetDocument()));
                }
            }
            FillFontDescriptor(fontDictionary.GetAsDictionary(PdfName.FontDescriptor));
        }
예제 #21
0
        public virtual void PrimitivesTest()
        {
            String data = "<</Size 70." + "/Value#20 .1" + "/Root 46 0 R" + "/Info 44 0 R" + "/ID[<736f6d652068657820737472696e672>(some simple string )<8C2547D58D4BD2C6F3D32B830BE3259D2>-70.1--0.2]"
                          + "/Name1 --15" + "/Prev ---116.23 >>";
            RandomAccessSourceFactory factory = new RandomAccessSourceFactory();
            PdfTokenizer tok = new PdfTokenizer(new RandomAccessFileOrArray(factory.CreateSource(data.GetBytes(iText.IO.Util.EncodingUtil.ISO_8859_1
                                                                                                               ))));

            tok.NextValidToken();
            NUnit.Framework.Assert.AreEqual(tok.GetTokenType(), PdfTokenizer.TokenType.StartDic);
            tok.NextValidToken();
            NUnit.Framework.Assert.AreEqual(tok.GetTokenType(), PdfTokenizer.TokenType.Name);
            PdfName name = new PdfName(tok.GetByteContent());

            NUnit.Framework.Assert.AreEqual("Size", name.GetValue());
            tok.NextValidToken();
            NUnit.Framework.Assert.AreEqual(tok.GetTokenType(), PdfTokenizer.TokenType.Number);
            PdfNumber num = new PdfNumber(tok.GetByteContent());

            NUnit.Framework.Assert.AreEqual("70.", num.ToString());
            tok.NextValidToken();
            NUnit.Framework.Assert.AreEqual(tok.GetTokenType(), PdfTokenizer.TokenType.Name);
            name = new PdfName(tok.GetByteContent());
            NUnit.Framework.Assert.AreEqual("Value ", name.GetValue());
            tok.NextValidToken();
            NUnit.Framework.Assert.AreEqual(tok.GetTokenType(), PdfTokenizer.TokenType.Number);
            num = new PdfNumber(tok.GetByteContent());
            NUnit.Framework.Assert.AreNotSame("0.1", num.ToString());
            tok.NextValidToken();
            NUnit.Framework.Assert.AreEqual(tok.GetTokenType(), PdfTokenizer.TokenType.Name);
            name = new PdfName(tok.GetByteContent());
            NUnit.Framework.Assert.AreEqual("Root", name.GetValue());
            tok.NextValidToken();
            NUnit.Framework.Assert.AreEqual(tok.GetTokenType(), PdfTokenizer.TokenType.Ref);
            PdfIndirectReference @ref = new PdfIndirectReference(null, tok.GetObjNr(), tok.GetGenNr());

            NUnit.Framework.Assert.AreEqual("46 0 R", @ref.ToString());
            tok.NextValidToken();
            NUnit.Framework.Assert.AreEqual(tok.GetTokenType(), PdfTokenizer.TokenType.Name);
            name = new PdfName(tok.GetByteContent());
            NUnit.Framework.Assert.AreEqual("Info", name.GetValue());
            tok.NextValidToken();
            NUnit.Framework.Assert.AreEqual(tok.GetTokenType(), PdfTokenizer.TokenType.Ref);
            @ref = new PdfIndirectReference(null, tok.GetObjNr(), tok.GetGenNr());
            NUnit.Framework.Assert.AreEqual("44 0 R", @ref.ToString());
            tok.NextValidToken();
            NUnit.Framework.Assert.AreEqual(tok.GetTokenType(), PdfTokenizer.TokenType.Name);
            name = new PdfName(tok.GetByteContent());
            NUnit.Framework.Assert.AreEqual("ID", name.GetValue());
            tok.NextValidToken();
            NUnit.Framework.Assert.AreEqual(tok.GetTokenType(), PdfTokenizer.TokenType.StartArray);
            tok.NextValidToken();
            NUnit.Framework.Assert.AreEqual(tok.GetTokenType(), PdfTokenizer.TokenType.String);
            NUnit.Framework.Assert.AreEqual(tok.IsHexString(), true);
            PdfString str = new PdfString(tok.GetByteContent(), tok.IsHexString());

            NUnit.Framework.Assert.AreEqual("some hex string ", str.GetValue());
            tok.NextValidToken();
            NUnit.Framework.Assert.AreEqual(tok.GetTokenType(), PdfTokenizer.TokenType.String);
            NUnit.Framework.Assert.AreEqual(tok.IsHexString(), false);
            str = new PdfString(tok.GetByteContent(), tok.IsHexString());
            NUnit.Framework.Assert.AreEqual("some simple string ", str.GetValue());
            tok.NextValidToken();
            NUnit.Framework.Assert.AreEqual(tok.GetTokenType(), PdfTokenizer.TokenType.String);
            NUnit.Framework.Assert.AreEqual(tok.IsHexString(), true);
            str = new PdfString(tok.GetByteContent(), tok.IsHexString());
            NUnit.Framework.Assert.AreEqual("\u008C%G\u00D5\u008DK\u00D2\u00C6\u00F3\u00D3+\u0083\u000B\u00E3%\u009D "
                                            , str.GetValue());
            tok.NextValidToken();
            NUnit.Framework.Assert.AreEqual(tok.GetTokenType(), PdfTokenizer.TokenType.Number);
            num = new PdfNumber(tok.GetByteContent());
            NUnit.Framework.Assert.AreEqual("-70.1", num.ToString());
            tok.NextValidToken();
            NUnit.Framework.Assert.AreEqual(tok.GetTokenType(), PdfTokenizer.TokenType.Number);
            num = new PdfNumber(tok.GetByteContent());
            NUnit.Framework.Assert.AreEqual("-0.2", num.ToString());
            tok.NextValidToken();
            NUnit.Framework.Assert.AreEqual(tok.GetTokenType(), PdfTokenizer.TokenType.EndArray);
            tok.NextValidToken();
            NUnit.Framework.Assert.AreEqual(tok.GetTokenType(), PdfTokenizer.TokenType.Name);
            name = new PdfName(tok.GetByteContent());
            NUnit.Framework.Assert.AreEqual("Name1", name.GetValue());
            tok.NextValidToken();
            NUnit.Framework.Assert.AreEqual(tok.GetTokenType(), PdfTokenizer.TokenType.Number);
            num = new PdfNumber(tok.GetByteContent());
            NUnit.Framework.Assert.AreEqual("0", num.ToString());
            tok.NextValidToken();
            NUnit.Framework.Assert.AreEqual(tok.GetTokenType(), PdfTokenizer.TokenType.Name);
            name = new PdfName(tok.GetByteContent());
            NUnit.Framework.Assert.AreEqual("Prev", name.GetValue());
            tok.NextValidToken();
            NUnit.Framework.Assert.AreEqual(tok.GetTokenType(), PdfTokenizer.TokenType.Number);
            num = new PdfNumber(tok.GetByteContent());
            NUnit.Framework.Assert.AreEqual("-116.23", num.ToString());
        }
예제 #22
0
        protected internal override void CheckAnnotation(PdfDictionary annotDic)
        {
            PdfName subtype = annotDic.GetAsName(PdfName.Subtype);

            if (subtype == null)
            {
                throw new PdfAConformanceException(PdfAConformanceException.AnnotationType1IsNotPermitted).SetMessageParams
                          ("null");
            }
            if (forbiddenAnnotations.Contains(subtype))
            {
                throw new PdfAConformanceException(PdfAConformanceException.AnnotationType1IsNotPermitted).SetMessageParams
                          (subtype.GetValue());
            }
            PdfNumber ca = annotDic.GetAsNumber(PdfName.CA);

            if (ca != null && ca.FloatValue() != 1.0)
            {
                throw new PdfAConformanceException(PdfAConformanceException.AnAnnotationDictionaryShallNotContainTheCaKeyWithAValueOtherThan1
                                                   );
            }
            if (!annotDic.ContainsKey(PdfName.F))
            {
                throw new PdfAConformanceException(PdfAConformanceException.AnnotationShallContainKeyF);
            }
            int flags = (int)annotDic.GetAsInt(PdfName.F);

            if (!CheckFlag(flags, PdfAnnotation.PRINT) || CheckFlag(flags, PdfAnnotation.HIDDEN) || CheckFlag(flags, PdfAnnotation
                                                                                                              .INVISIBLE) || CheckFlag(flags, PdfAnnotation.NO_VIEW))
            {
                throw new PdfAConformanceException(PdfAConformanceException.TheFKeysPrintFlagBitShallBeSetTo1AndItsHiddenInvisibleAndNoviewFlagBitsShallBeSetTo0
                                                   );
            }
            if (subtype.Equals(PdfName.Text) && (!CheckFlag(flags, PdfAnnotation.NO_ZOOM) || !CheckFlag(flags, PdfAnnotation
                                                                                                        .NO_ROTATE)))
            {
                throw new PdfAConformanceException(PdfAConformanceException.TextAnnotationsShouldSetTheNozoomAndNorotateFlagBitsOfTheFKeyTo1
                                                   );
            }
            if (annotDic.ContainsKey(PdfName.C) || annotDic.ContainsKey(PdfName.IC))
            {
                if (!ICC_COLOR_SPACE_RGB.Equals(pdfAOutputIntentColorSpace))
                {
                    throw new PdfAConformanceException(PdfAConformanceException.DestoutputprofileInThePdfa1OutputintentDictionaryShallBeRgb
                                                       );
                }
            }
            PdfDictionary ap = annotDic.GetAsDictionary(PdfName.AP);

            if (ap != null)
            {
                if (ap.ContainsKey(PdfName.D) || ap.ContainsKey(PdfName.R))
                {
                    throw new PdfAConformanceException(PdfAConformanceException.AppearanceDictionaryShallContainOnlyTheNKeyWithStreamValue
                                                       );
                }
                PdfStream n = ap.GetAsStream(PdfName.N);
                if (n == null)
                {
                    throw new PdfAConformanceException(PdfAConformanceException.AppearanceDictionaryShallContainOnlyTheNKeyWithStreamValue
                                                       );
                }
                CheckResourcesOfAppearanceStreams(ap);
            }
            if (PdfName.Widget.Equals(subtype) && (annotDic.ContainsKey(PdfName.AA) || annotDic.ContainsKey(PdfName.A)
                                                   ))
            {
                throw new PdfAConformanceException(PdfAConformanceException.WidgetAnnotationDictionaryOrFieldDictionaryShallNotIncludeAOrAAEntry
                                                   );
            }
            if (annotDic.ContainsKey(PdfName.AA))
            {
                throw new PdfAConformanceException(PdfAConformanceException.AnAnnotationDictionaryShallNotContainAAKey);
            }
            if (CheckStructure(conformanceLevel))
            {
                if (contentAnnotations.Contains(subtype) && !annotDic.ContainsKey(PdfName.Contents))
                {
                    throw new PdfAConformanceException(PdfAConformanceException.AnnotationOfType1ShouldHaveContentsKey).SetMessageParams
                              (subtype);
                }
            }
        }
예제 #23
0
        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.GetAsName(PdfName.Subtype);
            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[i] = glyph;
                if (glyph.HasValidUnicode())
                {
                    //FontEncoding.codeToUnicode table has higher priority
                    if (fontEncoding.ConvertToByte(glyph.GetUnicode()) == i)
                    {
                        fontProgram.unicodeToGlyph[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);
        }
예제 #24
0
        internal static void FillFontDescriptor(iText.Kernel.Font.DocTrueTypeFont font, PdfDictionary fontDesc)
        {
            if (fontDesc == null)
            {
                ILog logger = LogManager.GetLogger(typeof(FontUtil));
                logger.Warn(iText.IO.LogMessageConstant.FONT_DICTIONARY_WITH_NO_FONT_DESCRIPTOR);
                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());
            }
            v = fontDesc.GetAsNumber(PdfName.MissingWidth);
            if (v != null)
            {
                font.missingWidth = v.IntValue();
            }
            PdfName fontStretch = fontDesc.GetAsName(PdfName.FontStretch);

            if (fontStretch != null)
            {
                font.SetFontStretch(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;
                }
            }
        }
예제 #25
0
 /// <summary>Checks if the provided dictionary is a valid font dictionary of the provided font type.</summary>
 /// <returns><c>true</c> if the passed dictionary is a valid dictionary, <c>false</c> otherwise</returns>
 private static bool CheckFontDictionary(PdfDictionary fontDic, PdfName fontType, bool isException)
 {
     if (fontDic == null || fontDic.Get(PdfName.Subtype) == null || !fontDic.Get(PdfName.Subtype).Equals(fontType
                                                                                                         ))
     {
         if (isException)
         {
             throw new PdfException(PdfException.DictionaryDoesntHave1FontData).SetMessageParams(fontType.GetValue());
         }
         return(false);
     }
     return(true);
 }
예제 #26
0
        protected internal override void CheckAnnotation(PdfDictionary annotDic)
        {
            PdfName subtype = annotDic.GetAsName(PdfName.Subtype);

            if (subtype == null)
            {
                throw new PdfAConformanceException(PdfAConformanceException.ANNOTATION_TYPE_0_IS_NOT_PERMITTED).SetMessageParams
                          ("null");
            }
            if (forbiddenAnnotations.Contains(subtype))
            {
                throw new PdfAConformanceException(PdfAConformanceException.ANNOTATION_TYPE_0_IS_NOT_PERMITTED).SetMessageParams
                          (subtype.GetValue());
            }
            PdfNumber ca = annotDic.GetAsNumber(PdfName.CA);

            if (ca != null && ca.FloatValue() != 1.0)
            {
                throw new PdfAConformanceException(PdfAConformanceException.AN_ANNOTATION_DICTIONARY_SHALL_NOT_CONTAIN_THE_CA_KEY_WITH_A_VALUE_OTHER_THAN_1
                                                   );
            }
            if (!annotDic.ContainsKey(PdfName.F))
            {
                throw new PdfAConformanceException(PdfAConformanceException.AN_ANNOTATION_DICTIONARY_SHALL_CONTAIN_THE_F_KEY
                                                   );
            }
            int flags = (int)annotDic.GetAsInt(PdfName.F);

            if (!CheckFlag(flags, PdfAnnotation.PRINT) || CheckFlag(flags, PdfAnnotation.HIDDEN) || CheckFlag(flags, PdfAnnotation
                                                                                                              .INVISIBLE) || CheckFlag(flags, PdfAnnotation.NO_VIEW))
            {
                throw new PdfAConformanceException(PdfAConformanceException.THE_F_KEYS_PRINT_FLAG_BIT_SHALL_BE_SET_TO_1_AND_ITS_HIDDEN_INVISIBLE_AND_NOVIEW_FLAG_BITS_SHALL_BE_SET_TO_0
                                                   );
            }
            if (subtype.Equals(PdfName.Text) && (!CheckFlag(flags, PdfAnnotation.NO_ZOOM) || !CheckFlag(flags, PdfAnnotation
                                                                                                        .NO_ROTATE)))
            {
                throw new PdfAConformanceException(PdfAConformanceLogMessageConstant.TEXT_ANNOTATIONS_SHOULD_SET_THE_NOZOOM_AND_NOROTATE_FLAG_BITS_OF_THE_F_KEY_TO_1
                                                   );
            }
            if (annotDic.ContainsKey(PdfName.C) || annotDic.ContainsKey(PdfName.IC))
            {
                if (!ICC_COLOR_SPACE_RGB.Equals(pdfAOutputIntentColorSpace))
                {
                    throw new PdfAConformanceException(PdfAConformanceException.DESTOUTPUTPROFILE_IN_THE_PDFA1_OUTPUTINTENT_DICTIONARY_SHALL_BE_RGB
                                                       );
                }
            }
            PdfDictionary ap = annotDic.GetAsDictionary(PdfName.AP);

            if (ap != null)
            {
                if (ap.ContainsKey(PdfName.D) || ap.ContainsKey(PdfName.R))
                {
                    throw new PdfAConformanceException(PdfAConformanceException.APPEARANCE_DICTIONARY_SHALL_CONTAIN_ONLY_THE_N_KEY_WITH_STREAM_VALUE
                                                       );
                }
                PdfStream n = ap.GetAsStream(PdfName.N);
                if (n == null)
                {
                    throw new PdfAConformanceException(PdfAConformanceException.APPEARANCE_DICTIONARY_SHALL_CONTAIN_ONLY_THE_N_KEY_WITH_STREAM_VALUE
                                                       );
                }
                CheckResourcesOfAppearanceStreams(ap);
            }
            if (PdfName.Widget.Equals(subtype) && (annotDic.ContainsKey(PdfName.AA) || annotDic.ContainsKey(PdfName.A)
                                                   ))
            {
                throw new PdfAConformanceException(PdfAConformanceException.WIDGET_ANNOTATION_DICTIONARY_OR_FIELD_DICTIONARY_SHALL_NOT_INCLUDE_A_OR_AA_ENTRY
                                                   );
            }
            if (annotDic.ContainsKey(PdfName.AA))
            {
                throw new PdfAConformanceException(PdfAConformanceException.AN_ANNOTATION_DICTIONARY_SHALL_NOT_CONTAIN_AA_KEY
                                                   );
            }
            if (CheckStructure(conformanceLevel))
            {
                if (contentAnnotations.Contains(subtype) && !annotDic.ContainsKey(PdfName.Contents))
                {
                    throw new PdfAConformanceException(PdfAConformanceException.ANNOTATION_OF_TYPE_0_SHOULD_HAVE_CONTENTS_KEY)
                          .SetMessageParams(subtype.GetValue());
                }
            }
        }
예제 #27
0
 protected internal static bool CheckFontDictionary(PdfDictionary fontDic, PdfName fontType, bool isException
                                                    )
 {
     if (fontDic == null || fontDic.Get(PdfName.Subtype) == null || !fontDic.Get(PdfName.Subtype).Equals(fontType
                                                                                                         ))
     {
         if (isException)
         {
             throw new PdfException(PdfException.DictionaryNotContainFontData).SetMessageParams(fontType.GetValue());
         }
         return(false);
     }
     return(true);
 }
 public virtual String GetRole()
 {
     return(currRole.GetValue());
 }