/// <summary> /// Reemplaza las cadenas de texto que encuentre en el array de datos del PDF. /// </summary> /// <param name="obj"></param> private void ReplacePRStream(PdfObject obj) { PRStream prStream = (PRStream)obj; byte[] data = PdfReader.GetStreamBytes(prStream); prStream.SetData(ReplaceValues(data)); }
/// <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(); }
private void Do_Form(PdfStream stream) { PdfDictionary resources = stream.GetAsDict(PdfName.RESOURCES); byte[] contentBytes = ContentByteUtils.GetContentBytesFromContentObject(stream); contentBytes = _modifier.Modify(contentBytes, resources); PRStream prStream = stream as PRStream; prStream.SetData(contentBytes); }
public static void ReplaceStream(PRStream orig, PdfStream stream) { orig.Clear(); MemoryStream ms = new MemoryStream(); stream.WriteContent(ms); orig.SetData(ms.ToArray(), false); Console.WriteLine("Iterating keys"); foreach (System.Collections.Generic.KeyValuePair <PdfName, PdfObject> keyValuePair in stream) { orig.Put(keyValuePair.Key, stream.Get(keyValuePair.Key)); } }
/// <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()); }
private static void FixPageNumberOnStream(PRStream stream, string initialLabel, string newPageLabel) { if (stream == null) { throw new Exception("The stream is null"); } byte[] data = PdfReader.GetStreamBytes(stream); var utf8 = new UTF8Encoding(); string originalString = utf8.GetString(data); if (originalString.Contains($"({initialLabel})Tj")) { string newString = originalString .Replace($"({initialLabel})Tj", $"({newPageLabel})Tj") .Replace("/F2 1", "/F1 1"); byte[] newData = utf8.GetBytes(newString); stream.SetData(newData); } }
/** * Parses the content of a page, replacing appearances of annotations * with Form XObjects. * @param page a page dictionary * @throws IOException */ 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)); }
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); }
/// <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); if ("BI".Equals(@operator.ToString())) { int found = 0; int ch; bool immediateAfterBI = true; while ((ch = tokeniser.Read()) != -1) { if (!immediateAfterBI || !PRTokeniser.IsWhitespace(ch)) { baos.WriteByte((byte)ch); } immediateAfterBI = false; if (found == 0 && PRTokeniser.IsWhitespace(ch)) { found++; } else if (found == 1 && ch == 'E') { found++; } else if (found == 1 && PRTokeniser.IsWhitespace(ch)) { // this clause is needed if we have a white space character that is part of the image data // followed by a whitespace character that precedes the EI operator. In this case, we need // to flush the first whitespace, then treat the current whitespace as the first potential // character for the end of stream check. Note that we don't increment 'found' here. } else if (found == 2 && ch == 'I') { found++; } else if (found == 3 && PRTokeniser.IsWhitespace(ch)) { break; } else { found = 0; } } } } baos.Flush(); baos.Close(); stream.SetData(baos.GetBuffer()); }
public virtual void Invoke(PdfContentStreamProcessor pdfContentStreamProcessor, PdfLiteral oper, List <PdfObject> operands) { String operatorStr = oper.ToString(); PdfContentByte canvas = cleanUpStrategy.Context.Canvas; PRStream xFormStream = null; bool disableOutput = pathConstructionOperators.Contains(operatorStr) || pathPaintingOperators.Contains(operatorStr) || clippingPathOperators.Contains(operatorStr); GraphicsState gs = pdfContentStreamProcessor.Gs(); // key - number of a string in the TJ operator, value - number following the string; the first number without string (if it's presented) is stored under 0. // BE AWARE: zero-length strings are ignored!!! IDictionary <int, float> structuredTJoperands = null; if ("Do" == operatorStr) { if (operands.Count == 2 && operands[0].IsName()) { PdfDictionary xObjResources = cleanUpStrategy.Context.Resources.GetAsDict(PdfName.XOBJECT); if (xObjResources != null) { PdfStream xObj = xObjResources.GetAsStream((PdfName)operands[0]); if (xObj is PRStream && xObj.GetAsName(PdfName.SUBTYPE) != null && xObj.GetAsName(PdfName.SUBTYPE).CompareTo(PdfName.FORM) == 0) { xFormStream = (PRStream)xObj; cleanUpStrategy.RegisterNewContext(xObj.GetAsDict(PdfName.RESOURCES), null); } } } } originalContentOperator.Invoke(pdfContentStreamProcessor, oper, operands); IList <PdfCleanUpContentChunk> chunks = cleanUpStrategy.Chunks; if (xFormStream != null) { xFormStream.SetData(cleanUpStrategy.Context.Canvas.ToPdf(cleanUpStrategy.Context.Canvas.PdfWriter)); cleanUpStrategy.PopContext(); canvas = cleanUpStrategy.Context.Canvas; } if ("Do" == operatorStr) { if (chunks.Count > 0 && chunks[0] is PdfCleanUpContentChunk.Image) { PdfCleanUpContentChunk.Image chunk = (PdfCleanUpContentChunk.Image)chunks[0]; if (chunk.Visible) { PdfDictionary xObjResources = cleanUpStrategy.Context.Resources.GetAsDict(PdfName.XOBJECT); PRStream imageStream = (PRStream)xObjResources.GetAsStream((PdfName)operands[0]); UpdateImageStream(imageStream, chunk.NewImageData); } else { disableOutput = true; } } } else if (lineStyleOperators.Contains(operatorStr)) { disableOutput = true; } else if (textShowingOperators.Contains(operatorStr) && !AllChunksAreVisible(cleanUpStrategy.Chunks)) { disableOutput = true; if ("'" == operatorStr) { canvas.InternalBuffer.Append(TStar); } else if ("\"" == operatorStr) { operands[0].ToPdf(canvas.PdfWriter, canvas.InternalBuffer); canvas.InternalBuffer.Append(Tw); operands[1].ToPdf(canvas.PdfWriter, canvas.InternalBuffer); canvas.InternalBuffer.Append(TcTStar); } else if ("TJ" == operatorStr) { structuredTJoperands = StructureTJarray((PdfArray)operands[0]); } WriteTextChunks(structuredTJoperands, chunks, canvas, gs.CharacterSpacing, gs.WordSpacing, gs.FontSize, gs.HorizontalScaling); } else if (pathPaintingOperators.Contains(operatorStr)) { WritePath(operatorStr, canvas, gs.ColorSpaceStroke); } else if (strokeColorOperators.Contains(operatorStr)) { // Replace current color with the new one. cleanUpStrategy.Context.PopStrokeColor(); cleanUpStrategy.Context.PushStrokeColor(operands); } else if ("q" == operatorStr) { cleanUpStrategy.Context.PushStrokeColor(cleanUpStrategy.Context.PeekStrokeColor()); } else if ("Q" == operatorStr) { cleanUpStrategy.Context.PopStrokeColor(); } if (!disableOutput) { WriteOperands(canvas, operands); } cleanUpStrategy.ClearChunks(); }
/// <summary> /// Gets image from PDF and compresses it - Found on StackOverflow - asis /// </summary> /// <param name="reader"></param> /// <param name="quality"></param> public static void ReduceResolution(PdfReader reader, long quality) { int n = reader.XrefSize; for (int i = 0; i < n; i++) { PdfObject obj = reader.GetPdfObject(i); if (obj == null || !obj.IsStream()) { continue; } PdfDictionary dict = (PdfDictionary)PdfReader.GetPdfObject(obj); PdfName subType = (PdfName)PdfReader.GetPdfObject( dict.Get(PdfName.SUBTYPE) ); if (!PdfName.IMAGE.Equals(subType)) { continue; } PRStream stream = (PRStream)obj; try { PdfImageObject image = new PdfImageObject(stream); //PdfName filter = (PdfName)image.Get(PdfName.FILTER); //if ( // PdfName.JBIG2DECODE.Equals(filter) // || PdfName.JPXDECODE.Equals(filter) // || PdfName.CCITTFAXDECODE.Equals(filter) // || PdfName.FLATEDECODE.Equals(filter) //) continue; System.Drawing.Image img = image.GetDrawingImage(); if (img == null) { continue; } var ll = image.GetImageBytesType(); int width = img.Width; int height = img.Height; using (System.Drawing.Bitmap dotnetImg = new System.Drawing.Bitmap(img)) { // set codec to jpeg type => jpeg index codec is "1" System.Drawing.Imaging.ImageCodecInfo codec = System.Drawing.Imaging.ImageCodecInfo.GetImageEncoders()[1]; // set parameters for image quality System.Drawing.Imaging.EncoderParameters eParams = new System.Drawing.Imaging.EncoderParameters(1); eParams.Param[0] = new System.Drawing.Imaging.EncoderParameter( System.Drawing.Imaging.Encoder.Quality, quality ); using (MemoryStream msImg = new MemoryStream()) { dotnetImg.Save(msImg, codec, eParams); msImg.Position = 0; stream.SetData(msImg.ToArray()); stream.SetData( msImg.ToArray(), false, PRStream.BEST_COMPRESSION ); stream.Put(PdfName.TYPE, PdfName.XOBJECT); stream.Put(PdfName.SUBTYPE, PdfName.IMAGE); stream.Put(PdfName.FILTER, image.Get(PdfName.FILTER)); stream.Put(PdfName.FILTER, PdfName.DCTDECODE); stream.Put(PdfName.WIDTH, new PdfNumber(width)); stream.Put(PdfName.HEIGHT, new PdfNumber(height)); stream.Put(PdfName.BITSPERCOMPONENT, new PdfNumber(8)); stream.Put(PdfName.COLORSPACE, PdfName.DEVICERGB); } } } catch { // throw; // iText[Sharp] can't handle all image types... } finally { // may or may not help reader.RemoveUnusedObjects(); } } }
public void Invoke(PdfContentStreamProcessor pdfContentStreamProcessor, PdfLiteral @operator, List <PdfObject> operands) { String operatorStr = @operator.ToString(); PdfContentByte canvas = cleanUpStrategy.Context.Canvas; PRStream xFormStream = null; // key - number of a string in the TJ operator, value - number following the string; the first number without string (if it's presented) is stored under 0. // BE AWARE: zero-length strings are ignored!!! IDictionary <int, float> structuredTJoperands = null; if ("Do" == operatorStr) { if (operands.Count == 2 && operands[0].IsName()) { PdfDictionary xObjResources = cleanUpStrategy.Context.Resources.GetAsDict(PdfName.XOBJECT); if (xObjResources != null) { PdfStream xObj = xObjResources.GetAsStream((PdfName)operands[0]); if (xObj is PRStream && xObj.GetAsName(PdfName.SUBTYPE) != null && xObj.GetAsName(PdfName.SUBTYPE).CompareTo(PdfName.FORM) == 0) { xFormStream = (PRStream)xObj; cleanUpStrategy.RegisterNewContext(xObj.GetAsDict(PdfName.RESOURCES), null); } } } } originalContentOperator.Invoke(pdfContentStreamProcessor, @operator, operands); IList <PdfCleanUpContentChunk> chunks = cleanUpStrategy.Chunks; bool disableOutput = false; if (xFormStream != null) { xFormStream.SetData(cleanUpStrategy.Context.Canvas.ToPdf(cleanUpStrategy.Context.Canvas.PdfWriter)); cleanUpStrategy.PopContext(); canvas = cleanUpStrategy.Context.Canvas; } if ("Do" == operatorStr) { if (chunks.Count > 0 && chunks[0].IsImage()) { PdfCleanUpContentChunk chunk = chunks[0]; if (chunk.IsVisible()) { PdfDictionary xObjResources = cleanUpStrategy.Context.Resources.GetAsDict(PdfName.XOBJECT); PRStream imageStream = (PRStream)xObjResources.GetAsStream((PdfName)operands[0]); UpdateImage(imageStream, chunk.NewImageData); } else { disableOutput = true; } } } else if ("q" == operatorStr) { cleanUpStrategy.Context.SaveGraphicsState(); } else if ("Q" == operatorStr) { cleanUpStrategy.Context.RestoreGraphicsState(); } else if ("Tf" == operatorStr) { cleanUpStrategy.Context.FontSize = ((PdfNumber)operands[1]).FloatValue; } else if ("Tc" == operatorStr) { cleanUpStrategy.Context.CharacterSpacing = ((PdfNumber)operands[0]).FloatValue; } else if ("Tw" == operatorStr) { cleanUpStrategy.Context.WordSpacing = ((PdfNumber)operands[0]).FloatValue; } else if ("Tz" == operatorStr) { cleanUpStrategy.Context.HorizontalScaling = ((PdfNumber)operands[0]).FloatValue; } else if (textShowingOperators.Contains(operatorStr) && !AllChunksAreVisible(cleanUpStrategy.Chunks)) { disableOutput = true; if ("'" == operatorStr) { canvas.InternalBuffer.Append(TStar); } else if ("\"" == operatorStr) { operands[0].ToPdf(canvas.PdfWriter, canvas.InternalBuffer); canvas.InternalBuffer.Append(Tw); operands[1].ToPdf(canvas.PdfWriter, canvas.InternalBuffer); canvas.InternalBuffer.Append(TcTStar); cleanUpStrategy.Context.CharacterSpacing = ((PdfNumber)operands[1]).FloatValue; } else if ("TJ" == operatorStr) { structuredTJoperands = StructureTJarray((PdfArray)operands[0]); } RenderChunks(structuredTJoperands, chunks, canvas); } else if ("\"" == operatorStr) { cleanUpStrategy.Context.CharacterSpacing = ((PdfNumber)operands[1]).FloatValue; } if (!disableOutput) { int index = 0; foreach (PdfObject o in operands) { ToPdf(o, canvas.PdfWriter, canvas.InternalBuffer); canvas.InternalBuffer.Append(operands.Count > ++index ? (byte)' ' : (byte)'\n'); } } cleanUpStrategy.ClearChunks(); }
private void Do_Image(PdfStream stream) { byte[] imageBuffer = null; PdfName filter = PdfName.NONE; if (stream.Contains(PdfName.FILTER)) { filter = stream.GetAsName(PdfName.FILTER); } int imageWidth = stream.GetAsNumber(PdfName.WIDTH).IntValue; int imageHeight = stream.GetAsNumber(PdfName.HEIGHT).IntValue; int imageBpp = stream.GetAsNumber(PdfName.BITSPERCOMPONENT).IntValue; PRStream prStream = stream as PRStream; bool cannotReadImage = false; Bitmap image = null; try { PdfImageObject pdfImage = new PdfImageObject(prStream); image = pdfImage.GetDrawingImage() as Bitmap; string strFile = "C:\\PDF_Print\\pdf" + bmpfileidx.ToString() + ".bmp"; image.Save(strFile); bmpfileidx++; } catch { try { if (filter == PdfName.FLATEDECODE) { byte[] streamBuffer = PdfReader.GetStreamBytes(prStream); image = this.CreateBitmapFromFlateDecodeImage(streamBuffer, imageWidth, imageHeight, imageBpp); string strFile = "C:\\PDF_Print\\pdf_" + bmpfileidx.ToString() + ".bmp"; image.Save(strFile); bmpfileidx++; } } catch { cannotReadImage = true; } } if (!cannotReadImage) { image = this.ConvertToGrayscale(image); //image = this.ConvertToBlackWhite(image); using (var ms = new MemoryStream()) { System.Drawing.Imaging.Encoder myEncoder = System.Drawing.Imaging.Encoder.Quality; ImageCodecInfo jgpEncoder = GetEncoder(ImageFormat.Jpeg); EncoderParameters myEncoderParameters = new EncoderParameters(1); EncoderParameter myEncoderParameter = new EncoderParameter(myEncoder, 80L); myEncoderParameters.Param[0] = myEncoderParameter; image.Save(ms, jgpEncoder, myEncoderParameters); imageBuffer = ms.ToArray(); //imageBuffer = ms.GetBuffer(); iTextSharp.text.Image newImage = iTextSharp.text.Image.GetInstance(imageBuffer); newImage.SimplifyColorspace(); // PdfImage tempPdfImage = new PdfImage(newImage, newImage.ToString(), null); // prStream.Clear(); // prStream.SetDataRaw(imageBuffer); // prStream.Merge(tempPdfImage); // imageBuffer = newImage.OriginalData; // prStream.Clear(); prStream.SetData(imageBuffer, false, PRStream.NO_COMPRESSION); prStream.Put(PdfName.TYPE, PdfName.XOBJECT); prStream.Put(PdfName.SUBTYPE, PdfName.IMAGE); prStream.Put(PdfName.FILTER, PdfName.DCTDECODE); prStream.Put(PdfName.WIDTH, new PdfNumber(image.Width)); prStream.Put(PdfName.HEIGHT, new PdfNumber(image.Height)); prStream.Put(PdfName.BITSPERCOMPONENT, new PdfNumber(8)); prStream.Put(PdfName.COLORSPACE, PdfName.DEVICERGB); prStream.Put(PdfName.LENGTH, new PdfNumber(imageBuffer.LongLength)); } } }
private void Do_Image(PdfStream stream) { byte[] imageBuffer = null; PdfName filter = PdfName.NONE; if (stream.Contains(PdfName.FILTER)) { filter = stream.GetAsName(PdfName.FILTER); } int imageWidth = stream.GetAsNumber(PdfName.WIDTH).IntValue; int imageHeight = stream.GetAsNumber(PdfName.HEIGHT).IntValue; int imageBpp = stream.GetAsNumber(PdfName.BITSPERCOMPONENT).IntValue; PRStream prStream = stream as PRStream; bool cannotReadImage = false; Bitmap image = null; try { PdfImageObject pdfImage = new PdfImageObject(prStream); image = pdfImage.GetDrawingImage() as Bitmap; } catch { try { if (filter == PdfName.FLATEDECODE) { byte[] streamBuffer = PdfReader.GetStreamBytes(prStream); image = this.CreateBitmapFromFlateDecodeImage(streamBuffer, imageWidth, imageHeight, imageBpp); } } catch { cannotReadImage = true; } } if (!cannotReadImage) { image = this.ConvertToGrayscale(image); using (var ms = new MemoryStream()) { System.Drawing.Imaging.Encoder myEncoder = System.Drawing.Imaging.Encoder.Quality; ImageCodecInfo jgpEncoder = GetEncoder(ImageFormat.Jpeg); EncoderParameters myEncoderParameters = new EncoderParameters(1); //EncoderParameter myEncoderParameter = new EncoderParameter(myEncoder, 80L); EncoderParameter myEncoderParameter = new EncoderParameter(myEncoder, 15L); myEncoderParameters.Param[0] = myEncoderParameter; image.Save(ms, jgpEncoder, myEncoderParameters); imageBuffer = ms.GetBuffer(); } Image compressedImage = Image.GetInstance(imageBuffer); imageBuffer = compressedImage.OriginalData; prStream.Clear(); //prStream.SetData(imageBuffer, false, PRStream.NO_COMPRESSION); prStream.SetData(imageBuffer, false, PRStream.BEST_COMPRESSION); prStream.Put(PdfName.TYPE, PdfName.XOBJECT); prStream.Put(PdfName.SUBTYPE, PdfName.IMAGE); prStream.Put(PdfName.FILTER, PdfName.DCTDECODE); prStream.Put(PdfName.WIDTH, new PdfNumber(image.Width)); prStream.Put(PdfName.HEIGHT, new PdfNumber(image.Height)); prStream.Put(PdfName.BITSPERCOMPONENT, new PdfNumber(8)); prStream.Put(PdfName.COLORSPACE, PdfName.DEVICERGB); prStream.Put(PdfName.LENGTH, new PdfNumber(imageBuffer.LongLength)); } }