/** * Gets a list of X509CRL objects from a Document Security Store. * @return a list of CRLs * @throws GeneralSecurityException * @throws IOException */ virtual public List <X509Crl> GetCRLsFromDSS() { List <X509Crl> crls = new List <X509Crl>(); if (dss == null) { return(crls); } PdfArray crlarray = dss.GetAsArray(PdfName.CRLS); if (crlarray == null) { return(crls); } X509CrlParser crlParser = new X509CrlParser(); for (int i = 0; i < crlarray.Size; ++i) { PRStream stream = (PRStream)crlarray.GetAsStream(i); X509Crl crl = crlParser.ReadCrl(new MemoryStream(PdfReader.GetStreamBytes(stream))); crls.Add(crl); } return(crls); }
/// <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 <code>/Font</code>, must have an indirect reference.</param> internal PdfType3Font(PdfDictionary fontDictionary) : base(fontDictionary) { subset = true; embedded = true; fontProgram = new Type3Font(false); CMapToUnicode toUni = FontUtil.ProcessToUnicode(fontDictionary.Get(PdfName.ToUnicode)); fontEncoding = DocFontEncoding.CreateDocFontEncoding(fontDictionary.Get(PdfName.Encoding), toUni); 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); foreach (PdfName glyphName in charProcsDic.KeySet()) { int unicode = AdobeGlyphList.NameToUnicode(glyphName.GetValue()); if (unicode != -1 && fontEncoding.CanEncode(unicode)) { int code = fontEncoding.ConvertToByte(unicode); ((Type3Font)GetFontProgram()).AddGlyph(code, unicode, widths[code], null, new Type3Glyph(charProcsDic.GetAsStream (glyphName), GetDocument())); } } FillFontDescriptor(fontDictionary.GetAsDictionary(PdfName.FontDescriptor)); }
public void countSheetsFormatsPdf(string Path, FileInfo fn) { PdfArray mediabox; int urx, ury; PdfReader reader = new PdfReader(Path); int numberOfPages = reader.NumberOfPages; List <string> formats = new List <string>(); for (int i = 1; i <= numberOfPages; i++) { PdfDictionary pageDict = reader.GetPageN(i); mediabox = pageDict.GetAsArray(PdfName.MEDIABOX); urx = mediabox.GetAsNumber(2).IntValue; ury = mediabox.GetAsNumber(3).IntValue; int[] sides = new int[] { urx, ury }; int shortSide = sides.Min(); int longSide = sides.Max(); if (shortSide < 600 && longSide < 900) { formats.Add("A4"); } else if (shortSide < 900 && longSide < 1200) { formats.Add("A3"); } else if (shortSide < 1200 && longSide < 1700) { formats.Add("A2"); } else if (shortSide < 1700 && longSide < 2400) { formats.Add("A1"); } else if (shortSide < 2400 && longSide < 3400) { formats.Add("A0"); } } var fUniq = formats.Distinct(); string format = String.Join("/", fUniq); fn.countSheets = numberOfPages.ToString(); fn.formatPages = format; }
protected void ScaleDown(PdfPage destPage, PdfDictionary pageDictSrc, PdfName box, float scale) { PdfArray original = pageDictSrc.GetAsArray(box); if (original != null) { float width = original.GetAsNumber(2).FloatValue() - original.GetAsNumber(0).FloatValue(); float height = original.GetAsNumber(3).FloatValue() - original.GetAsNumber(1).FloatValue(); PdfArray result = new PdfArray(); result.Add(new PdfNumber(0)); result.Add(new PdfNumber(0)); result.Add(new PdfNumber(width * scale)); result.Add(new PdfNumber(height * scale)); destPage.Put(box, result); } }
private void GetAllFieldNames(PdfArray fields, ICollection <String> existingFields) { foreach (PdfObject field in fields) { PdfDictionary dic = (PdfDictionary)field; PdfString name = dic.GetAsString(PdfName.T); if (name != null) { existingFields.Add(name.ToUnicodeString()); } PdfArray kids = dic.GetAsArray(PdfName.Kids); if (kids != null) { GetAllFieldNames(kids, existingFields); } } }
protected void ManipulatePdf(String dest) { PdfDocument pdfDoc = new PdfDocument(new PdfReader(SRC), new PdfWriter(dest)); PdfDictionary root = pdfDoc.GetCatalog().GetPdfObject(); PdfDictionary names = root.GetAsDictionary(PdfName.Names); PdfDictionary embeddedFiles = names.GetAsDictionary(PdfName.EmbeddedFiles); PdfArray namesArray = embeddedFiles.GetAsArray(PdfName.Names); // Remove the description of the embedded file namesArray.Remove(0); // Remove the reference to the embedded file. namesArray.Remove(0); pdfDoc.Close(); }
// ******************************************************************** // Fct: ParseDoc // // Descr: - // // Owner: erst // ******************************************************************** public static void ParseDoc(String src, String dest) { try { PdfDocument ScrPdf = new PdfDocument(new PdfReader(src)); // PdfDocument DestPdf = new PdfDocument(new PdfWriter(dest)); PdfPage page = ScrPdf.GetFirstPage(); // Collects all comment annotations in the document Collection <PdfAnnotation> annotations = new Collection <PdfAnnotation>(page.GetAnnotations()); foreach (PdfAnnotation annot in annotations) { if (annot.GetType().Equals((typeof(iText.Kernel.Pdf.Annot.PdfTextAnnotation)))) { PdfDictionary annotDictionary = annot.GetPdfObject(); //Rect is the annotation rectangle defining the location of the annotation on the page PdfArray Arr = annotDictionary.GetAsArray(PdfName.Rect); int x = Arr.GetAsNumber(0).IntValue(); int y = Arr.GetAsNumber(1).IntValue(); Rectangle rect = annotDictionary.GetAsRectangle(PdfName.Rect); float recX = rect.GetX(); float recY = rect.GetY(); //Read the content String content = annotDictionary.Get(PdfName.Contents).ToString(); string output = content; } } // DestPdf.Close(); ScrPdf.Close(); } catch (Exception ex) { throw ex; } finally { } }
protected void ManipulatePdf(String dest) { PdfDocument pdfDoc = new PdfDocument(new PdfReader(SRC), new PdfWriter(dest)); Dictionary <String, PdfString> renamed = new Dictionary <String, PdfString>(); PdfNameTree nameTree = pdfDoc.GetCatalog().GetNameTree(PdfName.Dests); IDictionary <String, PdfObject> names = nameTree.GetNames(); List <String> keys = new List <string>(names.Keys); // Loop over all named destinations and rename its string values with new names foreach (String key in keys) { String newName = "new" + key; names.Add(newName, names[key]); names.Remove(key); renamed.Add(key, new PdfString(newName)); } // Specify that the name tree has been modified // This implies that the name tree will be rewritten on close() method. nameTree.SetModified(); PdfDictionary page = pdfDoc.GetPage(1).GetPdfObject(); PdfArray annotations = page.GetAsArray(PdfName.Annots); // Loop over all link annotations of the first page and change their destinations. for (int i = 0; i < annotations.Size(); i++) { PdfDictionary annotation = annotations.GetAsDictionary(i); PdfDictionary action = annotation.GetAsDictionary(PdfName.A); if (action == null) { continue; } PdfString n = action.GetAsString(PdfName.D); if (n != null && renamed.ContainsKey(n.ToString())) { action.Put(PdfName.D, renamed[n.ToString()]); } } pdfDoc.Close(); }
/** * Creates an object that can inform you about the type of signature * in a signature dictionary as well as some of the permissions * defined by the signature. */ public SignaturePermissions(PdfDictionary sigDict, SignaturePermissions previous) { if (previous != null) { annotationsAllowed &= previous.AnnotationsAllowed; fillInAllowed &= previous.FillInAllowed; fieldLocks.AddRange(previous.FieldLocks); } PdfArray reference = sigDict.GetAsArray(PdfName.REFERENCE); if (reference != null) { for (int i = 0; i < reference.Size; i++) { PdfDictionary dict = reference.GetAsDict(i); PdfDictionary parameters = dict.GetAsDict(PdfName.TRANSFORMPARAMS); if (PdfName.DOCMDP.Equals(dict.GetAsName(PdfName.TRANSFORMMETHOD))) { certification = true; } PdfName action = parameters.GetAsName(PdfName.ACTION); if (action != null) { fieldLocks.Add(new FieldLock(action, parameters.GetAsArray(PdfName.FIELDS))); } PdfNumber p = parameters.GetAsNumber(PdfName.P); if (p == null) { continue; } switch (p.IntValue) { case 1: fillInAllowed = false; break; case 2: annotationsAllowed = false; break; } } } }
private void CheckAnnotations(PdfDictionary page) { PdfArray annots = page.GetAsArray(PdfName.Annots); if (annots != null) { for (int i = 0; i < annots.Size(); i++) { PdfDictionary annot = annots.GetAsDictionary(i); CheckAnnotation(annot); PdfDictionary action = annot.GetAsDictionary(PdfName.A); if (action != null) { CheckAction(action); } } } }
public static Content.Annotation ToCircle(this PdfDictionary annotation) { PdfArray data = annotation.GetAsArray(PdfName.RECT); if (data == null) { return(null); } var min = Point.ByCoordinates(data[0].ToDouble(), data[1].ToDouble()); var max = Point.ByCoordinates(data[2].ToDouble(), data[3].ToDouble()); var center = Point.ByCoordinates(min.X + ((max.X - min.X) / 2), min.Y + ((max.Y - min.Y) / 2)); var radius = (max.X - min.X) / 2; return(new Content.Annotation(annotation, Circle.ByCenterPointRadius(center, radius))); }
private PdfArray GetFormFields(PdfArray array) { PdfArray fields = new PdfArray(); // explicit iteration to resolve indirect references on get(). // TODO DEVSIX-591 for (int i = 0; i < array.Size(); i++) { PdfDictionary field = array.GetAsDictionary(i); PdfArray kids = field.GetAsArray(PdfName.Kids); fields.Add(field); if (kids != null) { fields.AddAll(GetFormFields(kids)); } } return(fields); }
public static Content.Annotation ToRectangle(this PdfDictionary annotation) { PdfArray data = annotation.GetAsArray(PdfName.RECT); if (data == null) { return(null); } List <Point> points = new List <Point>(); points.Add(Point.ByCoordinates(data[0].ToDouble(), data[1].ToDouble())); points.Add(Point.ByCoordinates(data[0].ToDouble(), data[3].ToDouble())); points.Add(Point.ByCoordinates(data[2].ToDouble(), data[3].ToDouble())); points.Add(Point.ByCoordinates(data[2].ToDouble(), data[1].ToDouble())); return(new Content.Annotation(annotation, Rectangle.ByCornerPoints(points))); }
private static IEnumerable <string> GetOrderedSignatureNames(PdfReader reader) { ArrayList signatureNames = reader.AcroFields.GetSignatureNames(); Dictionary <string, long> signatureNamesDict = new Dictionary <string, long>(); foreach (string signatureName in signatureNames) { PdfDictionary dict = reader.AcroFields.GetSignatureDictionary(signatureName); PdfArray byteRange = dict.GetAsArray(PdfName.Byterange); var offset = ((PdfNumber)byteRange[2]).IntValue; var end = offset + ((PdfNumber)byteRange[3]).IntValue; signatureNamesDict.Add(signatureName, end); } var orderedSignatures = signatureNamesDict.OrderBy(x => x.Value).Select(x => x.Key); return(orderedSignatures); }
virtual public void CopyTaggedPdf15() { InitializeDocument("15"); copy.SetMergeFields(); PdfReader reader1 = new PdfReader(SOURCE61); PdfReader reader2 = new PdfReader(SOURCE62); copy.AddDocument(reader1); copy.AddDocument(reader2); document.Close(); reader1.Close(); reader2.Close(); PdfReader reader = new PdfReader(output); PdfDictionary catalog = reader.Catalog; PdfDictionary structTreeRoot = catalog.GetAsDict(PdfName.STRUCTTREEROOT); PdfDictionary structParent = structTreeRoot.GetAsDict(PdfName.PARENTTREE); PdfArray nums = structParent.GetAsArray(PdfName.NUMS); PdfDictionary acroForm = catalog.GetAsDict(PdfName.ACROFORM); PdfDictionary fonts = acroForm.GetAsDict(PdfName.DR).GetAsDict(PdfName.FONT); Assert.AreEqual(new PdfName("Helvetica"), fonts.GetAsDict(new PdfName("Helv")).GetAsName(PdfName.BASEFONT)); Assert.AreEqual(new PdfName("ZapfDingbats"), fonts.GetAsDict(new PdfName("ZaDb")).GetAsName(PdfName.BASEFONT)); Assert.AreEqual(new PdfName("ArialMT"), fonts.GetAsDict(new PdfName("ArialMT")).GetAsName(PdfName.BASEFONT)); Assert.AreEqual(new PdfName("CourierStd"), fonts.GetAsDict(new PdfName("CourierStd")).GetAsName(PdfName.BASEFONT)); Assert.AreEqual(1, nums.GetAsNumber(2).IntValue); Assert.AreEqual(4, nums.GetAsNumber(8).IntValue); Assert.AreEqual(acroForm.GetAsArray(PdfName.FIELDS).GetAsIndirectObject(0).Number, nums.GetAsDict(5).GetAsDict(PdfName.K).GetAsIndirectObject(PdfName.OBJ).Number); Assert.AreEqual(acroForm.GetAsArray(PdfName.FIELDS).GetAsIndirectObject(2).Number, nums.GetAsDict(11).GetAsDict(PdfName.K).GetAsIndirectObject(PdfName.OBJ).Number); Assert.AreEqual(acroForm.GetAsArray(PdfName.FIELDS).GetAsDict(1).GetAsArray(PdfName.KIDS).GetAsIndirectObject(0).Number, nums.GetAsDict(3).GetAsDict(PdfName.K).GetAsIndirectObject(PdfName.OBJ).Number); Assert.AreEqual(acroForm.GetAsArray(PdfName.FIELDS).GetAsDict(1).GetAsArray(PdfName.KIDS).GetAsIndirectObject(1).Number, nums.GetAsDict(9).GetAsDict(PdfName.K).GetAsIndirectObject(PdfName.OBJ).Number); Assert.AreEqual(2, acroForm.GetAsArray(PdfName.FIELDS).GetAsDict(0).GetAsNumber(PdfName.STRUCTPARENT).IntValue); Assert.AreEqual(1, acroForm.GetAsArray(PdfName.FIELDS).GetAsDict(1).GetAsArray(PdfName.KIDS).GetAsDict(0).GetAsNumber(PdfName.STRUCTPARENT).IntValue); Assert.AreEqual(5, acroForm.GetAsArray(PdfName.FIELDS).GetAsDict(2).GetAsNumber(PdfName.STRUCTPARENT).IntValue); Assert.AreEqual(4, acroForm.GetAsArray(PdfName.FIELDS).GetAsDict(1).GetAsArray(PdfName.KIDS).GetAsDict(1).GetAsNumber(PdfName.STRUCTPARENT).IntValue); reader.Close(); }
// extension method to the outlines // in the itext package public static int GetPageNumber(this PdfOutline outline, PdfDocument doc) { try { PdfDictionary dict = outline.GetContent().GetAsDictionary(PdfName.A); if (dict == null) { PdfArray array = outline.GetContent().GetAsArray(PdfName.Dest); if (array != null) { PdfObject obj = array.SubList(0, 1)[0]; if (obj is PdfNumber) { return(((PdfNumber)obj).IntValue() + 1); } else if (obj is PdfDictionary) { return(doc.GetPageNumber((PdfDictionary)obj)); } else { return(-3); } } else { return(-1); } } dict = dict.GetAsArray(PdfName.D).GetAsDictionary(0); return(doc.GetPageNumber(dict)); } #pragma warning disable CS0168 // The variable 'e' is declared but never used catch (Exception e) #pragma warning restore CS0168 // The variable 'e' is declared but never used { return(-2); } }
/// <summary>Creates a Type3 font based on an existing font dictionary, which must be an indirect object.</summary> /// <param name="fontDictionary">a dictionary of type <code>/Font</code>, must have an indirect reference.</param> internal PdfType3Font(PdfDictionary fontDictionary) : base(fontDictionary) { EnsureObjectIsAddedToDocument(fontDictionary); CheckFontDictionary(fontDictionary, PdfName.Type3); subset = true; embedded = true; fontProgram = new Type3FontProgram(false); fontEncoding = DocFontEncoding.CreateDocFontEncoding(fontDictionary.Get(PdfName.Encoding), null, false); 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); } 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); double[] fontMatrix = new double[6]; for (int i = 0; i < fontMatrixArray.Size(); i++) { fontMatrix[i] = ((PdfNumber)fontMatrixArray.Get(i)).GetValue(); } SetFontMatrix(fontMatrix); foreach (PdfName glyphName in charProcsDic.KeySet()) { int unicode = (int)AdobeGlyphList.NameToUnicode(glyphName.GetValue()); if (unicode != -1 && fontEncoding.CanEncode(unicode)) { int code = fontEncoding.ConvertToByte(unicode); ((Type3FontProgram)GetFontProgram()).AddGlyph(code, unicode, widths[code], null, new Type3Glyph(charProcsDic .GetAsStream(glyphName), GetDocument())); } } }
internal static void ValidateTemplateForSignedDeferredResult(String output, String sigFieldName, PdfName filter , PdfName subFilter, int estimatedSize) { PdfDocument outDocument = new PdfDocument(new PdfReader(output)); PdfObject outSigDictObj = PdfAcroForm.GetAcroForm(outDocument, false).GetField(sigFieldName).GetValue(); NUnit.Framework.Assert.IsTrue(outSigDictObj.IsDictionary()); PdfDictionary outSigDict = (PdfDictionary)outSigDictObj; PdfArray byteRange = outSigDict.GetAsArray(PdfName.ByteRange); NUnit.Framework.Assert.IsNotNull(byteRange); NUnit.Framework.Assert.IsTrue(byteRange.Size() == 4); NUnit.Framework.Assert.AreEqual(filter, outSigDict.GetAsName(PdfName.Filter)); NUnit.Framework.Assert.AreEqual(subFilter, outSigDict.GetAsName(PdfName.SubFilter)); PdfString outSigContents = outSigDict.GetAsString(PdfName.Contents); NUnit.Framework.Assert.IsTrue(outSigContents.IsHexWriting()); NUnit.Framework.Assert.AreEqual(new byte[estimatedSize], outSigContents.GetValueBytes()); }
internal void ExtractAttachments(string file_name, string folderName, PdfWriter write) { PdfDictionary documentNames = null; PdfDictionary embeddedFiles = null; PdfDictionary fileArray = null; PdfDictionary file = null; PRStream stream = null; PdfReader reader = new PdfReader(file_name); PdfDictionary catalog = reader.Catalog; documentNames = (PdfDictionary)PdfReader.GetPdfObject(catalog.Get(PdfName.NAMES)); if (documentNames != null) { embeddedFiles = (PdfDictionary)PdfReader.GetPdfObject(documentNames.Get(PdfName.EMBEDDEDFILES)); if (embeddedFiles != null) { PdfArray filespecs = embeddedFiles.GetAsArray(PdfName.NAMES); for (int i = 0; i < filespecs.Size; i++) { i++; fileArray = filespecs.GetAsDict(i); file = fileArray.GetAsDict(PdfName.EF); foreach (PdfName key in file.Keys) { stream = (PRStream)PdfReader.GetPdfObject(file.GetAsIndirectObject(key)); string attachedFileName = folderName + fileArray.GetAsString(key).ToString(); byte[] attachedFileBytes = PdfReader.GetStreamBytes(stream); //graba el anexo extraido System.IO.File.WriteAllBytes(attachedFileName, attachedFileBytes); //adjunta los anexos PdfFileSpecification pfs = PdfFileSpecification.FileEmbedded(write, attachedFileName, fileArray.GetAsString(key).ToString(), null); write.AddFileAttachment(pfs); //borramos los archivos extraidos System.IO.File.Delete(attachedFileName); } } } } }
private void AddChildToExistingParent(PdfDictionary fieldDic, ICollection <String> existingFields, IDictionary <String, PdfFormField> fieldsTo) { PdfDictionary parent = fieldDic.GetAsDictionary(PdfName.Parent); if (parent == null) { return; } PdfString parentName = parent.GetAsString(PdfName.T); if (parentName != null) { String name = parentName.ToUnicodeString(); if (existingFields.Contains(name)) { PdfArray kids = parent.GetAsArray(PdfName.Kids); foreach (PdfObject kid in kids) { if (((PdfDictionary)kid).Get(PdfName.T).Equals(fieldDic.Get(PdfName.T))) { PdfFormField kidField = MakeFormField(kid); PdfFormField field = MakeFormField(fieldDic); if (kidField == null || field == null) { continue; } fieldsTo.Put(kidField.GetFieldName().ToUnicodeString(), kidField); PdfFormField mergedField = MergeFieldsWithTheSameName(field); formTo.GetFormFields().Put(mergedField.GetFieldName().ToUnicodeString(), mergedField); return; } } kids.Add(fieldDic); } else { parent.Put(PdfName.Kids, new PdfArray(fieldDic)); AddChildToExistingParent(parent, existingFields); } } }
/// <summary>This method removes all widget annotation entries from the form field the given annotation merged with. /// </summary> public virtual void ReleaseFormFieldFromWidgetAnnotation() { PdfDictionary annotDict = GetPdfObject(); foreach (PdfName entry in widgetEntries) { annotDict.Remove(entry); } PdfDictionary parent = annotDict.GetAsDictionary(PdfName.Parent); if (parent != null && annotDict.Size() == 1) { PdfArray kids = parent.GetAsArray(PdfName.Kids); kids.Remove(annotDict); if (kids.Size() == 0) { parent.Remove(PdfName.Kids); } } }
private void AddChildToExistingParent(PdfDictionary fieldDic, ICollection <String> existingFields) { PdfDictionary parent = fieldDic.GetAsDictionary(PdfName.Parent); PdfString parentName = parent.GetAsString(PdfName.T); if (parentName != null) { String name = parentName.ToUnicodeString(); if (existingFields.Contains(name)) { PdfArray kids = parent.GetAsArray(PdfName.Kids); kids.Add(fieldDic); } else { parent.Put(PdfName.Kids, new PdfArray(fieldDic)); AddChildToExistingParent(parent, existingFields); } } }
private void CheckAnnotations(PdfDictionary page) { PdfArray annots = page.GetAsArray(PdfName.Annots); if (annots != null) { // explicit iteration to resolve indirect references on get(). // TODO DEVSIX-591 for (int i = 0; i < annots.Size(); i++) { PdfDictionary annot = annots.GetAsDictionary(i); CheckAnnotation(annot); PdfDictionary action = annot.GetAsDictionary(PdfName.A); if (action != null) { CheckAction(action); } } } }
internal static TrueTypeFont CreateFontProgram(PdfDictionary fontDictionary, FontEncoding fontEncoding, CMapToUnicode toUnicode) { iText.Kernel.Font.DocTrueTypeFont fontProgram = new iText.Kernel.Font.DocTrueTypeFont(fontDictionary); FillFontDescriptor(fontProgram, fontDictionary.GetAsDictionary(PdfName.FontDescriptor)); 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); //FontEncoding.codeToUnicode table has higher priority if (glyph.HasValidUnicode() && 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); }
/** * @param colorSpaceName the name of the color space. If null, a bi-tonal (black and white) color space is assumed. * @return the components per pixel for the specified color space */ private static int GetComponentsPerPixel(PdfName colorSpaceName, PdfDictionary colorSpaceDic) { if (colorSpaceName == null) { return(1); } if (colorSpaceName.Equals(PdfName.DEVICEGRAY)) { return(1); } if (colorSpaceName.Equals(PdfName.DEVICERGB)) { return(3); } if (colorSpaceName.Equals(PdfName.DEVICECMYK)) { return(4); } if (colorSpaceDic != null) { PdfArray colorSpace = colorSpaceDic.GetAsArray(colorSpaceName); if (colorSpace != null) { if (PdfName.INDEXED.Equals(colorSpace.GetAsName(0))) { return(1); } } else { PdfName tempName = colorSpaceDic.GetAsName(colorSpaceName); if (tempName != null) { return(GetComponentsPerPixel(tempName, colorSpaceDic)); } } } throw new ArgumentException("Unexpected color space " + colorSpaceName); }
protected void ManipulatePdf(String dest) { PdfDocument pdfDoc = new PdfDocument(new PdfReader(SRC), new PdfWriter(dest)); PdfCatalog catalog = pdfDoc.GetCatalog(); PdfOCProperties ocProps = catalog.GetOCProperties(true); PdfDictionary occd = (PdfDictionary)ocProps.GetPdfObject().Get(PdfName.D); PdfArray order = occd.GetAsArray(PdfName.Order); PdfObject nestedLayers = order.Get(0); PdfObject nestedLayerArray = order.Get(1); PdfObject groupedLayers = order.Get(2); PdfObject radioGroup = order.Get(3); order.Set(0, radioGroup); order.Set(1, nestedLayers); order.Set(2, nestedLayerArray); order.Set(3, groupedLayers); pdfDoc.Close(); }
private static void ProcessStructElem(PdfStructElem elem, StringBuilder builder) { PdfDictionary page = elem.GetPdfObject().GetAsDictionary(PdfName.Pg); if (page == null) { return; } PdfStream contents = page.GetAsStream(PdfName.Contents); if (contents != null) { builder.Append("Content: \n" + Encoding.UTF8.GetString(contents.GetBytes()) + "\n"); } else { PdfArray array = page.GetAsArray(PdfName.Contents); builder.Append("Contents array: " + array + "\n"); } }
/// <param name="colorSpaceName">the name of the color space. If null, a bi-tonal (black and white) color space is assumed. /// </param> /// <returns>the components per pixel for the specified color space</returns> private static int GetComponentsPerPixel(PdfName colorSpaceName, PdfDictionary colorSpaceDic) { if (colorSpaceName == null) { return(1); } if (colorSpaceName.Equals(PdfName.DeviceGray)) { return(1); } if (colorSpaceName.Equals(PdfName.DeviceRGB)) { return(3); } if (colorSpaceName.Equals(PdfName.DeviceCMYK)) { return(4); } if (colorSpaceDic != null) { PdfArray colorSpace = colorSpaceDic.GetAsArray(colorSpaceName); if (colorSpace != null) { if (PdfName.Indexed.Equals(colorSpace.GetAsName(0))) { return(1); } } else { PdfName tempName = colorSpaceDic.GetAsName(colorSpaceName); if (tempName != null) { return(GetComponentsPerPixel(tempName, colorSpaceDic)); } } } throw new InlineImageParsingUtils.InlineImageParseException(PdfException.UnexpectedColorSpace1).SetMessageParams (colorSpaceName); }
public static string DNATool(string filePath, string fileName, string siteAddress, StreamWriter writer) //Writes found assets to CSV and outputs any errors { string error = ""; PdfReader reader = new PdfReader(filePath); for (int page = 1; page <= reader.NumberOfPages; page++) //Loops through all the pages { PdfDictionary pageDict = reader.GetPageN(page); //Honestly not sure how this works... PdfArray annotArray = pageDict.GetAsArray(PdfName.ANNOTS); if (annotArray == null) //If there are no annotations on that page { error += "WARNING: No annotaions found (Page " + page + ")\n"; continue; } foreach (PdfObject annot in annotArray) //Loops through every annotation on that page { PdfDictionary annotDict = (PdfDictionary)PdfReader.GetPdfObject(annot); if (annotDict.Get(PdfName.SUBTYPE).Equals(PdfName.LINK) || annotDict.Get(PdfName.SUBTYPE).Equals(PdfName.WIDGET)) //If the annotation is a hyperlink { PdfDictionary annotAction = (PdfDictionary)PdfReader.GetPdfObject(annotDict.Get(PdfName.A)); if (annotAction.Get(PdfName.S).Equals(PdfName.URI)) { string foundURL = annotAction.GetAsString(PdfName.URI).ToString(); int index = foundURL.IndexOf("assetnum"); //Searches for blue box links if (index != -1) //If it's a blue box { string assetNum = foundURL.Substring(index + 9, 5); //From counting writer.WriteLine("\"" + assetNum + "\",,\"" + siteAddress + "/" + fileName + "\",,\"" + fileName + "\""); //Adds the asset to the CSV file } } } } } return(error); }
private void AddPagesFromDict(PdfObject dictRef, IList <PdfDictionary> pages, IList <RefKey> pagesRef) { PdfDictionary dict = (PdfDictionary)PdfReader.GetPdfObject(dictRef); if (dict.IsPages()) { PdfArray kids = dict.GetAsArray(PdfName.KIDS); if (kids == null) { return; } foreach (PdfObject kid in kids) { AddPagesFromDict(kid, pages, pagesRef); } } else if (dict.IsPage()) { pages.Add(dict); pagesRef.Add(new RefKey((PRIndirectReference)dictRef)); } }
/** * @param colorSpaceName the name of the color space. If null, a bi-tonal (black and white) color space is assumed. * @return the components per pixel for the specified color space */ private static int GetComponentsPerPixel(PdfName colorSpaceName, PdfDictionary colorSpaceDic){ if (colorSpaceName == null) return 1; if (colorSpaceName.Equals(PdfName.DEVICEGRAY)) return 1; if (colorSpaceName.Equals(PdfName.DEVICERGB)) return 3; if (colorSpaceName.Equals(PdfName.DEVICECMYK)) return 4; if (colorSpaceDic != null){ PdfArray colorSpace = colorSpaceDic.GetAsArray(colorSpaceName); if (colorSpace != null){ if (PdfName.INDEXED.Equals(colorSpace.GetAsName(0))){ return 1; } } } throw new ArgumentException("Unexpected color space " + colorSpaceName); }
/** * 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)); }
/// <summary> /// Gets an array from a dictionary and checks if it contains references to OCGs that need to be removed </summary> /// <param name="dict"> the dictionary </param> /// <param name="name"> the name of an array entry </param> /// <param name="ocgs"> the removal list </param> private void RemoveOCGsFromArray(PdfDictionary dict, PdfName name, ICollection<string> ocgs) { if (dict == null) { return; } PdfArray array = dict.GetAsArray(name); if (array == null) { return; } RemoveOCGsFromArray(array, ocgs); }
/** * Creates an object that can inform you about the type of signature * in a signature dictionary as well as some of the permissions * defined by the signature. */ public SignaturePermissions(PdfDictionary sigDict, SignaturePermissions previous) { if (previous != null) { annotationsAllowed &= previous.AnnotationsAllowed; fillInAllowed &= previous.FillInAllowed; fieldLocks.AddRange(previous.FieldLocks); } PdfArray reference = sigDict.GetAsArray(PdfName.REFERENCE); if (reference != null) { for (int i = 0; i < reference.Size; i++) { PdfDictionary dict = reference.GetAsDict(i); PdfDictionary parameters = dict.GetAsDict(PdfName.TRANSFORMPARAMS); if (PdfName.DOCMDP.Equals(dict.GetAsName(PdfName.TRANSFORMMETHOD))) certification = true; PdfName action = parameters.GetAsName(PdfName.ACTION); if (action != null) fieldLocks.Add(new FieldLock(action, parameters.GetAsArray(PdfName.FIELDS))); PdfNumber p = parameters.GetAsNumber(PdfName.P); if (p == null) continue; switch (p.IntValue) { case 1: fillInAllowed = false; break; case 2: annotationsAllowed = false; break; } } } }
/// <summary> /// Removes annotations from a page dictionary </summary> /// <param name="page"> a page dictionary </param> /// <param name="ocgs"> a set of names of OCG layers </param> private void RemoveAnnots(PdfDictionary page, ICollection<string> ocgs) { PdfArray annots = page.GetAsArray(PdfName.ANNOTS); if (annots == null) { return; } IList<int?> remove = new List<int?>(); for (int i = annots.Size; i > 0; ) { PdfDictionary annot = annots.GetAsDict(--i); if (IsToBeRemoved(annot.GetAsDict(PdfName.OC), ocgs)) { remove.Add(i); } else { RemoveOCGsFromArray(annot.GetAsDict(PdfName.A), PdfName.STATE, ocgs); } } foreach (int i in remove) { annots.Remove(i); } }