/// <summary> /// Keeps track of the MarkedContent state. </summary> /// <param name="ocref"> a reference to an OCG dictionary </param> protected internal virtual void CheckMarkedContentStart(PdfName ocref) { if (mc_balance > 0) { mc_balance++; return; } if (properties == null) { return; } PdfDictionary ocdict = properties.GetAsDict(ocref); if (ocdict == null) { return; } PdfString ocname = ocdict.GetAsString(PdfName.NAME); if (ocname == null) { return; } if (ocgs.Contains(ocname.ToString())) { mc_balance++; } }
private void AddChildToExistingParent(PdfDictionary fieldDic, ICollection <String> existingFields) { 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); kids.Add(fieldDic); } else { parent.Put(PdfName.Kids, new PdfArray(fieldDic)); AddChildToExistingParent(parent, existingFields); } } }
public SignaturePermissions InspectSignature(AcroFields fields, String name, SignaturePermissions perms) { IList <AcroFields.FieldPosition> fps = fields.GetFieldPositions(name); if (fps != null && fps.Count > 0) { AcroFields.FieldPosition fp = fps[0]; Rectangle pos = fp.position; if (pos.Width == 0 || pos.Height == 0) { Console.WriteLine("Invisible signature"); } else { Console.WriteLine("Field on page {0}; llx: {1}, lly: {2}, urx: {3}; ury: {4}", fp.page, pos.Left, pos.Bottom, pos.Right, pos.Top); } } PdfPKCS7 pkcs7 = VerifySignature(fields, name); Console.WriteLine("Digest algorithm: " + pkcs7.GetHashAlgorithm()); Console.WriteLine("Encryption algorithm: " + pkcs7.GetEncryptionAlgorithm()); Console.WriteLine("Filter subtype: " + pkcs7.GetFilterSubtype()); X509Certificate cert = pkcs7.SigningCertificate; Console.WriteLine("Name of the signer: " + CertificateInfo.GetSubjectFields(cert).GetField("CN")); if (pkcs7.SignName != null) { Console.WriteLine("Alternative name of the signer: " + pkcs7.SignName); } Console.WriteLine("Signed on: " + pkcs7.SignDate.ToString("yyyy-MM-dd HH:mm:ss.ff")); if (!pkcs7.TimeStampDate.Equals(DateTime.MaxValue)) { Console.WriteLine("TimeStamp: " + pkcs7.TimeStampDate.ToString("yyyy-MM-dd HH:mm:ss.ff")); TimeStampToken ts = pkcs7.TimeStampToken; Console.WriteLine("TimeStamp service: " + ts.TimeStampInfo.Tsa); Console.WriteLine("Timestamp verified? " + pkcs7.VerifyTimestampImprint()); } Console.WriteLine("Location: " + pkcs7.Location); Console.WriteLine("Reason: " + pkcs7.Reason); PdfDictionary sigDict = fields.GetSignatureDictionary(name); PdfString contact = sigDict.GetAsString(PdfName.CONTACTINFO); if (contact != null) { Console.WriteLine("Contact info: " + contact); } perms = new SignaturePermissions(sigDict, perms); Console.WriteLine("Signature type: " + (perms.Certification ? "certification" : "approval")); Console.WriteLine("Filling out fields allowed: " + perms.FillInAllowed); Console.WriteLine("Adding annotations allowed: " + perms.AnnotationsAllowed); foreach (SignaturePermissions.FieldLock Lock in perms.FieldLocks) { Console.WriteLine("Lock: " + Lock); } return(perms); }
public virtual void CheckSingleParamConstructorTest() { String somePath = "C:\\some\\path\\some-app.exe"; PdfWin win = new PdfWin(new PdfString(somePath)); PdfDictionary pdfWinObj = win.GetPdfObject(); NUnit.Framework.Assert.AreEqual(1, pdfWinObj.Size()); NUnit.Framework.Assert.AreEqual(somePath, pdfWinObj.GetAsString(PdfName.F).ToString()); }
// --------------------------------------------------------------------------- public void AddKids(PdfArray dests, PdfDictionary outline) { while (outline != null) { dests.Add(outline.GetAsString(PdfName.TITLE)); dests.Add(outline.GetAsArray(PdfName.DEST)); AddKids(dests, outline.GetAsDict(PdfName.FIRST)); outline = outline.GetAsDict(PdfName.NEXT); } }
private String GetPropertyAsString(PdfName name) { PdfString text = properties.GetAsString(name); String result = null; if (text != null) { result = text.ToUnicodeString(); } return(result); }
public static List <string> GetPdfLinks(string file, int page) { //Open our reader PdfReader R = new PdfReader(file); //Get the current page PdfDictionary PageDictionary = R.GetPageN(page); //Get all of the annotations for the current page PdfArray Annots = PageDictionary.GetAsArray(PdfName.ANNOTS); //Make sure we have something if ((Annots == null) || (Annots.Length == 0)) { return(null); } List <string> Ret = new List <string>(); //Loop through each annotation foreach (PdfObject A in Annots.ArrayList) { //Convert the itext-specific object as a generic PDF object PdfDictionary AnnotationDictionary = (PdfDictionary)PdfReader.GetPdfObject(A); //Make sure this annotation has a link if (!AnnotationDictionary.Get(PdfName.SUBTYPE).Equals(PdfName.LINK)) { continue; } //Make sure this annotation has an ACTION if (AnnotationDictionary.Get(PdfName.A) == null) { continue; } //Get the ACTION for the current annotation PdfDictionary AnnotationAction = (PdfDictionary)AnnotationDictionary.Get(PdfName.A); //Test if it is a URI action (There are tons of other types of actions, some of which might mimic URI, such as JavaScript, but those need to be handled seperately) if (AnnotationAction.Get(PdfName.S).Equals(PdfName.URI)) { PdfString Destination = AnnotationAction.GetAsString(PdfName.URI); if (Destination != null) { Ret.Add(Destination.ToString()); } } } return(Ret); }
public virtual String GetActualText() { PdfString actualText = properties.GetAsString(PdfName.ActualText); String result = null; if (actualText != null) { result = actualText.ToUnicodeString(); } return(result); }
public virtual void PutTest() { PdfName key1 = new PdfName("Key1"); PdfName key2 = new PdfName("Key2"); PdfDictionary dictionary = new PdfDictionary(); PdfTarget target = PdfTarget.Create(dictionary); target.Put(key1, new PdfNumber(23)).Put(key2, new PdfString("Hello, world!")); NUnit.Framework.Assert.AreEqual(23, dictionary.GetAsNumber(key1).IntValue()); NUnit.Framework.Assert.AreEqual("Hello, world!", dictionary.GetAsString(key2).GetValue()); }
public static string LinkGrabber(string filePath, string fileName, StreamWriter writer) //Writes found links to CSV and outputs count { string error = "\n"; int foundLinks = 0; //Number of links found 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 { continue; } try { 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(); try { if (foundURL.Substring(0, 4).Equals("http")) //If it's an actual link { writer.WriteLine("\"" + foundURL + "\",\"" + fileName + "\""); //Adds the link to the CSV file foundLinks++; } } catch { } //Intentionally left blank } } } } catch { error += " WARNING: Problem reading page " + page + "\n"; } } return(" - " + foundLinks + " link(s) found" + error); }
/// <summary> /// Checks if an OCG dictionary is on the list for removal. </summary> /// <param name="ocg"> a dictionary </param> /// <param name="names"> the removal list /// @return true if the dictionary should be removed </param> private bool IsToBeRemoved(PdfDictionary ocg, ICollection <string> names) { if (ocg == null) { return(false); } PdfString n = ocg.GetAsString(PdfName.NAME); if (n == null) { return(false); } return(names.Contains(n.ToString())); }
public static string ExtractEdiconData(string srcEdiconPdfFileName) { PdfReader reader = null; // try { reader = new PdfReader(srcEdiconPdfFileName); // PdfDictionary root = reader.Catalog; PdfDictionary documentnames = root.GetAsDict(PdfName.NAMES); PdfDictionary embeddedfiles = documentnames.GetAsDict(PdfName.EMBEDDEDFILES); PdfArray filespecs = embeddedfiles.GetAsArray(PdfName.NAMES); // for (int i = 0; i < filespecs.Size;) { filespecs.GetAsString(i++); PdfDictionary filespec = filespecs.GetAsDict(i++); PdfDictionary refs = filespec.GetAsDict(PdfName.EF); // foreach (PdfName key in refs.Keys) { PRStream stream = (PRStream)PdfReader.GetPdfObject(refs.GetAsIndirectObject(key)); // var outName = filespec.GetAsString(key).ToString(); // if (outName.Equals(EDICON_EMBED_FILENAME, StringComparison.OrdinalIgnoreCase)) { byte[] outByteArray = PdfReader.GetStreamBytes(stream); string ediconData = Encoding.UTF8.GetString(outByteArray); return(ediconData); } } } } catch (Exception ex) { //Console.WriteLine("ExtractEdiconData error: " + ex.Message); throw new EdiconException("Soubor neobsahuje platnou přílohu Edicon"); } finally { if (reader != null) { reader.Close(); } } return(null); }
static PdfName getSignatureHashKey(PdfDictionary dic, bool encrypted) { PdfString contents = dic.GetAsString(PdfName.CONTENTS); byte[] bc = contents.GetOriginalBytes(); if (PdfName.ETSI_RFC3161.Equals(PdfReader.GetPdfObject(dic.Get(PdfName.SUBFILTER)))) { using (Asn1InputStream din = new Asn1InputStream(bc)) { Asn1Object pkcs = din.ReadObject(); bc = pkcs.GetEncoded(); } } byte[] bt = hashBytesSha1(bc); return(new PdfName(Utilities.ConvertToHex(bt))); }
private PdfName GetSignatureHashKey(String signatureName) { PdfDictionary dic = acroFields.GetSignatureDictionary(signatureName); PdfString contents = dic.GetAsString(PdfName.CONTENTS); byte[] bc = contents.GetOriginalBytes(); byte[] bt = null; if (PdfName.ETSI_RFC3161.Equals(dic.GetAsName(PdfName.SUBFILTER))) { Asn1InputStream din = new Asn1InputStream(new MemoryStream(bc)); Asn1Object pkcs = din.ReadObject(); bc = pkcs.GetEncoded(); } bt = HashBytesSha1(bc); return(new PdfName(Utilities.ConvertToHex(bt))); }
/// <exception cref="Org.BouncyCastle.Security.SecurityUtilityException"/> /// <exception cref="System.IO.IOException"/> private PdfName GetSignatureHashKey(String signatureName) { PdfDictionary dic = sgnUtil.GetSignatureDictionary(signatureName); PdfString contents = dic.GetAsString(PdfName.Contents); byte[] bc = PdfEncodings.ConvertToBytes(contents.GetValue(), null); byte[] bt = null; if (PdfName.ETSI_RFC3161.Equals(dic.GetAsName(PdfName.SubFilter))) { Asn1InputStream din = new Asn1InputStream(new MemoryStream(bc)); Asn1Object pkcs = din.ReadObject(); bc = pkcs.GetEncoded(); } bt = HashBytesSha1(bc); return(new PdfName(ConvertToHex(bt))); }
public static (SignaturePermissions, FileDetailsModel) InspectSignature(FileDetailsModel model, PdfDocument pdfDoc, SignatureUtil signUtil, PdfAcroForm form, String name, SignaturePermissions perms) { IList <PdfWidgetAnnotation> widgets = form.GetField(name).GetWidgets(); PdfPKCS7 pkcs7 = null; (pkcs7, model) = VerifySignature(model, signUtil, name); logger.Error("Digest algorithm: " + pkcs7.GetHashAlgorithm()); logger.Error("Encryption algorithm: " + pkcs7.GetEncryptionAlgorithm()); logger.Error("Filter subtype: " + pkcs7.GetFilterSubtype()); X509Certificate cert = (X509Certificate)pkcs7.GetSigningCertificate(); logger.Error("Name of the signer: " + iText.Signatures.CertificateInfo.GetSubjectFields(cert).GetField("CN")); model.SignerName = iText.Signatures.CertificateInfo.GetSubjectFields(cert).GetField("CN"); if (pkcs7.GetSignName() != null) { logger.Error("Alternative name of the signer: " + pkcs7.GetSignName()); } logger.Error("Signed on: " + pkcs7.GetSignDate().ToUniversalTime().ToString("yyyy-MM-dd")); model.SignatureDate = pkcs7.GetSignDate().ToUniversalTime().ToString("yyyy-MM-dd"); logger.Error("Location: " + pkcs7.GetLocation()); logger.Error("Reason: " + pkcs7.GetReason()); PdfDictionary sigDict = signUtil.GetSignatureDictionary(name); PdfString contact = sigDict.GetAsString(PdfName.ContactInfo); if (contact != null) { logger.Error("Contact info: " + contact); } return(perms, model); }
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)); 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(); }
/// <summary> /// Parses a stream object and removes OCGs. </summary> /// <param name="stream"> a stream object </param> /// <param name="resources"> the resources dictionary of that object (containing info about the OCGs) </param> public virtual void Parse(PRStream stream, PdfDictionary resources) { baos = new MemoryStream(); properties = resources.GetAsDict(PdfName.PROPERTIES); xobj = new HashSet2 <PdfName>(); PdfDictionary xobjects = resources.GetAsDict(PdfName.XOBJECT); if (xobjects != null) { // remove XObject (form or image) that belong to an OCG that needs to be removed foreach (PdfName name in xobjects.Keys) { PRStream xobject = (PRStream)xobjects.GetAsStream(name); PdfDictionary oc = xobject.GetAsDict(PdfName.OC); if (oc != null) { PdfString ocname = oc.GetAsString(PdfName.NAME); if (ocname != null && ocgs.Contains(ocname.ToString())) { xobj.Add(name); } } } foreach (PdfName name in xobj) { xobjects.Remove(name); } } // parse the content stream byte[] contentBytes = PdfReader.GetStreamBytes(stream); PRTokeniser tokeniser = new PRTokeniser(new RandomAccessFileOrArray(contentBytes)); PdfContentParser ps = new PdfContentParser(tokeniser); List <PdfObject> operands = new List <PdfObject>(); while (ps.Parse(operands).Count > 0) { PdfLiteral @operator = (PdfLiteral)operands[operands.Count - 1]; ProcessOperator(this, @operator, operands); } baos.Flush(); baos.Close(); stream.SetData(baos.GetBuffer()); }
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); } } } } }
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()); }
protected internal override void CheckFileSpec(PdfDictionary fileSpec) { PdfName relationship = fileSpec.GetAsName(PdfName.AFRelationship); if (relationship == null || !allowedAFRelationships.Contains(relationship)) { throw new PdfAConformanceException(PdfAConformanceException.FileSpecificationDictionaryShallContainOneOfThePredefinedAFRelationshipKeys ); } if (fileSpec.ContainsKey(PdfName.EF)) { if (!fileSpec.ContainsKey(PdfName.F) || !fileSpec.ContainsKey(PdfName.UF) || !fileSpec.ContainsKey(PdfName .Desc)) { throw new PdfAConformanceException(PdfAConformanceException.FileSpecificationDictionaryShallContainFKeyUFKeyAndDescKey ); } PdfDictionary ef = fileSpec.GetAsDictionary(PdfName.EF); PdfStream embeddedFile = ef.GetAsStream(PdfName.F); if (embeddedFile == null) { throw new PdfAConformanceException(PdfAConformanceException.EFKeyOfFileSpecificationDictionaryShallContainDictionaryWithValidFKey ); } if (!embeddedFile.ContainsKey(PdfName.Subtype)) { throw new PdfAConformanceException(PdfAConformanceException.MimeTypeShallBeSpecifiedUsingTheSubtypeKeyOfTheFileSpecificationStreamDictionary ); } PdfDictionary @params = embeddedFile.GetAsDictionary(PdfName.Params); if (@params == null) { throw new PdfAConformanceException(PdfAConformanceException.EmbeddedFileShallContainParamsKeyWithDictionaryAsValue ); } if (@params.GetAsString(PdfName.ModDate) == null) { throw new PdfAConformanceException(PdfAConformanceException.EmbeddedFileShallContainParamsKeyWithValidModdateKey ); } } }
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); } } }
public string Pdf_get_metadata(string path) { PdfDocument pdfDoc = new PdfDocument(new PdfReader(path)); Document doc = new Document(pdfDoc); PdfFont pdfFont; pdfFont = null; PdfDictionary infoDictionary = pdfDoc.GetTrailer().GetAsDictionary(PdfName.Info); string metadatastring = $"Metadata: {Environment.NewLine}"; foreach (PdfName key in infoDictionary.KeySet()) { string keytext = infoDictionary.GetAsString(key).ToUnicodeString(); if (key == PdfName.CreationDate | key == PdfName.ModDate) { DateTime date = PdfDate.Decode(keytext); keytext = date.ToString("dd/MM/yyyy HH:mm:ss"); } string cleankey = ($"{ key }").Replace("/", ""); metadatastring += $"{cleankey}: {keytext}{Environment.NewLine}{Environment.NewLine}"; } metadatastring += $"-----------------{Environment.NewLine}"; HashSet <string> fontinfo = Find_fonts(path); if (fontinfo != null && fontinfo.Count > 0) { metadatastring += $"OCR present because pdf has {fontinfo.Count} fonts.{Environment.NewLine}-----------------{Environment.NewLine}"; } else { metadatastring += $"OCR NOT present because pdf has no fonts.{Environment.NewLine}-----------------{Environment.NewLine}"; } metadatastring += $"Pages: {pdfDoc.GetNumberOfPages().ToString()}" + Environment.NewLine; return(metadatastring); }
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 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()); } }
private void InitKeyAndReadDictionary(PdfDictionary encryptionDictionary, byte[] password) { try { if (password == null) { password = new byte[0]; } else { if (password.Length > 127) { password = JavaUtil.ArraysCopyOf(password, 127); } } isPdf2 = encryptionDictionary.GetAsNumber(PdfName.R).GetValue() == 6; byte[] oValue = GetIsoBytes(encryptionDictionary.GetAsString(PdfName.O)); byte[] uValue = GetIsoBytes(encryptionDictionary.GetAsString(PdfName.U)); byte[] oeValue = GetIsoBytes(encryptionDictionary.GetAsString(PdfName.OE)); byte[] ueValue = GetIsoBytes(encryptionDictionary.GetAsString(PdfName.UE)); byte[] perms = GetIsoBytes(encryptionDictionary.GetAsString(PdfName.Perms)); PdfNumber pValue = (PdfNumber)encryptionDictionary.Get(PdfName.P); this.permissions = pValue.LongValue(); byte[] hash; hash = ComputeHash(password, oValue, VALIDATION_SALT_OFFSET, SALT_LENGTH, uValue); usedOwnerPassword = CompareArray(hash, oValue, 32); if (usedOwnerPassword) { hash = ComputeHash(password, oValue, KEY_SALT_OFFSET, SALT_LENGTH, uValue); AESCipherCBCnoPad ac = new AESCipherCBCnoPad(false, hash); nextObjectKey = ac.ProcessBlock(oeValue, 0, oeValue.Length); } else { hash = ComputeHash(password, uValue, VALIDATION_SALT_OFFSET, SALT_LENGTH); if (!CompareArray(hash, uValue, 32)) { throw new BadPasswordException(PdfException.BadUserPassword); } hash = ComputeHash(password, uValue, KEY_SALT_OFFSET, SALT_LENGTH); AESCipherCBCnoPad ac = new AESCipherCBCnoPad(false, hash); nextObjectKey = ac.ProcessBlock(ueValue, 0, ueValue.Length); } nextObjectKeySize = 32; AESCipherCBCnoPad ac_1 = new AESCipherCBCnoPad(false, nextObjectKey); byte[] decPerms = ac_1.ProcessBlock(perms, 0, perms.Length); if (decPerms[9] != (byte)'a' || decPerms[10] != (byte)'d' || decPerms[11] != (byte)'b') { throw new BadPasswordException(PdfException.BadUserPassword); } int permissionsDecoded = (decPerms[0] & 0xff) | ((decPerms[1] & 0xff) << 8) | ((decPerms[2] & 0xff) << 16) | ((decPerms[3] & 0xff) << 24); bool encryptMetadata = decPerms[8] == (byte)'T'; bool?encryptMetadataEntry = encryptionDictionary.GetAsBool(PdfName.EncryptMetadata); if (permissionsDecoded != permissions || encryptMetadataEntry != null && encryptMetadata != encryptMetadataEntry ) { ILog logger = LogManager.GetLogger(typeof(iText.Kernel.Crypto.Securityhandler.StandardHandlerUsingAes256)); logger.Error(iText.IO.LogMessageConstant.ENCRYPTION_ENTRIES_P_AND_ENCRYPT_METADATA_NOT_CORRESPOND_PERMS_ENTRY ); } this.permissions = permissionsDecoded; this.encryptMetadata = encryptMetadata; } catch (BadPasswordException ex) { throw; } catch (Exception ex) { throw new PdfException(PdfException.PdfEncryption, ex); } }
/** * Converts an annotation structure item to a Form XObject annotation. * @param item the structure item * @throws IOException */ 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; } }
public SignaturePermissions InspectSignature(PdfDocument pdfDoc, SignatureUtil signUtil, PdfAcroForm form, String name, SignaturePermissions perms) { IList <PdfWidgetAnnotation> widgets = form.GetField(name).GetWidgets(); // Check the visibility of the signature annotation if (widgets != null && widgets.Count > 0) { Rectangle pos = widgets[0].GetRectangle().ToRectangle(); int pageNum = pdfDoc.GetPageNumber(widgets[0].GetPage()); if (pos.GetWidth() == 0 || pos.GetHeight() == 0) { Console.Out.WriteLine("Invisible signature"); } else { Console.Out.WriteLine(String.Format("Field on page {0}; llx: {1}, lly: {2}, urx: {3}; ury: {4}", pageNum, pos.GetLeft(), pos.GetBottom(), pos.GetRight(), pos.GetTop())); } } /* Find out how the message digest of the PDF bytes was created, * how these bytes and additional attributes were signed * and how the signed bytes are stored in the PDF */ PdfPKCS7 pkcs7 = VerifySignature(signUtil, name); Console.Out.WriteLine("Digest algorithm: " + pkcs7.GetHashAlgorithm()); Console.Out.WriteLine("Encryption algorithm: " + pkcs7.GetEncryptionAlgorithm()); Console.Out.WriteLine("Filter subtype: " + pkcs7.GetFilterSubtype()); // Get the signing certificate to find out the name of the signer. X509Certificate cert = (X509Certificate)pkcs7.GetSigningCertificate(); Console.Out.WriteLine("Name of the signer: " + iText.Signatures.CertificateInfo.GetSubjectFields(cert).GetField("CN")); if (pkcs7.GetSignName() != null) { Console.Out.WriteLine("Alternative name of the signer: " + pkcs7.GetSignName()); } /* Get the signing time. * Mind that the getSignDate() method is not that secure as timestamp * because it's based only on signature author claim. I.e. this value can only be trusted * if signature is trusted and it cannot be used for signature verification. */ Console.Out.WriteLine("Signed on: " + pkcs7.GetSignDate().ToUniversalTime().ToString("yyyy-MM-dd")); /* If a timestamp was applied, retrieve information about it. * Timestamp is a secure source of signature creation time, * because it's based on Time Stamping Authority service. */ if (TimestampConstants.UNDEFINED_TIMESTAMP_DATE != pkcs7.GetTimeStampDate()) { Console.Out.WriteLine("TimeStamp: " + pkcs7.GetTimeStampDate().ToUniversalTime().ToString("yyyy-MM-dd")); TimeStampToken ts = pkcs7.GetTimeStampToken(); Console.Out.WriteLine("TimeStamp service: " + ts.TimeStampInfo.Tsa); Console.Out.WriteLine("Timestamp verified? " + pkcs7.VerifyTimestampImprint()); } Console.Out.WriteLine("Location: " + pkcs7.GetLocation()); Console.Out.WriteLine("Reason: " + pkcs7.GetReason()); /* If you want less common entries than PdfPKCS7 object has, such as the contact info, * you should use the signature dictionary and get the properties by name. */ PdfDictionary sigDict = signUtil.GetSignatureDictionary(name); PdfString contact = sigDict.GetAsString(PdfName.ContactInfo); if (contact != null) { Console.Out.WriteLine("Contact info: " + contact); } /* Every new signature can add more restrictions to a document, but it can’t take away previous restrictions. * So if you want to retrieve information about signatures restrictions, you need to pass * the SignaturePermissions instance of the previous signature, or null if there was none. */ perms = new SignaturePermissions(sigDict, perms); Console.Out.WriteLine("Signature type: " + (perms.IsCertification() ? "certification" : "approval")); Console.Out.WriteLine("Filling out fields allowed: " + perms.IsFillInAllowed()); Console.Out.WriteLine("Adding annotations allowed: " + perms.IsAnnotationsAllowed()); foreach (SignaturePermissions.FieldLock Lock in perms.GetFieldLocks()) { Console.Out.WriteLine("Lock: " + Lock); } return(perms); }
public ActionResult Index() { #region [Search Annotations] List <AnnotC> Annot = new List <AnnotC>(); PdfReader vAnnotedReader = new PdfReader(Server.MapPath("~/Data/Extender.pdf")); for (int i = 1; i <= vAnnotedReader.NumberOfPages; i++) { PdfArray array = vAnnotedReader.GetPageN(i).GetAsArray(PdfName.ANNOTS); if (array == null) { continue; } //AnnotC c = new AnnotC(); //c.Page = i; //c.Annot = vAnnotedReader.GetPageN(i); //Annot.Add(c); for (int j = 0; j < array.Size; j++) { PdfDictionary annot = array.GetAsDict(j); PdfString text = annot.GetAsString(PdfName.CONTENTS); if (text != null) { AnnotC c = new AnnotC(); c.Page = i; c.Annot = annot; Annot.Add(c); } } } PdfReader vAnnotedReader2 = new PdfReader(Server.MapPath("~/Data/Ori.pdf")); for (int i = 1; i <= vAnnotedReader2.NumberOfPages; i++) { PdfArray array = vAnnotedReader2.GetPageN(i).GetAsArray(PdfName.ANNOTS); if (array == null) { continue; } for (int j = 0; j < array.Size; j++) { PdfDictionary annot = array.GetAsDict(j); PdfString text = annot.GetAsString(PdfName.CONTENTS); if (text != null) { AnnotC c = new AnnotC(); c.Page = i; c.Annot = annot; Annot.Add(c); } //PdfAnnotation test = annot; } } //var json = new JavaScriptSerializer().Serialize(Annot); PdfReader vOriginalReader = new PdfReader(Server.MapPath("~/Data/Ori.pdf")); var pDestinationFileName = Server.MapPath("~/Data/Merge.pdf"); for (int vPageNumber = 1; vPageNumber <= vOriginalReader.NumberOfPages; vPageNumber++) { PdfDictionary vOriginalPage = vOriginalReader.GetPageN(vPageNumber); foreach (var x in Annot) { if (x.Page == vPageNumber) { //PdfAnnotation annotation = PdfAnnotation.CreateText(vStamper.Writer, x.Annot.GetAsName(PdfRectangle.ARRAY), "Note", "This document is written by Dara Yuk", false, "Note"); PdfString contents = x.Annot.GetAsString(PdfName.CONTENTS); String value = contents.ToString(); Rectangle rect = Rectangle() //vOriginalReader.GetPageN(vPageNumber).MergeDifferent(x.Annot); //PdfAnnotation test = x.Annot.GetAsString(PdfName.ann) vOriginalReader.GetPageN(vPageNumber).Put(PdfName.ANNOT, x.Annot); //vOriginalReader.GetPageN(vPageNumber).Merge(x.Annot); } } //vStamper.MarkUsed(vOriginalPage); } PdfStamper vStamper = new PdfStamper(vOriginalReader, new FileStream(pDestinationFileName, FileMode.Create)); vStamper.Close(); vAnnotedReader.Close(); vOriginalReader.Close(); #endregion #region [Merging] /*//set the output file * using (Stream outputPdfStream = new FileStream("C:\\Users\\Athe\\source\\repos\\Reader\\Reader\\Data\\Merge.pdf", FileMode.Create, FileAccess.Write, FileShare.None)) * { * //select the PDF files you want to merge, in this example I only merged 2 files, but you can do more. * string[] pdfArrayFiles = { "C:\\Users\\Athe\\source\\repos\\Reader\\Reader\\Data\\Extender.pdf", "C:\\Users\\Athe\\source\\repos\\Reader\\Reader\\Data\\Ori.pdf" }; * * //create a new document * Document document = new Document(); * //use PdfSmartCopy to merge PDF files to output file (or stream) * PdfSmartCopy copy = new PdfSmartCopy(document, outputPdfStream); * //open the document * document.Open(); * //set the reader to read files and add pages * PdfReader reader; * int n; * for (int i = 0; i < pdfArrayFiles.Length; i++) * { * reader = new PdfReader(pdfArrayFiles[i]); * n = reader.NumberOfPages; * for (int page = 0; page < n;) * { * copy.AddPage(copy.GetImportedPage(reader, ++page)); * } * } * document.Close(); * }*/ #endregion #region [3] //Stream sourcePdfStream = new FileStream("C:\\Users\\Athe\\source\\repos\\Reader\\Reader\\Data\\Extender.pdf", FileMode.Create, FileAccess.Write, FileShare.None); //Stream destinationPdfStream = new FileStream("C:\\Users\\Athe\\source\\repos\\Reader\\Reader\\Data\\Ori.pdf", FileMode.Create, FileAccess.Write, FileShare.None); //var output = new MemoryStream(); //using (var document = new Document(PageSize.A4, 70f, 70f, 20f, 20f)) //{ // var readers = new List<PdfReader>(); // var writer = PdfWriter.GetInstance(document, output); // writer.CloseStream = false; // document.Open(); // const Int32 requiredWidth = 500; // const Int32 zeroBottom = 647; // const Int32 left = 50; // Action<String, Action> inlcudePdfInDocument = (filename, e) => // { // var reader = new PdfReader(filename); // readers.Add(reader); // var pageCount = reader.NumberOfPages; // for (var i = 0; i < pageCount; i++) // { // e?.Invoke(); // var imp = writer.GetImportedPage(reader, (i + 1)); // var scale = requiredWidth / imp.Width; // var height = imp.Height * scale; // writer.DirectContent.AddTemplate(imp, scale, 0, 0, scale, left, zeroBottom - height); // var annots = reader.GetPageN(i + 1).GetAsArray(PdfName.ANNOTS); // if (annots != null && annots.Size != 0) // { // foreach (var a in annots) // { // var newannot = new PdfAnnotation(writer, new Rectangle(0, 0)); // var annotObj = (PdfDictionary)PdfReader.GetPdfObject(a); // newannot.PutAll(annotObj); // var rect = newannot.GetAsArray(PdfName.RECT); // rect[0] = new PdfNumber(((PdfNumber)rect[0]).DoubleValue * scale + left); // Left // rect[1] = new PdfNumber(((PdfNumber)rect[1]).DoubleValue * scale); // top // rect[2] = new PdfNumber(((PdfNumber)rect[2]).DoubleValue * scale + left); // right // rect[3] = new PdfNumber(((PdfNumber)rect[3]).DoubleValue * scale); // bottom // writer.AddAnnotation(newannot); // } // } // document.NewPage(); // } // }; // List<String> pdfs = new List<string>(); // pdfs.Add("C:\\Users\\Athe\\source\\repos\\Reader\\Reader\\Data\\Extender.pdf"); // pdfs.Add("C:\\Users\\Athe\\source\\repos\\Reader\\Reader\\Data\\Ori.pdf"); // foreach (var apprPdf in pdfs) // { // document.NewPage(); // inlcudePdfInDocument(apprPdf, null); // } // document.Close(); // readers.ForEach(x => x.Close()); //} //output.Position = 0; //FileStream F = new FileStream("C:\\Users\\Athe\\source\\repos\\Reader\\Reader\\Data\\Merge.pdf", FileMode.Create, FileAccess.Write, FileShare.None); //output.WriteTo(F); //F.Close(); //output.Close(); #endregion #region [Add Annot] //path to source file //String source = "C:\\Users\\Athe\\source\\repos\\Reader\\Reader\\Data\\Extender.pdf"; ////create PdfReader object to read the source file //PdfReader reader = new PdfReader(source); ////create PdfStamper object to modify the content of the PDF //PdfStamper stamp = new PdfStamper(reader, new FileStream("C:\\Users\\Athe\\source\\repos\\Reader\\Reader\\Data\\Extender - Copy.pdf", FileMode.Create)); ////create a Rectangle object to deine the size and location of the annotation //Rectangle rect = new Rectangle(10, 30, 50, 50); ////create a PdfAnnotation object //PdfAnnotation annotation = PdfAnnotation.CreateText(stamp.Writer, rect, "Note", "This document is written by Dara Yuk", false, "Note"); ////loop through the document and add the annotation to every page //for (int page = 1; page <= reader.NumberOfPages; page++) // stamp.AddAnnotation(annotation, page); //stamp.Close(); //System.Diagnostics.Process.Start("C:\\Users\\Athe\\source\\repos\\Reader\\Reader\\Data\\Extender - Copy.pdf"); //Console.Read(); #endregion #region [Tes Copy Annot] //Stream sourcePdfStream = new FileStream("C:\\Users\\Athe\\source\\repos\\Reader\\Reader\\Data\\Extender.pdf", FileMode.Create, FileAccess.Write, FileShare.None); //Stream destinationPdfStream = new FileStream("C:\\Users\\Athe\\source\\repos\\Reader\\Reader\\Data\\Ori.pdf", FileMode.Create, FileAccess.Write, FileShare.None); //// Create new document (IText) //Document outdoc = new Document(PageSize.A4); //// Seek to Stream start and create Reader for input PDF //m.Seek(0, SeekOrigin.Begin); //PdfReader inputPdfReader = new PdfReader(sourcePdfStream); //// Seek to Stream start and create Reader for destination PDF //m.Seek(0, SeekOrigin.Begin); //PdfReader destinationPdfReader = new PdfReader(destinationPdfStream); //// Create a PdfWriter from for new a pdf destination stream //// You should write into a new stream here! //Stream processedPdf = new MemoryStream(); //PdfWriter pdfw = PdfWriter.GetInstance(outdoc, processedPdf); //// do not close stream if we've read everything //pdfw.CloseStream = false; //// Open document //outdoc.Open(); //// get number of pages //int numPagesIn = inputPdfReader.NumberOfPages; //int numPagesOut = destinationPdfReader.NumberOfPages; //int max = numPagesIn; //// Process max number of pages //if (max < numPagesOut) //{ // throw new Exception("Impossible - different number of pages"); //} //int i = 0; //// Process Pdf pages //while (i < max) //{ // // Import pages from corresponding reader // PdfImportedPage pageIn = writer.inputPdfReader(reader, i); // PdfImportedPage pageOut = writer.destinationPdfReader(reader, i); // // Get named destinations (annotations // List<Annotat ions> toBeAdded = ParseInAndOutAndGetAnnotations(pageIn, pageOut); // // add your annotations // foreach (Annotation anno in toBeAdded) pageOut.Add(anno); // // Add processed page to output PDFWriter // outdoc.Add(pageOut); //} //// PDF creation finished //outdoc.Close(); #endregion #region [Test Copy Annot 2] //string oldFile = Server.MapPath("~/Data2/Extender.pdf"); //string oldFile2 = Server.MapPath("~/Data2/Ori.pdf"); //string newFile = Server.MapPath("~/Data2/Merge.pdf"); //// open the reader //PdfReader reader = new PdfReader(oldFile); //Rectangle size = reader.GetPageSizeWithRotation(1); //Document document = new Document(size); //PdfReader reader2 = new PdfReader(oldFile2); //Rectangle size2 = reader2.GetPageSizeWithRotation(1); //Document document2 = new Document(size2); //// open the writer //// remember to set the page size before opening document //// otherwise the page is already set. ///* chapter02/HelloWorldMetadata.java */ //document.Open(); //// the pdf content //// cb does not work with stamper //// create the new pagez and add it to the pdf //// this segment of code is meant for writer //FileStream fs = new FileStream(newFile, FileMode.Create, FileAccess.ReadWrite); //PdfStamper writer = new PdfStamper(reader, fs, reader.PdfVersion, false); //for (int pg = 1; pg <= reader.NumberOfPages; pg++) //{ // // taken from http://itextsharp.10939.n7.nabble.com/How-to-edit-annotations-td3352.html // PdfDictionary pagedic = reader.GetPageN(pg); // PdfArray annotarray = (PdfArray)PdfReader.GetPdfObject(pagedic.Get(PdfName.ANNOTS)); // if (annotarray == null || annotarray.Size == 0) // continue; // foreach (PdfIndirectReference annot in annotarray.ArrayList) // { // PdfDictionary annotationDic = (PdfDictionary)PdfReader.GetPdfObject(annot); // PdfName subType = (PdfName)annotationDic.Get(PdfName.SUBTYPE); // if (subType.Equals(PdfName.TEXT) || subType.Equals(PdfName.FREETEXT)) // { // annotationDic.Put(PdfName.CONTENTS, new PdfString("These are changed contents", PdfObject.TEXT_UNICODE)); // } // PdfString contents = annotationDic.GetAsString(PdfName.CONTENTS); // if (contents != null) // { // String value = contents.ToString(); // annotationDic.Put(PdfName.CONTENTS, new PdfString(value)); // annotationDic.Remove(PdfName.AP); // List<PdfName> tobeDel = new List<PdfName>(); // foreach (PdfName key in annotationDic.Keys) // { // if (key.CompareTo(PdfName.AP) == 0 || // key.CompareTo(PdfName.RC) == 0 || // annotationDic.Get(key).IsDictionary()) // { // tobeDel.Add(key); // } // } // foreach (PdfName key in tobeDel) // { // annotationDic.Remove(key); // } // } // writer.MarkUsed(annotationDic); // } // if ((pg + 1) < reader.NumberOfPages) // { // document.NewPage(); // } //} ////tesstart //PdfStamper writer2 = new PdfStamper(reader2, fs, reader2.PdfVersion, false); //document2.Open(); //for (int pg = 1; pg <= reader2.NumberOfPages; pg++) //{ // PdfDictionary pagedic = reader2.GetPageN(pg); // PdfArray annotarray = (PdfArray)PdfReader.GetPdfObject(pagedic.Get(PdfName.ANNOTS)); // if (annotarray == null || annotarray.Size == 0) // continue; // foreach (PdfIndirectReference annot in annotarray.ArrayList) // { // PdfDictionary annotationDic = (PdfDictionary)PdfReader.GetPdfObject(annot); // PdfName subType = (PdfName)annotationDic.Get(PdfName.SUBTYPE); // if (subType.Equals(PdfName.TEXT) || subType.Equals(PdfName.FREETEXT)) // { // annotationDic.Put(PdfName.CONTENTS, new PdfString("These are changed contents", PdfObject.TEXT_UNICODE)); // } // PdfString contents = annotationDic.GetAsString(PdfName.CONTENTS); // if (contents != null) // { // String value = contents.ToString(); // annotationDic.Put(PdfName.CONTENTS, new PdfString(value)); // annotationDic.Remove(PdfName.AP); // List<PdfName> tobeDel = new List<PdfName>(); // foreach (PdfName key in annotationDic.Keys) // { // if (key.CompareTo(PdfName.AP) == 0 || // key.CompareTo(PdfName.RC) == 0 || // annotationDic.Get(key).IsDictionary()) // { // tobeDel.Add(key); // } // } // foreach (PdfName key in tobeDel) // { // annotationDic.Remove(key); // } // } // writer2.MarkUsed(annotationDic); // } // if ((pg + 1) < reader2.NumberOfPages) // { // document2.NewPage(); // } //} ////tesend //// close the streams and voilá the file should be changed :) //writer.Close(); //reader.Close(); #endregion ViewBag.Title = "Home Page"; return(View()); }
/// <summary> /// Checks if an OCG dictionary is on the list for removal. </summary> /// <param name="ocg"> a dictionary </param> /// <param name="names"> the removal list /// @return true if the dictionary should be removed </param> private bool IsToBeRemoved(PdfDictionary ocg, ICollection<string> names) { if (ocg == null) { return false; } PdfString n = ocg.GetAsString(PdfName.NAME); if (n == null) { return false; } return names.Contains(n.ToString()); }