private TreeNode PrintObject(TreeNodeCollection tvDomNodes, PdfObject obj, string objectNumber) { var streamType = GetStreamType(obj); string isIndirect = "Indirect"; if (!obj.IsIndirect()) { isIndirect = "Direct"; } var node = tvDomNodes.Add($"{objectNumber} - {obj.GetType().Name} {streamType} {isIndirect}"); node.Tag = obj; if (streamType.Contains("Image")) { node.BackColor = Color.Olive; } if (obj.IsDictionary()) { var dict = obj as PdfDictionary; foreach (var dictKey in dict.Keys) { var dictObj = dict.GetDirectObject(dictKey); var newNode = PrintObject(node.Nodes, dictObj, dictObj.ToString()); } } return(node); }
/// <summary> /// Updates the pagination in the footer. /// </summary> /// <param name="inputPdf">The pdf to modify.</param> /// <param name="outputPdf">The pdf created with updated pagination.</param> public static void UpdateFooterPagination(string inputPdf, string outputPdf) { PdfReader reader = new PdfReader(inputPdf); FileStream fs = new FileStream(outputPdf, FileMode.Create, FileAccess.Write); int n = reader.NumberOfPages; for (int i = 1; i <= n; i++) { PdfDictionary dict = reader.GetPageN(i); PdfObject obj = dict.GetDirectObject(PdfName.CONTENTS); if (obj.GetType() == typeof(PRStream)) { PRStream stream = (PRStream)obj; byte[] data = PdfReader.GetStreamBytes(stream); String oldStr = System.Text.Encoding.UTF8.GetString(data); //Get the string matching the pagination String pageString = CommonUtils.MatchRegex(oldStr, @"\[\(Seite \)\]TJ.*\[\("); //Regex replacement of page string with updated page number String updatedPageString = Regex.Replace(pageString, @"\[\(\d+\)\]", "[(" + i + ")]"); String newString = Regex.Replace(oldStr, @"\[\(Seite \)\]TJ.*\[\(", updatedPageString, RegexOptions.Singleline); stream.SetData(System.Text.Encoding.UTF8.GetBytes(newString)); } } PdfStamper stamper = new PdfStamper(reader, fs); stamper.Close(); reader.Close(); }
public IndirectObject CreateInstance(PdfObjectId objectId, PdfObject referencedObject, bool isReadOnly) { var objectType = referencedObject.GetType(); var genCtor = ctorCache.GetOrAdd(objectType, GetConstructorForType); return((IndirectObject)genCtor.Invoke(new object[] { objectId, referencedObject, isReadOnly })); }
/// <summary> /// Tests if an object has a end delimiter. /// </summary> /// <param name="target">The <see cref="PdfObject"/> to test.</param> /// <returns>True if object has a end delimiter, otherwise false.</returns> public static bool HasEndDelimiter(this PdfObject target) { if (target == null) { throw new ArgumentNullException(nameof(target)); } return(target.GetType().GetTypeInfo().GetCustomAttribute <HasDelimitersAttribute>()?.AtEnd ?? false); }
/// <summary> /// Gets <see cref="HasDelimitersAttribute"/> of object. /// </summary> /// <param name="target">The target <see cref="PdfObject"/>.</param> /// <returns>The objects <see cref="HasDelimitersAttribute"/> or null.</returns> internal static HasDelimitersAttribute GetHasDelimiterAttibute(this PdfObject target) { if (target == null) { throw new ArgumentNullException(nameof(target)); } return(target.GetType().GetTypeInfo().GetCustomAttribute <HasDelimitersAttribute>()); }
void WriteObjectAddress(PdfObject value) { if (_layout == PdfWriterLayout.Verbose) { WriteRaw(String.Format("{0} {1} obj % {2}\n", value.ObjectID.ObjectNumber, value.ObjectID.GenerationNumber, value.GetType().FullName)); } else { WriteRaw(String.Format("{0} {1} obj\n", value.ObjectID.ObjectNumber, value.ObjectID.GenerationNumber)); } }
/// <summary> /// Replace texts. /// TODO: Los textos con formato creado en word introducen caracteres entre las palabras y no lo localiza. /// </summary> public void Replace() { using (FileStream stream = new FileStream(_pathSource, FileMode.Open)) { using (PdfReader pdfReader = new PdfReader(stream)) { for (int x = 1; x <= pdfReader.NumberOfPages; x++) { using (FileStream streamDest = new FileStream(_pathDest, FileMode.Create)) { PdfDictionary dict = pdfReader.GetPageN(x); PdfObject obj = dict.GetDirectObject(PdfName.CONTENTS); if (obj.GetType() == typeof(PRStream)) { ReplacePRStream(obj); } if (obj.GetType() == typeof(PdfArray)) { foreach (var r in (PdfArray)obj) { PRIndirectReference ir = (PRIndirectReference)r; PdfObject refdObj = pdfReader.GetPdfObject(ir.Number); if (refdObj.IsStream()) { ReplacePRStream(refdObj); } } } using (PdfStamper stamper = new PdfStamper(pdfReader, streamDest)) { } } } } } }
public static void Test_TraceObjects(string file) { Trace.WriteLine($"pdf \"{file}\""); using (PdfReader pdfReader = new PdfReader(file)) { int objectCount = pdfReader.XrefSize; for (int i = 0; i < objectCount; i++) { PdfObject obj = pdfReader.GetPdfObject(i); //if (obj != null) if (obj is PdfDictionary) { PdfDictionary objDic = (PdfDictionary)obj; string type = null; if (objDic.Contains(PdfName.TYPE)) { type = objDic.Get(PdfName.TYPE).ToString(); } string subtype = null; if (objDic.Contains(PdfName.SUBTYPE)) { subtype = objDic.Get(PdfName.SUBTYPE).ToString(); } Trace.WriteLine($"object {i + 1,3} object type {obj.GetType()} dictionary type {type} subtype {subtype}"); } else if (obj != null) { Trace.WriteLine($"object {i + 1,3} object type {obj.GetType()}"); } else { Trace.WriteLine($"object {i + 1,3} null"); } } } }
internal override void SetObject(PdfItem value) { PdfObject obj = (PdfObject)value; this.tbxObjectID.Text = PdfInternals.GetObjectID(obj).ToString(); this.txtType.Text = obj.GetType().Name; this.lvKeys.Items.Clear(); ListViewItem item = new ListViewItem( new string[3] { ExplorerProcess.GetTypeName(obj), value.ToString(), value.GetType().Name }); this.lvKeys.Items.Add(item); }
/** * Gets the content bytes from a content object, which may be a reference * a stream or an array. * @param contentObject the object to read bytes from * @return the content bytes * @throws IOException */ public static byte[] GetContentBytesFromContentObject(PdfObject contentObject) { byte[] result; switch (contentObject.Type) { case PdfObject.INDIRECT: PRIndirectReference refi = (PRIndirectReference)contentObject; PdfObject directObject = PdfReader.GetPdfObject(refi); result = GetContentBytesFromContentObject(directObject); break; case PdfObject.STREAM: PRStream stream = (PRStream)PdfReader.GetPdfObject(contentObject); result = PdfReader.GetStreamBytes(stream); break; case PdfObject.ARRAY: // Stitch together all content before calling ProcessContent(), because // ProcessContent() resets state. MemoryStream allBytes = new MemoryStream(); PdfArray contentArray = (PdfArray)contentObject; ListIterator <PdfObject> iter = contentArray.GetListIterator(); while (iter.HasNext()) { PdfObject element = iter.Next(); byte[] b; allBytes.Write(b = GetContentBytesFromContentObject(element), 0, b.Length); allBytes.WriteByte((byte)' '); } result = allBytes.ToArray(); break; default: String msg = "Unable to handle Content of type " + contentObject.GetType(); throw new InvalidOperationException(msg); } return(result); }
public static string GetTypeName(PdfObject obj) { if (obj is PdfDictionary) { return("dictionary"); } if (obj is PdfArray) { return("array"); } if (obj is PdfBooleanObject) { return("boolean"); } if (obj is PdfIntegerObject) { return("integer"); } if (obj is PdfRealObject) { return("real"); } if (obj is PdfStringObject) { return("string"); } if (obj is PdfNameObject) { return("name"); } if (obj is PdfNullObject) { return("null"); } throw new NotImplementedException("TODO: " + obj.GetType().FullName); }
public static MemoryStream RemoveText(MemoryStream streamInput, string watermarkText) { string content; PRStream stream; PdfArray contentarray; PdfReader reader = new PdfReader(streamInput.ToArray()); string DEST = "D:\\WebMes Projects\\NewYueWebMES\\YueWebMES.Service\\WebMES.API\\Attachments\\fa1.pdf"; //reader.RemoveUnusedObjects(); for (var i = 1; i <= reader.NumberOfPages; i++) { PdfDictionary dictionary = reader.GetPageN(i);//获取页 try { PdfObject pdfObj = dictionary.GetDirectObject(PdfName.CONTENTS); if (pdfObj.GetType() == typeof(PRStream)) { PRStream pst = (PRStream)pdfObj; byte[] data = PdfReader.GetStreamBytes(pst); content = System.Text.Encoding.ASCII.GetString(data);//获取pdf页内的文字内容 content = content.Replace(watermarkText, ""); pst.SetData(System.Text.Encoding.Default.GetBytes(content)); } } catch (Exception ex) { } //contentarray = page.GetAsArray(PdfName.CONTENTS); //if (contentarray != null) //{ // //Loop through content // for (int j = 0; j < contentarray.Size; j++) // { // //Get the raw byte stream // stream = (PRStream)contentarray.GetAsStream(j); // //Convert to a string. NOTE, you might need a different encoding here // content = System.Text.Encoding.ASCII.GetString(PdfReader.GetStreamBytes(stream));//获取pdf页内的文字内容 // //Look for the OCG token in the stream as well as our watermarked text // if (content.IndexOf("/OC") >= 0 || content.IndexOf(watermarkText) >= 0)//如果pdf内容包含水印文字 // { // //Remove it by giving it zero length and zero data // content = content.Replace(watermarkText, "");//替换水印文字为空 // byte[] byteArray = System.Text.Encoding.Default.GetBytes(content);//转换为byte[] // stream.Put(PdfName.LENGTH, new PdfNumber(byteArray.Length));//重新指定大小 // stream.SetData(byteArray);//重新赋值 // } // } //} } //PdfStamper stamper = new PdfStamper(reader, new FileStream(DEST, FileMode.Create, FileAccess.ReadWrite)); MemoryStream mstream = new MemoryStream(); PdfStamper stamper = new PdfStamper(reader, mstream); stamper.Close(); reader.Close(); return(mstream); }
private void CreateRawContent(List <byte> rawContent, PdfObject pdfObject) { Type pdfObjectType = pdfObject.GetType(); if (pdfObjectType == typeof(PdfName)) { rawContent.AddRange(pdfObject.GetBytes()); } else if (pdfObjectType == typeof(PdfLiteral)) { string t = pdfObject.ToString(); if (t == "EMC" || t == "BMC" || t == "BDC") { rawContent.Add(BYTE_SPACE); } rawContent.AddRange(pdfObject.GetBytes()); if (t == "BT") { rawContent.AddRange(BYTES_LINE_BREAK_WINDOWS); } if (t == "EMC" || t == "BMC" || t == "BDC") { rawContent.Add(BYTE_SPACE); } } else if (pdfObjectType == typeof(PdfNumber)) { rawContent.AddRange(pdfObject.GetBytes()); } else if (pdfObjectType == typeof(PdfString)) { rawContent.Add(BYTE_ROUND_OPENING_BRACKET); byte[] objectBuffer = pdfObject.GetBytes(); foreach (byte objectByte in objectBuffer) { switch (objectByte) { case BYTE_CARRIAGE_RETURN: { rawContent.AddRange(BYTES_REVERSE_SOLIDUS_AND_CHAR_r); break; } case BYTE_LINE_FEED: { rawContent.AddRange(BYTES_REVERSE_SOLIDUS_AND_CHAR_n); break; } case BYTE_HORIZONTAL_TAB: { rawContent.AddRange(BYTES_REVERSE_SOLIDUS_AND_CHAR_t); break; } case BYTE_BACKSPACE: { rawContent.AddRange(BYTES_REVERSE_SOLIDUS_AND_CHAR_b); break; } case BYTE_FORM_FEED: { rawContent.AddRange(BYTES_REVERSE_SOLIDUS_AND_CHAR_f); break; } case BYTE_ROUND_OPENING_BRACKET: case BYTE_ROUND_CLOSING_BRACKET: case BYTE_REVERSE_SOLIDUS: { rawContent.Add(BYTE_ESCAPE_CHAR); rawContent.Add(objectByte); break; } default: { rawContent.Add(objectByte); break; } } } rawContent.Add(BYTE_ROUND_CLOSING_BRACKET); } else if (pdfObjectType == typeof(PdfDictionary)) { rawContent.AddRange(BYTES_DOUBLE_ANGLE_OPENING_BRACKETS); PdfDictionary dict = pdfObject as PdfDictionary; foreach (PdfObject key in dict.Keys) { CreateRawContent(rawContent, key); PdfName keyName = key as PdfName; this.CreateRawContent(rawContent, dict.Get(keyName)); } rawContent.AddRange(BYTES_DOUBLE_ANGLE_CLOSING_BRACKETS); } else if (pdfObjectType == typeof(PdfArray)) { rawContent.Add(BYTE_SQUARE_OPENING_BRACKET); PdfArray pa = pdfObject as PdfArray; foreach (PdfObject obj in pa.ArrayList) { this.CreateRawContent(rawContent, obj); } rawContent.Add(BYTE_SQUARE_CLOSING_BRACKET); } else { rawContent.AddRange(pdfObject.GetBytes()); } rawContent.Add(BYTE_SPACE); }
void WriteObjectAddress(PdfObject value) { if (this.layout == PdfWriterLayout.Verbose) this.WriteRaw(String.Format("{0} {1} obj % {2}\n", value.ObjectID.ObjectNumber, value.ObjectID.GenerationNumber, value.GetType().FullName)); else this.WriteRaw(String.Format("{0} {1} obj\n", value.ObjectID.ObjectNumber, value.ObjectID.GenerationNumber)); }