public PdfPageTree(PdfObjectId objectId) : base(objectId) { this[PdfName.Names.Type] = PdfName.Names.Pages; this.kids = new PdfArray(); this[PdfName.Names.Kids] = kids; }
/// <summary> /// Initializes a new instance of the <see cref="ArrowAnnotation"/> class. /// </summary> /// <param name="color">The arrow color.</param> /// <param name="x1">The x1.</param> /// <param name="y1">The y1.</param> /// <param name="x2">The x2.</param> /// <param name="y2">The y2.</param> public ArrowAnnotation(XColor color, float x1, float y1, float x2, float y2) { Elements.SetName(Keys.Subtype, "/Line"); var line = new PdfArray(); line.Elements.Add(new PdfReal(x1)); line.Elements.Add(new PdfReal(y1)); line.Elements.Add(new PdfReal(x2)); line.Elements.Add(new PdfReal(y2)); Elements["/L"] = line; // change line ending PdfArray end = new PdfArray(); end.Elements.Add(new PdfName("/ClosedArrow")); end.Elements.Add(new PdfName("/None")); Elements["/LE"] = end; // change all color properties Elements.SetColor("/IC", color); Color = color; // change line width var bsDict = new PdfBorderStyle(3, BorderStyle.Solid); Elements[Keys.BS] = bsDict; }
static PdfResources() { DefaultProcedureSets = new PdfArray(); DefaultProcedureSets.Add(PdfName.Names.PDF); DefaultProcedureSets.Add(PdfName.Names.Text); DefaultProcedureSets.Add(PdfName.Names.ImageB); DefaultProcedureSets.Add(PdfName.Names.ImageC); DefaultProcedureSets.Add(PdfName.Names.ImageI); }
/** <summary>Gets the color corresponding to the specified components.</summary> <param name="components">Color components to convert.</param> */ public static DeviceNColor Get( PdfArray components ) { return (components != null ? new DeviceNColor(components) : null ); }
static PdfGoToRemote() { DefaultDestination = new PdfArray(); DefaultDestination.Add(new PdfNumeric(0)); DefaultDestination.Add(PdfName.Names.XYZ); DefaultDestination.Add(PdfNull.Null); DefaultDestination.Add(PdfNull.Null); DefaultDestination.Add(PdfNull.Null); }
protected internal override void Write(PdfWriter writer) { PdfArray dest = new PdfArray(); dest.Add(pageReference); dest.Add(PdfName.Names.XYZ); dest.Add(new PdfNumeric(xPosition)); dest.Add(new PdfNumeric(yPosition)); dest.Add(PdfNull.Null); this[PdfName.Names.D] = dest; base.Write(writer); }
private PdfObject CleverPdfArrayClone(PdfArray array) { PdfArray newArray = new PdfArray(); for (int i = 0; i < array.Size; i++) { PdfObject obj = array[i]; if (obj is PdfDictionary) newArray.Add(CleverPdfDictionaryClone((PdfDictionary) obj)); else newArray.Add(obj); } return newArray; }
public virtual PdfObject Visit( PdfArray obj, object data ) { foreach(PdfDirectObject item in obj) { if(item != null) {item.Accept(this, data);} } return obj; }
/** <summary>Gets the color corresponding to the specified components.</summary> <param name="components">Color components to convert.</param> */ public static DeviceColor Get( PdfArray components ) { if(components == null) return null; switch(components.Count) { case 1: return DeviceGrayColor.Get(components); case 3: return DeviceRGBColor.Get(components); case 4: return DeviceCMYKColor.Get(components); default: return null; } }
public PdfPage( PdfResources resources, PdfContentStream contents, int pagewidth, int pageheight, PdfObjectId objectId) : base(objectId) { this[PdfName.Names.Type] = PdfName.Names.Page; this[PdfName.Names.Resources] = resources.GetReference(); this[PdfName.Names.Contents] = contents.GetReference(); PdfArray mediaBox = new PdfArray(); mediaBox.Add(new PdfNumeric(0)); mediaBox.Add(new PdfNumeric(0)); mediaBox.Add(new PdfNumeric(pagewidth)); mediaBox.Add(new PdfNumeric(pageheight)); this[PdfName.Names.MediaBox] = mediaBox; }
/// <summary> /// Initializes a new instance of the <see cref="FreeTextAnnotation"/> class. /// </summary> /// <param name="color">The text color.</param> /// <param name="font">The font name.</param> /// <param name="fontSize">Size of the font.</param> public FreeTextAnnotation(XColor color, string font, double fontSize) { Elements.SetName(Keys.Subtype, "/FreeText"); string daString = string.Format(CultureInfo.InvariantCulture, "{0} {1} {2} rg /{3} {4} Tf /BG []", color.R / (double)byte.MaxValue, color.G / (double)byte.MaxValue, color.B / (double)byte.MaxValue, font, fontSize); Elements["/DA"] = new PdfString(daString); // no border var border = new PdfArray(); border.Elements.Add(new PdfInteger(0)); border.Elements.Add(new PdfInteger(0)); border.Elements.Add(new PdfInteger(0)); Elements[Keys.Border] = border; }
public void CopyTaggedPdf6() { InitializeDocument("6"); PdfReader reader = new PdfReader(SOURCE11); int n = 8; copy.AddPage(copy.GetImportedPage(reader, 1, true)); copy.AddPage(copy.GetImportedPage(reader, 25, true)); copy.AddPage(copy.GetImportedPage(reader, 7, true)); copy.AddPage(copy.GetImportedPage(reader, 48, true)); copy.AddPage(copy.GetImportedPage(reader, 50, true)); copy.AddPage(copy.GetImportedPage(reader, 2, true)); copy.AddPage(copy.GetImportedPage(reader, 8, true)); copy.AddPage(copy.GetImportedPage(reader, 90, true)); document.Close(); reader.Close(); reader = new PdfReader(output); PdfDictionary structTreeRoot = VerifyIsDictionary(reader.Catalog.GetDirectObject(PdfName.STRUCTTREEROOT), NO_STRUCT_TREE_ROOT); VerifyArraySize(structTreeRoot.Get(PdfName.K), 6, "Invalid count of kids in StructTreeRoot"); PdfObject obj = PdfStructTreeController.GetDirectObject(structTreeRoot.Get(PdfName.PARENTTREE)); VerifyIsDictionary(obj, NO_PARENT_TREE); PdfArray array = ((PdfDictionary)obj).GetAsArray(PdfName.NUMS); VerifyArraySize(array, n * 2, "Nums"); int[] nums = new int[] { 3, 18, 9, 25, 15, 91, 13, 18 }; for (int i = 0; i < n; ++i) { VerifyArraySize(PdfStructTreeController.GetDirectObject(array.GetDirectObject(i * 2 + 1)), nums[i], "Nums of page " + (i + 1)); } PdfDictionary ClassMap = VerifyIsDictionary(PdfStructTreeController.GetDirectObject(structTreeRoot.Get(PdfName.CLASSMAP)), NO_CLASS_MAP); if (ClassMap.Size != 27) { Assert.Fail("ClassMap incorrect"); } String[] CMs = new String[] { "CM118", "CM117", "CM133", "CM47", "CM46", "CM114", "CM43", "CM110", "CM21", "CM22", "CM26", "CM27", "CM145", "CM128", "CM29", "CM56", "CM1", "CM2", "CM72", "CM16", "CM34", "CM17", "CM14", "CM15", "CM119", "CM12", "CM13" }; for (int i = 0; i < CMs.Length; ++i) { VerifyIsDictionary(PdfStructTreeController.GetDirectObject(ClassMap.Get(new PdfName(CMs[i]))), "ClassMap.does.not.contain.\"" + CMs[i] + "\""); } PdfDictionary RoleMap = VerifyIsDictionary(PdfStructTreeController.GetDirectObject(structTreeRoot.Get(PdfName.ROLEMAP)), NO_ROLE_MAP); if (!PdfName.SPAN.Equals(RoleMap.Get(new PdfName("ParagraphSpan")))) { throw new BadPdfFormatException("RoleMap does not contain \"ParagraphSpan\"."); } //if (reader.eofPos != 249068) Assert.Fail("Invalid size of pdf."); reader.Close(); CompareResults("6"); }
/// <summary> /// An array of numbers in the range 0.0 to 1.0 specifying the interior color /// which is used to fill the annotation's rectangle. /// </summary> /// <param name="interiorColor"> /// a /// <see cref="iText.Kernel.Pdf.PdfArray"/> /// of numbers in the range 0.0 to 1.0. The number of array elements determines /// the colour space in which the colour is defined: 0 - No colour, transparent; 1 - DeviceGray, /// 3 - DeviceRGB, 4 - DeviceCMYK. For the /// <see cref="PdfRedactAnnotation"/> /// number of elements shall be /// equal to 3 (which defines DeviceRGB colour space). /// </param> /// <returns> /// this /// <see cref="PdfSquareAnnotation"/> /// instance. /// </returns> public virtual iText.Kernel.Pdf.Annot.PdfSquareAnnotation SetInteriorColor(PdfArray interiorColor) { return((iText.Kernel.Pdf.Annot.PdfSquareAnnotation)Put(PdfName.IC, interiorColor)); }
private PdfObject getColorspace() { if (_iccProfile != null) { if ((_colorType & 2) == 0) { return(PdfName.Devicegray); } else { return(PdfName.Devicergb); } } if (_gamma.ApproxEquals(1f) && !_hasChrm) { if ((_colorType & 2) == 0) { return(PdfName.Devicegray); } else { return(PdfName.Devicergb); } } else { var array = new PdfArray(); var dic = new PdfDictionary(); if ((_colorType & 2) == 0) { if (_gamma.ApproxEquals(1f)) { return(PdfName.Devicegray); } array.Add(PdfName.Calgray); dic.Put(PdfName.Gamma, new PdfNumber(_gamma)); dic.Put(PdfName.Whitepoint, new PdfLiteral("[1 1 1]")); array.Add(dic); } else { PdfObject wp = new PdfLiteral("[1 1 1]"); array.Add(PdfName.Calrgb); if (_gamma.ApproxNotEqual(1f)) { var gm = new PdfArray(); var n = new PdfNumber(_gamma); gm.Add(n); gm.Add(n); gm.Add(n); dic.Put(PdfName.Gamma, gm); } if (_hasChrm) { var z = _yW * ((_xG - _xB) * _yR - (_xR - _xB) * _yG + (_xR - _xG) * _yB); var ya = _yR * ((_xG - _xB) * _yW - (_xW - _xB) * _yG + (_xW - _xG) * _yB) / z; var xa = ya * _xR / _yR; var za = ya * ((1 - _xR) / _yR - 1); var yb = -_yG * ((_xR - _xB) * _yW - (_xW - _xB) * _yR + (_xW - _xR) * _yB) / z; var xb = yb * _xG / _yG; var zb = yb * ((1 - _xG) / _yG - 1); var yc = _yB * ((_xR - _xG) * _yW - (_xW - _xG) * _yW + (_xW - _xR) * _yG) / z; var xc = yc * _xB / _yB; var zc = yc * ((1 - _xB) / _yB - 1); var xw = xa + xb + xc; float yw = 1;//YA+YB+YC; var zw = za + zb + zc; var wpa = new PdfArray(); wpa.Add(new PdfNumber(xw)); wpa.Add(new PdfNumber(yw)); wpa.Add(new PdfNumber(zw)); wp = wpa; var matrix = new PdfArray(); matrix.Add(new PdfNumber(xa)); matrix.Add(new PdfNumber(ya)); matrix.Add(new PdfNumber(za)); matrix.Add(new PdfNumber(xb)); matrix.Add(new PdfNumber(yb)); matrix.Add(new PdfNumber(zb)); matrix.Add(new PdfNumber(xc)); matrix.Add(new PdfNumber(yc)); matrix.Add(new PdfNumber(zc)); dic.Put(PdfName.Matrix, matrix); } dic.Put(PdfName.Whitepoint, wp); array.Add(dic); } return(array); } }
protected internal PdfCieBasedCs(PdfArray pdfObject) : base(pdfObject) { }
/// <summary>Setter for the annotation's preset dashed border style.</summary> /// <remarks> /// Setter for the annotation's preset dashed border style. This property has affect only if /// <see cref="PdfAnnotation.STYLE_DASHED"/> /// style was used for the annotation border style (see /// <see cref="SetBorderStyle(iText.Kernel.Pdf.PdfName)"/>. /// See ISO-320001 8.4.3.6, "Line Dash Pattern" for the format in which dash pattern shall be specified. /// </remarks> /// <param name="dashPattern"> /// a dash array defining a pattern of dashes and gaps that /// shall be used in drawing a dashed border. /// </param> /// <returns> /// this /// <see cref="PdfSquareAnnotation"/> /// instance. /// </returns> public virtual iText.Kernel.Pdf.Annot.PdfSquareAnnotation SetDashPattern(PdfArray dashPattern) { return(SetBorderStyle(BorderStyleUtil.SetDashPattern(GetBorderStyle(), dashPattern))); }
/// <summary>Move tag structure of page to other place in the same document</summary> /// <param name="document">document in which modifications will take place (should be opened in read-write mode) /// </param> /// <param name="from">page, which tag structure will be moved</param> /// <param name="insertBefore">indicates before what page number structure will be inserted to</param> public static void Move(PdfDocument document, PdfPage from, int insertBefore) { if (!document.IsTagged() || insertBefore < 1 || insertBefore > document.GetNumberOfPages() + 1) { return; } int fromNum = document.GetPageNumber(from); if (fromNum == 0 || fromNum == insertBefore || fromNum + 1 == insertBefore) { return; } int destStruct; int currStruct = 0; if (fromNum > insertBefore) { destStruct = currStruct = SeparateStructure(document, 1, insertBefore, 0); currStruct = SeparateStructure(document, insertBefore, fromNum, currStruct); currStruct = SeparateStructure(document, fromNum, fromNum + 1, currStruct); } else { currStruct = SeparateStructure(document, 1, fromNum, 0); currStruct = SeparateStructure(document, fromNum, fromNum + 1, currStruct); destStruct = currStruct = SeparateStructure(document, fromNum + 1, insertBefore, currStruct); } ICollection <PdfDictionary> topsToMove = new HashSet <PdfDictionary>(); ICollection <PdfMcr> mcrs = document.GetStructTreeRoot().GetPageMarkedContentReferences(from); if (mcrs != null) { foreach (PdfMcr mcr in mcrs) { PdfDictionary top = GetTopmostParent(mcr); if (top != null) { if (top.IsFlushed()) { throw new PdfException(PdfException.CannotMoveFlushedTag); } topsToMove.Add(top); } } } IList <PdfDictionary> orderedTopsToMove = new List <PdfDictionary>(); PdfArray tops = document.GetStructTreeRoot().GetKidsObject(); for (int i = 0; i < tops.Size(); ++i) { PdfDictionary top = tops.GetAsDictionary(i); if (topsToMove.Contains(top)) { orderedTopsToMove.Add(top); tops.Remove(i); if (i < destStruct) { --destStruct; } } } foreach (PdfDictionary top in orderedTopsToMove) { document.GetStructTreeRoot().AddKidObject(destStruct++, top); } }
public Lab(PdfArray pdfObject) : base(pdfObject) { }
public virtual void SetDashPattern(PdfArray dashPattern) { this.dashPattern = dashPattern; }
/// <summary>Updates current graphic state with values from extended graphic state dictionary.</summary> /// <param name="extGState">the wrapper around the extended graphic state dictionary</param> /// <param name="pdfDocument">the document to retrieve fonts from. Needed when the newly created fonts are used /// </param> internal virtual void UpdateFromExtGState(PdfExtGState extGState, PdfDocument pdfDocument) { float?lw = extGState.GetLineWidth(); if (lw != null) { lineWidth = (float)lw; } int?lc = extGState.GetLineCapStyle(); if (lc != null) { lineCapStyle = (int)lc; } int?lj = extGState.GetLineJoinStyle(); if (lj != null) { lineJoinStyle = (int)lj; } float?ml = extGState.GetMiterLimit(); if (ml != null) { miterLimit = (float)ml; } PdfArray d = extGState.GetDashPattern(); if (d != null) { dashPattern = d; } PdfName ri = extGState.GetRenderingIntent(); if (ri != null) { renderingIntent = ri; } bool?op = extGState.GetStrokeOverprintFlag(); if (op != null) { strokeOverprint = (bool)op; } op = extGState.GetFillOverprintFlag(); if (op != null) { fillOverprint = (bool)op; } int?opm = extGState.GetOverprintMode(); if (opm != null) { overprintMode = (int)opm; } PdfArray fnt = extGState.GetFont(); if (fnt != null) { PdfDictionary fontDictionary = fnt.GetAsDictionary(0); if (this.font == null || this.font.GetPdfObject() != fontDictionary) { this.font = pdfDocument.GetFont(fontDictionary); } PdfNumber fntSz = fnt.GetAsNumber(1); if (fntSz != null) { this.fontSize = fntSz.FloatValue(); } } PdfObject bg = extGState.GetBlackGenerationFunction(); if (bg != null) { blackGenerationFunction = bg; } PdfObject bg2 = extGState.GetBlackGenerationFunction2(); if (bg2 != null) { blackGenerationFunction2 = bg2; } PdfObject ucr = extGState.GetUndercolorRemovalFunction(); if (ucr != null) { underColorRemovalFunction = ucr; } PdfObject ucr2 = extGState.GetUndercolorRemovalFunction2(); if (ucr2 != null) { underColorRemovalFunction2 = ucr2; } PdfObject tr = extGState.GetTransferFunction(); if (tr != null) { transferFunction = tr; } PdfObject tr2 = extGState.GetTransferFunction2(); if (tr2 != null) { transferFunction2 = tr2; } PdfObject ht = extGState.GetHalftone(); if (ht != null) { halftone = ht; } PdfObject local_htp = extGState.GetPdfObject().Get(PdfName.HTP); if (local_htp != null) { this.htp = local_htp; } float?fl = extGState.GetFlatnessTolerance(); if (fl != null) { flatnessTolerance = (float)fl; } float?sm = extGState.GetSmothnessTolerance(); if (sm != null) { smoothnessTolerance = sm; } bool?sa = extGState.GetAutomaticStrokeAdjustmentFlag(); if (sa != null) { automaticStrokeAdjustment = (bool)sa; } PdfObject bm = extGState.GetBlendMode(); if (bm != null) { blendMode = bm; } PdfObject sMask = extGState.GetSoftMask(); if (sMask != null) { softMask = sMask; } float?ca = extGState.GetStrokeOpacity(); if (ca != null) { strokeAlpha = (float)ca; } ca = extGState.GetFillOpacity(); if (ca != null) { fillAlpha = (float)ca; } bool?ais = extGState.GetAlphaSourceFlag(); if (ais != null) { alphaIsShape = (bool)ais; } bool?tk = extGState.GetTextKnockoutFlag(); if (tk != null) { textKnockout = (bool)tk; } }
/** * <summary>Parses the current PDF object [PDF:1.6:3.2].</summary> */ public PdfDataObject ParsePdfObject( ) { /* * NOTE: Object parsing is intrinsically a sequential operation tied to the stream pointer. * Calls bound towards other classes are potentially disruptive for the predictability of * the position of the stream pointer, so we are forced to carefully keep track of our * current position in order to recover its proper state after any outbound call. */ do { // Which token type? switch (tokenType) { case TokenTypeEnum.Integer: return(new PdfInteger((int)token)); case TokenTypeEnum.Name: return(new PdfName((string)token, true)); case TokenTypeEnum.Reference: /* * NOTE: Curiously, PDF references are the only primitive objects that require * a file reference. That's because they deal with indirect objects, which are strongly * coupled with the current state of the file: so, PDF references are the fundamental * bridge between the token layer and the file layer. */ return(new PdfReference( (Reference)token, file )); case TokenTypeEnum.Literal: return(new PdfTextString( Encoding.Encode((string)token) )); case TokenTypeEnum.DictionaryBegin: PdfDictionary dictionary = new PdfDictionary(); while (true) { // Key. MoveNext(); if (tokenType == TokenTypeEnum.DictionaryEnd) { break; } PdfName key = (PdfName)ParsePdfObject(); // Value. MoveNext(); PdfDirectObject value = (PdfDirectObject)ParsePdfObject(); // Add the current entry to the dictionary! dictionary[key] = value; } int oldOffset = (int)stream.Position; MoveNext(); // Is this dictionary the header of a stream object [PDF:1.6:3.2.7]? if ((tokenType == TokenTypeEnum.Keyword) && token.Equals(Keyword.BeginStream)) { // Keep track of current position! long position = stream.Position; // Get the stream length! /* * NOTE: Indirect reference resolution is an outbound call (stream pointer hazard!), * so we need to recover our current position after it returns. */ int length = ((PdfInteger)files.File.Resolve(dictionary[PdfName.Length])).RawValue; // Move to the stream data beginning! stream.Seek(position); SkipEOL(); // Copy the stream data to the instance! byte[] data = new byte[length]; stream.Read(data); MoveNext(); // Postcondition (last token should be 'endstream' keyword). Object streamType = dictionary[PdfName.Type]; if (PdfName.ObjStm.Equals(streamType)) // Object stream [PDF:1.6:3.4.6]. { return(new ObjectStream( dictionary, new bytes.Buffer(data), file )); } else if (PdfName.XRef.Equals(streamType)) // Cross-reference stream [PDF:1.6:3.4.7]. { return(new XRefStream( dictionary, new bytes.Buffer(data), file )); } else // Generic stream. { return(new PdfStream( dictionary, new bytes.Buffer(data) )); } } else // Stand-alone dictionary. { stream.Seek(oldOffset); // Restores postcondition (last token should be the dictionary end). return(dictionary); } case TokenTypeEnum.ArrayBegin: PdfArray array = new PdfArray(); while (true) { // Value. MoveNext(); if (tokenType == TokenTypeEnum.ArrayEnd) { break; } // Add the current item to the array! array.Add((PdfDirectObject)ParsePdfObject()); } return(array); case TokenTypeEnum.Real: return(new PdfReal((float)token)); case TokenTypeEnum.Boolean: return(PdfBoolean.Get((bool)token)); case TokenTypeEnum.Date: return(new PdfDate((DateTime)token)); case TokenTypeEnum.Hex: return(new PdfTextString( (string)token, PdfString.SerializationModeEnum.Hex )); case TokenTypeEnum.Null: return(null); case TokenTypeEnum.Comment: // NOOP: Comments are simply ignored and skipped. break; default: throw new Exception("Unknown type: " + tokenType); } } while(MoveNext()); return(null); }
protected override void CheckPdfObject(PdfWriter writer, int key, Object obj1) { if (obj1 is PdfNumber) { PdfNumber number = (PdfNumber)obj1; if (Math.Abs(number.DoubleValue) > maxRealValue && number.ToString().Contains(".")) { throw new PdfAConformanceException(obj1, MessageLocalization.GetComposedMessage("real.number.is.out.of.range")); } } else if (obj1 is PdfString) { PdfString str = (PdfString)obj1; if (str.GetBytes().Length > maxStringLength) { throw new PdfAConformanceException(obj1, MessageLocalization.GetComposedMessage("pdf.string.is.too.long")); } } else if (obj1 is PdfArray) { PdfArray array = (PdfArray)obj1; if (array.Size > maxArrayLength) { throw new PdfAConformanceException(obj1, MessageLocalization.GetComposedMessage("pdf.array.exceeds.length.set.by.PDFA1.standard", array.Length.ToString())); } } else if (obj1 is PdfDictionary) { PdfDictionary dictionary = (PdfDictionary)obj1; if (dictionary.Size > maxDictionaryLength) { throw new PdfAConformanceException(obj1, MessageLocalization.GetComposedMessage("pdf.dictionary.is.out.of.bounds")); } PdfName type = dictionary.GetAsName(PdfName.TYPE); if (PdfName.CATALOG.Equals(type)) { if (!dictionary.Contains(PdfName.METADATA)) { throw new PdfAConformanceException(obj1, MessageLocalization.GetComposedMessage("the.document.catalog.dictionary.shall.contain.metadata")); } if (dictionary.Contains(PdfName.AA)) { throw new PdfAConformanceException(obj1, MessageLocalization.GetComposedMessage("the.document.catalog.dictionary.shall.not.include.an.aa.entry")); } if (dictionary.Contains(PdfName.NAMES)) { PdfDictionary names = GetDirectDictionary(dictionary.Get(PdfName.NAMES)); if (names != null && names.Contains(PdfName.EMBEDDEDFILES)) { throw new PdfAConformanceException(obj1, MessageLocalization.GetComposedMessage("the.document.catalog.dictionary.shall.not.include.embeddedfiles.names.entry")); } } if (CheckStructure(conformanceLevel)) { PdfDictionary markInfo = GetDirectDictionary(dictionary.Get(PdfName.MARKINFO)); if (markInfo == null || markInfo.GetAsBoolean(PdfName.MARKED) == null || markInfo.GetAsBoolean(PdfName.MARKED).BooleanValue == false) { throw new PdfAConformanceException(obj1, MessageLocalization.GetComposedMessage("document.catalog.dictionary.shall.include.a.markinfo.dictionary.whose.entry.marked.shall.have.a.value.of.true")); } if (!dictionary.Contains(PdfName.LANG)) { if (LOGGER.IsLogging(Level.WARN)) { LOGGER.Warn(MessageLocalization.GetComposedMessage("document.catalog.dictionary.should.contain.lang.entry")); } } } } else if (PdfName.PAGE.Equals(type)) { if (dictionary.Contains(PdfName.AA)) { throw new PdfAConformanceException(obj1, MessageLocalization.GetComposedMessage("page.dictionary.shall.not.include.aa.entry")); } } else if (PdfName.OUTPUTINTENT.Equals(type)) { isCheckOutputIntent = true; PdfObject destOutputIntent = dictionary.Get(PdfName.DESTOUTPUTPROFILE); if (destOutputIntent != null && pdfaDestOutputIntent != null) { if (pdfaDestOutputIntent.IndRef != destOutputIntent.IndRef) { throw new PdfAConformanceException(obj1, MessageLocalization.GetComposedMessage( "if.outputintents.array.more.than.one.entry.the.same.indirect.object")); } } else { pdfaDestOutputIntent = destOutputIntent; } PdfName gts = dictionary.GetAsName(PdfName.S); if (pdfaDestOutputIntent != null) { if (PdfName.GTS_PDFA1.Equals(gts)) { if (pdfaOutputIntentColorSpace != null) { throw new PdfAConformanceException(obj1, MessageLocalization.GetComposedMessage("a.pdfa.file.may.have.only.one.pdfa.outputintent")); } pdfaOutputIntentColorSpace = ""; ICC_Profile icc_profile = writer.ColorProfile; pdfaOutputIntentColorSpace = Encoding.GetEncoding("US-ASCII").GetString(icc_profile.Data, 16, 4); } } else { throw new PdfAConformanceException(obj1, MessageLocalization.GetComposedMessage("outputintent.shall.have.gtspdfa1.and.destoutputintent")); } } } }
/** * Creates new {@link LineDashPattern} object. * @param dashArray The dash array. See {@link #getDashArray()} * @param dashPhase The dash phase. See {@link #getDashPhase()} */ public LineDashPattern(PdfArray dashArray, float dashPhase) { this.dashArray = new PdfArray(dashArray); this.dashPhase = dashPhase; InitFirst(dashPhase); }
protected static Image GetTiffImageColor(TiffDirectory dir, RandomAccessFileOrArray s) { var predictor = 1; TifflzwDecoder lzwDecoder = null; var compression = (int)dir.GetFieldAsLong(TiffConstants.TIFFTAG_COMPRESSION); switch (compression) { case TiffConstants.COMPRESSION_NONE: case TiffConstants.COMPRESSION_LZW: case TiffConstants.COMPRESSION_PACKBITS: case TiffConstants.COMPRESSION_DEFLATE: case TiffConstants.COMPRESSION_ADOBE_DEFLATE: case TiffConstants.COMPRESSION_OJPEG: case TiffConstants.COMPRESSION_JPEG: break; default: throw new InvalidOperationException("The compression " + compression + " is not supported."); } var photometric = (int)dir.GetFieldAsLong(TiffConstants.TIFFTAG_PHOTOMETRIC); switch (photometric) { case TiffConstants.PHOTOMETRIC_MINISWHITE: case TiffConstants.PHOTOMETRIC_MINISBLACK: case TiffConstants.PHOTOMETRIC_RGB: case TiffConstants.PHOTOMETRIC_SEPARATED: case TiffConstants.PHOTOMETRIC_PALETTE: break; default: if (compression != TiffConstants.COMPRESSION_OJPEG && compression != TiffConstants.COMPRESSION_JPEG) { throw new InvalidOperationException("The photometric " + photometric + " is not supported."); } break; } float rotation = 0; if (dir.IsTagPresent(TiffConstants.TIFFTAG_ORIENTATION)) { var rot = (int)dir.GetFieldAsLong(TiffConstants.TIFFTAG_ORIENTATION); if (rot == TiffConstants.ORIENTATION_BOTRIGHT || rot == TiffConstants.ORIENTATION_BOTLEFT) { rotation = (float)Math.PI; } else if (rot == TiffConstants.ORIENTATION_LEFTTOP || rot == TiffConstants.ORIENTATION_LEFTBOT) { rotation = (float)(Math.PI / 2.0); } else if (rot == TiffConstants.ORIENTATION_RIGHTTOP || rot == TiffConstants.ORIENTATION_RIGHTBOT) { rotation = -(float)(Math.PI / 2.0); } } if (dir.IsTagPresent(TiffConstants.TIFFTAG_PLANARCONFIG) && dir.GetFieldAsLong(TiffConstants.TIFFTAG_PLANARCONFIG) == TiffConstants.PLANARCONFIG_SEPARATE) { throw new InvalidOperationException("Planar images are not supported."); } if (dir.IsTagPresent(TiffConstants.TIFFTAG_EXTRASAMPLES)) { throw new InvalidOperationException("Extra samples are not supported."); } var samplePerPixel = 1; if (dir.IsTagPresent(TiffConstants.TIFFTAG_SAMPLESPERPIXEL)) // 1,3,4 { samplePerPixel = (int)dir.GetFieldAsLong(TiffConstants.TIFFTAG_SAMPLESPERPIXEL); } var bitsPerSample = 1; if (dir.IsTagPresent(TiffConstants.TIFFTAG_BITSPERSAMPLE)) { bitsPerSample = (int)dir.GetFieldAsLong(TiffConstants.TIFFTAG_BITSPERSAMPLE); } switch (bitsPerSample) { case 1: case 2: case 4: case 8: break; default: throw new InvalidOperationException("Bits per sample " + bitsPerSample + " is not supported."); } Image img = null; var h = (int)dir.GetFieldAsLong(TiffConstants.TIFFTAG_IMAGELENGTH); var w = (int)dir.GetFieldAsLong(TiffConstants.TIFFTAG_IMAGEWIDTH); var dpiX = 0; var dpiY = 0; var resolutionUnit = TiffConstants.RESUNIT_INCH; if (dir.IsTagPresent(TiffConstants.TIFFTAG_RESOLUTIONUNIT)) { resolutionUnit = (int)dir.GetFieldAsLong(TiffConstants.TIFFTAG_RESOLUTIONUNIT); } dpiX = getDpi(dir.GetField(TiffConstants.TIFFTAG_XRESOLUTION), resolutionUnit); dpiY = getDpi(dir.GetField(TiffConstants.TIFFTAG_YRESOLUTION), resolutionUnit); var fillOrder = 1; var reverse = false; var fillOrderField = dir.GetField(TiffConstants.TIFFTAG_FILLORDER); if (fillOrderField != null) { fillOrder = fillOrderField.GetAsInt(0); } reverse = (fillOrder == TiffConstants.FILLORDER_LSB2MSB); var rowsStrip = h; if (dir.IsTagPresent(TiffConstants.TIFFTAG_ROWSPERSTRIP)) //another hack for broken tiffs { rowsStrip = (int)dir.GetFieldAsLong(TiffConstants.TIFFTAG_ROWSPERSTRIP); } if (rowsStrip <= 0 || rowsStrip > h) { rowsStrip = h; } var offset = getArrayLongShort(dir, TiffConstants.TIFFTAG_STRIPOFFSETS); var size = getArrayLongShort(dir, TiffConstants.TIFFTAG_STRIPBYTECOUNTS); if ((size == null || (size.Length == 1 && (size[0] == 0 || size[0] + offset[0] > s.Length))) && h == rowsStrip) { // some TIFF producers are really lousy, so... size = new long[] { s.Length - (int)offset[0] }; } if (compression == TiffConstants.COMPRESSION_LZW) { var predictorField = dir.GetField(TiffConstants.TIFFTAG_PREDICTOR); if (predictorField != null) { predictor = predictorField.GetAsInt(0); if (predictor != 1 && predictor != 2) { throw new InvalidOperationException("Illegal value for Predictor in TIFF file."); } if (predictor == 2 && bitsPerSample != 8) { throw new InvalidOperationException(bitsPerSample + "-bit samples are not supported for Horizontal differencing Predictor."); } } lzwDecoder = new TifflzwDecoder(w, predictor, samplePerPixel); } var rowsLeft = h; MemoryStream stream = null; ZDeflaterOutputStream zip = null; Ccittg4Encoder g4 = null; if (bitsPerSample == 1 && samplePerPixel == 1) { g4 = new Ccittg4Encoder(w); } else { stream = new MemoryStream(); if (compression != TiffConstants.COMPRESSION_OJPEG && compression != TiffConstants.COMPRESSION_JPEG) { zip = new ZDeflaterOutputStream(stream); } } if (compression == TiffConstants.COMPRESSION_OJPEG) { // Assume that the TIFFTAG_JPEGIFBYTECOUNT tag is optional, since it's obsolete and // is often missing if ((!dir.IsTagPresent(TiffConstants.TIFFTAG_JPEGIFOFFSET))) { throw new IOException("Missing tag(s) for OJPEG compression."); } var jpegOffset = (int)dir.GetFieldAsLong(TiffConstants.TIFFTAG_JPEGIFOFFSET); var jpegLength = s.Length - jpegOffset; if (dir.IsTagPresent(TiffConstants.TIFFTAG_JPEGIFBYTECOUNT)) { jpegLength = (int)dir.GetFieldAsLong(TiffConstants.TIFFTAG_JPEGIFBYTECOUNT) + (int)size[0]; } var jpeg = new byte[Math.Min(jpegLength, s.Length - jpegOffset)]; var posFilePointer = s.FilePointer; posFilePointer += jpegOffset; s.Seek(posFilePointer); s.ReadFully(jpeg); img = new Jpeg(jpeg); } else if (compression == TiffConstants.COMPRESSION_JPEG) { if (size.Length > 1) { throw new IOException("Compression JPEG is only supported with a single strip. This image has " + size.Length + " strips."); } var jpeg = new byte[(int)size[0]]; s.Seek(offset[0]); s.ReadFully(jpeg); img = new Jpeg(jpeg); } else { for (var k = 0; k < offset.Length; ++k) { var im = new byte[(int)size[k]]; s.Seek(offset[k]); s.ReadFully(im); var height = Math.Min(rowsStrip, rowsLeft); byte[] outBuf = null; if (compression != TiffConstants.COMPRESSION_NONE) { outBuf = new byte[(w * bitsPerSample * samplePerPixel + 7) / 8 * height]; } if (reverse) { TiffFaxDecoder.ReverseBits(im); } switch (compression) { case TiffConstants.COMPRESSION_DEFLATE: case TiffConstants.COMPRESSION_ADOBE_DEFLATE: Inflate(im, outBuf); break; case TiffConstants.COMPRESSION_NONE: outBuf = im; break; case TiffConstants.COMPRESSION_PACKBITS: DecodePackbits(im, outBuf); break; case TiffConstants.COMPRESSION_LZW: lzwDecoder.Decode(im, outBuf, height); break; } if (bitsPerSample == 1 && samplePerPixel == 1) { g4.Fax4Encode(outBuf, height); } else { zip.Write(outBuf, 0, outBuf.Length); } rowsLeft -= rowsStrip; } if (bitsPerSample == 1 && samplePerPixel == 1) { img = Image.GetInstance(w, h, false, Element.CCITTG4, photometric == TiffConstants.PHOTOMETRIC_MINISBLACK ? Element.CCITT_BLACKIS1 : 0, g4.Close()); } else { zip.Close(); img = Image.GetInstance(w, h, samplePerPixel, bitsPerSample, stream.ToArray()); img.Deflated = true; } } img.SetDpi(dpiX, dpiY); if (compression != TiffConstants.COMPRESSION_OJPEG && compression != TiffConstants.COMPRESSION_JPEG) { if (dir.IsTagPresent(TiffConstants.TIFFTAG_ICCPROFILE)) { try { var fd = dir.GetField(TiffConstants.TIFFTAG_ICCPROFILE); var iccProf = IccProfile.GetInstance(fd.GetAsBytes()); if (samplePerPixel == iccProf.NumComponents) { img.TagIcc = iccProf; } } catch { //empty } } if (dir.IsTagPresent(TiffConstants.TIFFTAG_COLORMAP)) { var fd = dir.GetField(TiffConstants.TIFFTAG_COLORMAP); var rgb = fd.GetAsChars(); var palette = new byte[rgb.Length]; var gColor = rgb.Length / 3; var bColor = gColor * 2; for (var k = 0; k < gColor; ++k) { palette[k * 3] = (byte)(rgb[k] >> 8); palette[k * 3 + 1] = (byte)(rgb[k + gColor] >> 8); palette[k * 3 + 2] = (byte)(rgb[k + bColor] >> 8); } var indexed = new PdfArray(); indexed.Add(PdfName.Indexed); indexed.Add(PdfName.Devicergb); indexed.Add(new PdfNumber(gColor - 1)); indexed.Add(new PdfString(palette)); var additional = new PdfDictionary(); additional.Put(PdfName.Colorspace, indexed); img.Additional = additional; } img.OriginalType = Image.ORIGINAL_TIFF; } if (photometric == TiffConstants.PHOTOMETRIC_MINISWHITE) { img.Inverted = true; } if (rotation.ApproxNotEqual(0)) { img.InitialRotation = rotation; } return(img); }
private static int SeparateStructure(PdfDocument document, int startPage, int beforePage, int startPageStructTopIndex ) { if (!document.IsTagged() || 1 > startPage || startPage > beforePage || beforePage > document.GetNumberOfPages () + 1) { return(-1); } else { if (beforePage == startPage) { return(startPageStructTopIndex); } else { if (beforePage == document.GetNumberOfPages() + 1) { return(document.GetStructTreeRoot().GetKidsObject().Size()); } } } // Here we separate the structure tree in two parts: struct elems that belong to the pages which indexes are // less then separateBeforePage and those struct elems that belong to other pages. Some elems might belong // to both parts and actually these are the ones that we are looking for. ICollection <PdfObject> firstPartElems = new HashSet <PdfObject>(); for (int i = startPage; i < beforePage; ++i) { PdfPage pageOfFirstHalf = document.GetPage(i); ICollection <PdfMcr> pageMcrs = document.GetStructTreeRoot().GetPageMarkedContentReferences(pageOfFirstHalf ); if (pageMcrs != null) { foreach (PdfMcr mcr in pageMcrs) { firstPartElems.Add(mcr.GetPdfObject()); PdfDictionary top = AddAllParentsToSet(mcr, firstPartElems); if (top != null && top.IsFlushed()) { throw new PdfException(PdfException.TagFromTheExistingTagStructureIsFlushedCannotAddCopiedPageTags); } } } } IList <PdfDictionary> clonedTops = new List <PdfDictionary>(); PdfArray tops = document.GetStructTreeRoot().GetKidsObject(); // Now we "walk" through all the elems which belong to the first part, and look for the ones that contain both // kids from first and second part. We clone found elements and move kids from the second part to cloned elems. int lastTopBefore = startPageStructTopIndex - 1; for (int i = 0; i < tops.Size(); ++i) { PdfDictionary top = tops.GetAsDictionary(i); if (firstPartElems.Contains(top)) { lastTopBefore = i; StructureTreeCopier.LastClonedAncestor lastCloned = new StructureTreeCopier.LastClonedAncestor(); lastCloned.ancestor = top; PdfDictionary topClone = top.Clone(ignoreKeysForClone); topClone.Put(PdfName.P, document.GetStructTreeRoot().GetPdfObject()); lastCloned.clone = topClone; SeparateKids(top, firstPartElems, lastCloned, document); if (topClone.ContainsKey(PdfName.K)) { topClone.MakeIndirect(document); clonedTops.Add(topClone); } } } for (int i = 0; i < clonedTops.Count; ++i) { document.GetStructTreeRoot().AddKidObject(lastTopBefore + 1 + i, clonedTops[i]); } return(lastTopBefore + 1); }
public CalRgb(PdfArray pdfObject) : base(pdfObject) { }
public void PdfMergeTest() { PdfDictionary CM31 = new PdfDictionary(); PdfDictionary sElem = new PdfDictionary(); //<</O/Layout/EndIndent 18.375/StartIndent 11.25/TextIndent -11.25/LineHeight 13>> //<</C/SC.7.147466/Pg 118 0 R/Type/StructElem/K 3/S/Span/Lang(en)/P 1 0 R>> CM31.Put(PdfName.O, new PdfName("Layout")); CM31.Put(new PdfName("EndIndent"), new PdfNumber(18.375)); CM31.Put(new PdfName("StartIndent"), new PdfNumber(11.25)); CM31.Put(new PdfName("TextIndent"), new PdfNumber(-11.25)); CM31.Put(new PdfName("LineHeight"), new PdfNumber(13)); sElem.Put(PdfName.C, new PdfName("SC.7.147466")); sElem.Put(PdfName.K, new PdfNumber(5)); sElem.Put(PdfName.S, PdfName.SPAN); sElem.Put(PdfName.LANG, new PdfString("en")); InitializeDocument("-merge"); int n = 4; PdfReader reader1 = new PdfReader(SOURCE11); copy.AddPage(copy.GetImportedPage(reader1, 76, true)); copy.AddPage(copy.GetImportedPage(reader1, 83, true)); reader1.Close(); PdfReader reader2 = new PdfReader(SOURCE32); copy.AddPage(copy.GetImportedPage(reader2, 69, true)); copy.AddPage(copy.GetImportedPage(reader2, 267, true)); document.Close(); reader2.Close(); PdfReader reader = new PdfReader(output); PdfDictionary structTreeRoot = VerifyIsDictionary(reader.Catalog.GetDirectObject(PdfName.STRUCTTREEROOT), NO_STRUCT_TREE_ROOT); VerifyArraySize(structTreeRoot.Get(PdfName.K), 2, "Kids in StructTreeRoot"); PdfObject obj = PdfStructTreeController.GetDirectObject(structTreeRoot.Get(PdfName.PARENTTREE)); VerifyIsDictionary(obj, NO_PARENT_TREE); PdfArray array = ((PdfDictionary)obj).GetAsArray(PdfName.NUMS); int[] nums = new int[] { 30, 32, 39, 80 }; for (int i = 0; i < n; ++i) { VerifyArraySize(PdfStructTreeController.GetDirectObject(array.GetDirectObject(i * 2 + 1)), nums[i], "Nums of page " + (i + 1)); } PdfDictionary ClassMap = VerifyIsDictionary(PdfStructTreeController.GetDirectObject(structTreeRoot.Get(PdfName.CLASSMAP)), NO_CLASS_MAP); PdfDictionary currCM31 = VerifyIsDictionary(PdfStructTreeController.GetDirectObject(ClassMap.Get(new PdfName("CM31"))), "ClassMap does not contain.\"CM31\""); if (!PdfStructTreeController.CompareObjects(CM31, currCM31)) { Assert.Fail("ClassMap contains incorrect \"CM31\""); } PdfDictionary RoleMap = VerifyIsDictionary(PdfStructTreeController.GetDirectObject(structTreeRoot.Get(PdfName.ROLEMAP)), NO_ROLE_MAP); if (!PdfName.SPAN.Equals(RoleMap.Get(new PdfName("ParagraphSpan")))) { throw new BadPdfFormatException("RoleMap does not contain \"ParagraphSpan\""); } reader.Close(); }
public IccBased(PdfArray pdfObject) : base(pdfObject) { }
public override void AfterClone( Cloner cloner, PdfArray parent, int index, PdfDirectObject item ) { PdfDictionary annotation = (PdfDictionary)item.Resolve(); if(annotation.ContainsKey(PdfName.FT)) {cloner.context.Document.Form.Fields.Add(Field.Wrap(annotation.Reference));} }
public PdfMediaBox(PdfArray box) : base(PdfObjectType.MediaBox, box) { }
public LayersLocation( PdfDirectObject parentLayerObject, PdfArray parentLayersObject, int index, Stack<Object[]> levels ) { ParentLayerObject = parentLayerObject; ParentLayersObject = parentLayersObject; Index = index; Levels = levels; }
/// <summary> /// A set of four numbers describing the numerical differences between two rectangles: /// the Rect entry of the annotation and the actual boundaries of the underlying square. /// </summary> /// <param name="rect"> /// a /// <see cref="iText.Kernel.Pdf.PdfArray"/> /// with four numbers which correspond to the differences in default user space between /// the left, top, right, and bottom coordinates of Rect and those of the inner rectangle, respectively. /// Each value shall be greater than or equal to 0. The sum of the top and bottom differences shall be /// less than the height of Rect, and the sum of the left and right differences shall be less than /// the width of Rect. /// </param> /// <returns> /// this /// <see cref="PdfSquareAnnotation"/> /// instance. /// </returns> public virtual iText.Kernel.Pdf.Annot.PdfSquareAnnotation SetRectangleDifferences(PdfArray rect) { return((iText.Kernel.Pdf.Annot.PdfSquareAnnotation)Put(PdfName.RD, rect)); }
/// <summary> /// Searches an array for references to OCGs that need to be removed. </summary> /// <param name="array"> the array </param> /// <param name="ocgs"> the removal list </param> private void RemoveOCGsFromArray(PdfArray array, ICollection<string> ocgs) { if (array == null) { return; } PdfObject o; PdfDictionary dict; IList<int?> remove = new List<int?>(); for (int i = array.Size; i > 0;) { o = array.GetDirectObject(--i); if (o.IsDictionary()) { dict = (PdfDictionary) o; if (IsToBeRemoved(dict, ocgs)) { remove.Add(i); } else { RemoveOCGsFromArray(dict, PdfName.OCGS, ocgs); } } if (o.IsArray()) { RemoveOCGsFromArray((PdfArray) o, ocgs); } } foreach (int i in remove) { array.Remove(i); } }
private void readPng() { for (var i = 0; i < Pngid.Length; i++) { if (Pngid[i] != _isp.ReadByte()) { throw new IOException("File is not a valid PNG."); } } var buffer = new byte[Transfersize]; while (true) { var len = GetInt(_isp); var marker = GetString(_isp); if (len < 0 || !checkMarker(marker)) { throw new IOException("Corrupted PNG file."); } if (IDAT.Equals(marker)) { int size; while (len != 0) { size = _isp.Read(buffer, 0, Math.Min(len, Transfersize)); if (size <= 0) { return; } _idat.Write(buffer, 0, size); len -= size; } } else if (tRNS.Equals(marker)) { switch (_colorType) { case 0: if (len >= 2) { len -= 2; var gray = GetWord(_isp); if (_bitDepth == 16) { _transRedGray = gray; } else { _additional.Put(PdfName.Mask, new PdfLiteral("[" + gray + " " + gray + "]")); } } break; case 2: if (len >= 6) { len -= 6; var red = GetWord(_isp); var green = GetWord(_isp); var blue = GetWord(_isp); if (_bitDepth == 16) { _transRedGray = red; _transGreen = green; _transBlue = blue; } else { _additional.Put(PdfName.Mask, new PdfLiteral("[" + red + " " + red + " " + green + " " + green + " " + blue + " " + blue + "]")); } } break; case 3: if (len > 0) { _trans = new byte[len]; for (var k = 0; k < len; ++k) { _trans[k] = (byte)_isp.ReadByte(); } len = 0; } break; } Utilities.Skip(_isp, len); } else if (IHDR.Equals(marker)) { _width = GetInt(_isp); _height = GetInt(_isp); _bitDepth = _isp.ReadByte(); _colorType = _isp.ReadByte(); _compressionMethod = _isp.ReadByte(); _filterMethod = _isp.ReadByte(); _interlaceMethod = _isp.ReadByte(); } else if (PLTE.Equals(marker)) { if (_colorType == 3) { var colorspace = new PdfArray(); colorspace.Add(PdfName.Indexed); colorspace.Add(getColorspace()); colorspace.Add(new PdfNumber(len / 3 - 1)); var colortable = new ByteBuffer(); while ((len--) > 0) { colortable.Append_i(_isp.ReadByte()); } colorspace.Add(new PdfString(_colorTable = colortable.ToByteArray())); _additional.Put(PdfName.Colorspace, colorspace); } else { Utilities.Skip(_isp, len); } } else if (pHYs.Equals(marker)) { var dx = GetInt(_isp); var dy = GetInt(_isp); var unit = _isp.ReadByte(); if (unit == 1) { _dpiX = (int)(dx * 0.0254f + 0.5f); _dpiY = (int)(dy * 0.0254f + 0.5f); } else { if (dy != 0) { _xyRatio = dx / (float)dy; } } } else if (cHRM.Equals(marker)) { _xW = GetInt(_isp) / 100000f; _yW = GetInt(_isp) / 100000f; _xR = GetInt(_isp) / 100000f; _yR = GetInt(_isp) / 100000f; _xG = GetInt(_isp) / 100000f; _yG = GetInt(_isp) / 100000f; _xB = GetInt(_isp) / 100000f; _yB = GetInt(_isp) / 100000f; _hasChrm = !(Math.Abs(_xW) < 0.0001f || Math.Abs(_yW) < 0.0001f || Math.Abs(_xR) < 0.0001f || Math.Abs(_yR) < 0.0001f || Math.Abs(_xG) < 0.0001f || Math.Abs(_yG) < 0.0001f || Math.Abs(_xB) < 0.0001f || Math.Abs(_yB) < 0.0001f); } else if (sRGB.Equals(marker)) { var ri = _isp.ReadByte(); _intent = _intents[ri]; _gamma = 2.2f; _xW = 0.3127f; _yW = 0.329f; _xR = 0.64f; _yR = 0.33f; _xG = 0.3f; _yG = 0.6f; _xB = 0.15f; _yB = 0.06f; _hasChrm = true; } else if (gAMA.Equals(marker)) { var gm = GetInt(_isp); if (gm != 0) { _gamma = 100000f / gm; if (!_hasChrm) { _xW = 0.3127f; _yW = 0.329f; _xR = 0.64f; _yR = 0.33f; _xG = 0.3f; _yG = 0.6f; _xB = 0.15f; _yB = 0.06f; _hasChrm = true; } } } else if (iCCP.Equals(marker)) { do { --len; } while (_isp.ReadByte() != 0); _isp.ReadByte(); --len; var icccom = new byte[len]; var p = 0; while (len > 0) { var r = _isp.Read(icccom, p, len); if (r < 0) { throw new IOException("Premature end of file."); } p += r; len -= r; } var iccp = PdfReader.FlateDecode(icccom, true); icccom = null; try { _iccProfile = IccProfile.GetInstance(iccp); } catch { _iccProfile = null; } } else if (IEND.Equals(marker)) { break; } else { Utilities.Skip(_isp, len); } Utilities.Skip(_isp, 4); } }
public PdfStructureDestination(PdfArray structureDestination) : base(structureDestination) { }
private void OutputDss(PdfDictionary dss, PdfDictionary vrim, PdfArray ocsps, PdfArray crls, PdfArray certs) { PdfDictionary catalog = reader.Catalog; stp.MarkUsed(catalog); foreach (PdfName vkey in validated.Keys) { PdfArray ocsp = new PdfArray(); PdfArray crl = new PdfArray(); PdfArray cert = new PdfArray(); PdfDictionary vri = new PdfDictionary(); foreach (byte[] b in validated[vkey].crls) { PdfStream ps = new PdfStream(b); ps.FlateCompress(); PdfIndirectReference iref = writer.AddToBody(ps, false).IndirectReference; crl.Add(iref); crls.Add(iref); } foreach (byte[] b in validated[vkey].ocsps) { PdfStream ps = new PdfStream(b); ps.FlateCompress(); PdfIndirectReference iref = writer.AddToBody(ps, false).IndirectReference; ocsp.Add(iref); ocsps.Add(iref); } foreach (byte[] b in validated[vkey].certs) { PdfStream ps = new PdfStream(b); ps.FlateCompress(); PdfIndirectReference iref = writer.AddToBody(ps, false).IndirectReference; cert.Add(iref); certs.Add(iref); } if (ocsp.Size > 0) { vri.Put(PdfName.OCSP, writer.AddToBody(ocsp, false).IndirectReference); } if (crl.Size > 0) { vri.Put(PdfName.CRL, writer.AddToBody(crl, false).IndirectReference); } if (cert.Size > 0) { vri.Put(PdfName.CERT, writer.AddToBody(cert, false).IndirectReference); } vrim.Put(vkey, writer.AddToBody(vri, false).IndirectReference); } dss.Put(PdfName.VRI, writer.AddToBody(vrim, false).IndirectReference); if (ocsps.Size > 0) { dss.Put(PdfName.OCSPS, writer.AddToBody(ocsps, false).IndirectReference); } if (crls.Size > 0) { dss.Put(PdfName.CRLS, writer.AddToBody(crls, false).IndirectReference); } if (certs.Size > 0) { dss.Put(PdfName.CERTS, writer.AddToBody(certs, false).IndirectReference); } catalog.Put(PdfName.DSS, writer.AddToBody(dss, false).IndirectReference); }
PdfObject GetColorspace() { if (icc_profile != null) { if ((colorType & 2) == 0) { return(PdfName.DEVICEGRAY); } else { return(PdfName.DEVICERGB); } } if (gamma == 1f && !hasCHRM) { if ((colorType & 2) == 0) { return(PdfName.DEVICEGRAY); } else { return(PdfName.DEVICERGB); } } else { PdfArray array = new PdfArray(); PdfDictionary dic = new PdfDictionary(); if ((colorType & 2) == 0) { if (gamma == 1f) { return(PdfName.DEVICEGRAY); } array.Add(PdfName.CALGRAY); dic.Put(PdfName.GAMMA, new PdfNumber(gamma)); dic.Put(PdfName.WHITEPOINT, new PdfLiteral("[1 1 1]")); array.Add(dic); } else { PdfObject wp = new PdfLiteral("[1 1 1]"); array.Add(PdfName.CALRGB); if (gamma != 1f) { PdfArray gm = new PdfArray(); PdfNumber n = new PdfNumber(gamma); gm.Add(n); gm.Add(n); gm.Add(n); dic.Put(PdfName.GAMMA, gm); } if (hasCHRM) { float z = yW * ((xG - xB) * yR - (xR - xB) * yG + (xR - xG) * yB); float YA = yR * ((xG - xB) * yW - (xW - xB) * yG + (xW - xG) * yB) / z; float XA = YA * xR / yR; float ZA = YA * ((1 - xR) / yR - 1); float YB = -yG * ((xR - xB) * yW - (xW - xB) * yR + (xW - xR) * yB) / z; float XB = YB * xG / yG; float ZB = YB * ((1 - xG) / yG - 1); float YC = yB * ((xR - xG) * yW - (xW - xG) * yW + (xW - xR) * yG) / z; float XC = YC * xB / yB; float ZC = YC * ((1 - xB) / yB - 1); float XW = XA + XB + XC; float YW = 1;//YA+YB+YC; float ZW = ZA + ZB + ZC; PdfArray wpa = new PdfArray(); wpa.Add(new PdfNumber(XW)); wpa.Add(new PdfNumber(YW)); wpa.Add(new PdfNumber(ZW)); wp = wpa; PdfArray matrix = new PdfArray(); matrix.Add(new PdfNumber(XA)); matrix.Add(new PdfNumber(YA)); matrix.Add(new PdfNumber(ZA)); matrix.Add(new PdfNumber(XB)); matrix.Add(new PdfNumber(YB)); matrix.Add(new PdfNumber(ZB)); matrix.Add(new PdfNumber(XC)); matrix.Add(new PdfNumber(YC)); matrix.Add(new PdfNumber(ZC)); dic.Put(PdfName.MATRIX, matrix); } dic.Put(PdfName.WHITEPOINT, wp); array.Add(dic); } return(array); } }
private static PdfDictionary CopyObject(PdfDictionary source, PdfDictionary destPage, bool parentChangePg, StructureTreeCopier.StructElemCopyingParams copyingParams) { PdfDictionary copied; if (copyingParams.IsCopyFromDestDocument()) { //TODO: detect wether object is needed to be cloned at all copied = source.Clone(ignoreKeysForClone); if (source.IsIndirect()) { copied.MakeIndirect(copyingParams.GetToDocument()); } PdfDictionary pg = source.GetAsDictionary(PdfName.Pg); if (pg != null) { if (copyingParams.IsCopyFromDestDocument()) { if (pg != destPage) { copied.Put(PdfName.Pg, destPage); parentChangePg = true; } else { parentChangePg = false; } } } } else { copied = source.CopyTo(copyingParams.GetToDocument(), ignoreKeysForCopy, true); PdfDictionary obj = source.GetAsDictionary(PdfName.Obj); if (obj != null) { // Link annotations could be not added to the toDocument, so we need to identify this case. // When obj.copyTo is called, and annotation was already copied, we would get this already created copy. // If it was already copied and added, /P key would be set. Otherwise /P won't be set. obj = obj.CopyTo(copyingParams.GetToDocument(), iText.IO.Util.JavaUtil.ArraysAsList(PdfName.P), false); copied.Put(PdfName.Obj, obj); } PdfDictionary nsDict = source.GetAsDictionary(PdfName.NS); if (nsDict != null) { PdfDictionary copiedNsDict = CopyNamespaceDict(nsDict, copyingParams); copied.Put(PdfName.NS, copiedNsDict); } PdfDictionary pg = source.GetAsDictionary(PdfName.Pg); if (pg != null) { PdfDictionary pageAnalog = copyingParams.GetPage2page().Get(pg); if (pageAnalog == null) { pageAnalog = destPage; parentChangePg = true; } else { parentChangePg = false; } copied.Put(PdfName.Pg, pageAnalog); } } PdfObject k = source.Get(PdfName.K); if (k != null) { if (k.IsArray()) { PdfArray kArr = (PdfArray)k; PdfArray newArr = new PdfArray(); for (int i = 0; i < kArr.Size(); i++) { PdfObject copiedKid = CopyObjectKid(kArr.Get(i), copied, destPage, parentChangePg, copyingParams); if (copiedKid != null) { newArr.Add(copiedKid); } } if (!newArr.IsEmpty()) { if (newArr.Size() == 1) { copied.Put(PdfName.K, newArr.Get(0)); } else { copied.Put(PdfName.K, newArr); } } } else { PdfObject copiedKid = CopyObjectKid(k, copied, destPage, parentChangePg, copyingParams); if (copiedKid != null) { copied.Put(PdfName.K, copiedKid); } } } return(copied); }
public void CopyTaggedPdf0() { InitializeDocument("0"); PdfReader reader = new PdfReader(SOURCE11); int n = reader.NumberOfPages; for (int i = 1; i <= n; ++i) { copy.AddPage(copy.GetImportedPage(reader, i, true)); } document.Close(); reader.Close(); reader = new PdfReader(output); PdfDictionary structTreeRoot = VerifyIsDictionary(reader.Catalog.GetDirectObject(PdfName.STRUCTTREEROOT), NO_STRUCT_TREE_ROOT); VerifyArraySize(structTreeRoot.Get(PdfName.K), 5, "Invalid count of kids in StructTreeRoot"); PdfObject obj = PdfStructTreeController.GetDirectObject(structTreeRoot.Get(PdfName.PARENTTREE)); VerifyIsDictionary(obj, NO_PARENT_TREE); obj = ((PdfDictionary)obj).Get(PdfName.KIDS); VerifyArraySize(obj, 3, "Invalid nums."); PdfObject numsDict = PdfStructTreeController.GetDirectObject(((PdfArray)obj).GetDirectObject(0)); VerifyIsDictionary(numsDict, "nums1"); PdfArray[] arrays = new PdfArray[3]; arrays[0] = VerifyArraySize(((PdfDictionary)numsDict).Get(PdfName.NUMS), 128, "nums 1"); numsDict = PdfStructTreeController.GetDirectObject(((PdfArray)obj).GetDirectObject(1)); VerifyIsDictionary(numsDict, "nums2"); arrays[1] = VerifyArraySize(((PdfDictionary)numsDict).Get(PdfName.NUMS), 128, "nums 2"); numsDict = PdfStructTreeController.GetDirectObject(((PdfArray)obj).GetDirectObject(2)); VerifyIsDictionary(numsDict, "nums3"); arrays[2] = VerifyArraySize(((PdfDictionary)numsDict).Get(PdfName.NUMS), 4, "nums 3"); int[] nums = new int[] { 3, 91, 42, 19, 15, 15, 9, 13, 15, 17, 18, 5, 17, 37, 24, 19, 15, 23, 8, 11, 17, 11, 13, 29, 18, 12, 11, 9, 14, 26, 17, 22, 30, 15, 21, 28, 22, 24, 22, 20, 21, 17, 24, 25, 20, 14, 32, 25, 14, 15, 24, 20, 22, 24, 21, 22, 18, 12, 23, 29, 19, 22, 21, 27, 25, 19, 6, 14, 18, 21, 25, 11, 26, 15, 15, 30, 23, 32, 17, 22, 18, 18, 32, 18, 16, 21, 28, 28, 10, 18, 13, 23, 17, 19, 24, 29, 25, 34, 26, 24, 28, 27, 21, 23, 23, 23, 10, 10, 10, 9, 16, 20, 16, 16, 22, 27, 14, 3, 11, 30, 11, 29, 6, 99, 117, 128, 92, 67, 132, 108 }; //OutputStreamWriter writer = new FileWriter(OUT0+".txt"); int k = 0; for (int i = 0; i < arrays.Length; ++i) { for (int j = 0; j < arrays[i].Size / 2; ++j) { VerifyArraySize(PdfStructTreeController.GetDirectObject(arrays[i].GetDirectObject(j * 2 + 1)), nums[k++], "Nums of page " + (i + 1)); } } //writer.write(((PdfArray)(PdfStructTreeController.GetDirectObject(arrays[i].GetDirectObject(j*2+1)))).size()+", "); //writer.Close(); PdfDictionary ClassMap = VerifyIsDictionary(PdfStructTreeController.GetDirectObject(structTreeRoot.Get(PdfName.CLASSMAP)), NO_CLASS_MAP); if (ClassMap.Size != 109) { Assert.Fail("ClassMap incorrect"); } String[] CMs = new String[] { "CM84", "CM81", "CM80", "CM87", "CM88", "CM9", "CM94", "CM95", "CM96", "CM97", "CM90", "CM91", "CM92", "CM93", "CM98", "CM99", "CM16", "CM17", "CM14", "CM15", "CM12", "CM13", "CM10", "CM19", "CM20", "CM21", "CM22", "CM23", "CM24", "CM25", "CM26", "CM27", "CM28", "CM29", "CM100", "CM101", "CM102", "CM103", "CM105", "CM106", "CM30", "CM31", "CM34", "CM35", "CM32", "CM33", "CM38", "CM39", "CM36", "CM118", "CM117", "CM49", "CM48", "CM116", "CM115", "CM47", "CM114", "CM46", "CM113", "CM45", "CM112", "CM44", "CM43", "CM111", "CM42", "CM110", "CM41", "CM108", "CM109", "CM127", "CM126", "CM58", "CM129", "CM128", "CM55", "CM123", "CM54", "CM125", "CM57", "CM56", "CM51", "CM50", "CM53", "CM120", "CM52", "CM119", "CM68", "CM136", "CM135", "CM67", "CM133", "CM139", "CM60", "CM132", "CM64", "CM63", "CM62", "CM61", "CM145", "CM76", "CM78", "CM1", "CM2", "CM71", "CM70", "CM73", "CM141", "CM72", "CM74" }; for (int i = 0; i < CMs.Length; ++i) { VerifyIsDictionary(PdfStructTreeController.GetDirectObject(ClassMap.Get(new PdfName(CMs[i]))), "ClassMap does not contain \"" + CMs[i] + "\""); } PdfDictionary RoleMap = VerifyIsDictionary(PdfStructTreeController.GetDirectObject(structTreeRoot.Get(PdfName.ROLEMAP)), NO_ROLE_MAP); if (!PdfName.SPAN.Equals(RoleMap.Get(new PdfName("ParagraphSpan")))) { throw new BadPdfFormatException("RoleMap does not contain \"ParagraphSpan\"."); } //if (reader.eofPos != 3378440L) Assert.Fail("Invalid size of pdf."); reader.Close(); CompareResults("0"); }
/** <summary>Notifies a starting clone operation on an array item.</summary> <param name="cloner">Object cloner.</param> <param name="parent">Parent clone object.</param> <param name="index">Item index within the parent.</param> <param name="item">Source item.</param> <returns>Whether the clone operation can be fulfilled.</returns> */ public virtual bool BeforeClone( Cloner cloner, PdfArray parent, int index, PdfDirectObject item ) { return true; }
private static void SeparateKids(PdfDictionary structElem, ICollection <PdfObject> firstPartElems, StructureTreeCopier.LastClonedAncestor lastCloned, PdfDocument document) { PdfObject k = structElem.Get(PdfName.K); // If /K entry is not a PdfArray - it would be a kid which we won't clone at the moment, because it won't contain // kids from both parts at the same time. It would either be cloned as an ancestor later, or not cloned at all. // If it's kid is struct elem - it would definitely be structElem from the first part, so we simply call separateKids for it. if (!k.IsArray()) { if (k.IsDictionary() && PdfStructElem.IsStructElem((PdfDictionary)k)) { SeparateKids((PdfDictionary)k, firstPartElems, lastCloned, document); } } else { PdfArray kids = (PdfArray)k; for (int i = 0; i < kids.Size(); ++i) { PdfObject kid = kids.Get(i); PdfDictionary dictKid = null; if (kid.IsDictionary()) { dictKid = (PdfDictionary)kid; } if (dictKid != null && PdfStructElem.IsStructElem(dictKid)) { if (firstPartElems.Contains(kid)) { SeparateKids((PdfDictionary)kid, firstPartElems, lastCloned, document); } else { if (dictKid.IsFlushed()) { throw new PdfException(PdfException.TagFromTheExistingTagStructureIsFlushedCannotAddCopiedPageTags); } // elems with no kids will not be marked as from the first part, // but nonetheless we don't want to move all of them to the second part; we just leave them as is if (dictKid.ContainsKey(PdfName.K)) { CloneParents(structElem, lastCloned, document); kids.Remove(i--); PdfStructElem.AddKidObject(lastCloned.clone, -1, kid); } } } else { if (!firstPartElems.Contains(kid)) { CloneParents(structElem, lastCloned, document); PdfMcr mcr; if (dictKid != null) { if (dictKid.Get(PdfName.Type).Equals(PdfName.MCR)) { mcr = new PdfMcrDictionary(dictKid, new PdfStructElem(lastCloned.clone)); } else { mcr = new PdfObjRef(dictKid, new PdfStructElem(lastCloned.clone)); } } else { mcr = new PdfMcrNumber((PdfNumber)kid, new PdfStructElem(lastCloned.clone)); } kids.Remove(i--); PdfStructElem.AddKidObject(lastCloned.clone, -1, kid); document.GetStructTreeRoot().GetParentTreeHandler().RegisterMcr(mcr); } } } } // re-register mcr if (lastCloned.ancestor == structElem) { lastCloned.ancestor = lastCloned.ancestor.GetAsDictionary(PdfName.P); lastCloned.clone = lastCloned.clone.GetAsDictionary(PdfName.P); } }
/** * If the child of a structured element is an array, we need to loop over * the elements. * * @param k * the child array to inspect */ virtual public void InspectChildArray(PdfArray k) { if (k == null) return; for (int i = 0; i < k.Size; i++) { InspectChild(k.GetDirectObject(i)); } }
public PdfExplicitDestination(PdfArray pdfObject) : base(pdfObject) { }
PdfAcroFieldCollection(PdfArray array) : base(array) { }
public override PdfObject GetDestinationPage(IDictionary <String, PdfObject> names) { PdfArray array = (PdfArray)names.Get(((PdfString)GetPdfObject()).ToUnicodeString()); return(array != null?array.Get(0) : null); }
public void SetMatrix(float a, float b, float c, float d, float e, float f) { matrix = new PdfArray(); matrix.Add(new PdfNumber(a)); matrix.Add(new PdfNumber(b)); matrix.Add(new PdfNumber(c)); matrix.Add(new PdfNumber(d)); matrix.Add(new PdfNumber(e)); matrix.Add(new PdfNumber(f)); }
void ReadPng() { for (int i = 0; i < PNGID.Length; i++) { if (PNGID[i] != isp.ReadByte()) { throw new IOException("File is not a valid PNG."); } } byte[] buffer = new byte[TRANSFERSIZE]; while (true) { int len = GetInt(isp); String marker = GetString(isp); if (len < 0 || !CheckMarker(marker)) { throw new IOException("Corrupted PNG file."); } if (IDAT.Equals(marker)) { int size; while (len != 0) { size = isp.Read(buffer, 0, Math.Min(len, TRANSFERSIZE)); if (size <= 0) { return; } idat.Write(buffer, 0, size); len -= size; } } else if (tRNS.Equals(marker)) { switch (colorType) { case 0: if (len >= 2) { len -= 2; int gray = GetWord(isp); if (bitDepth == 16) { transRedGray = gray; } else { additional.Put(PdfName.MASK, new PdfLiteral("[" + gray + " " + gray + "]")); } } break; case 2: if (len >= 6) { len -= 6; int red = GetWord(isp); int green = GetWord(isp); int blue = GetWord(isp); if (bitDepth == 16) { transRedGray = red; transGreen = green; transBlue = blue; } else { additional.Put(PdfName.MASK, new PdfLiteral("[" + red + " " + red + " " + green + " " + green + " " + blue + " " + blue + "]")); } } break; case 3: if (len > 0) { trans = new byte[len]; for (int k = 0; k < len; ++k) { trans[k] = (byte)isp.ReadByte(); } len = 0; } break; } Utilities.Skip(isp, len); } else if (IHDR.Equals(marker)) { width = GetInt(isp); height = GetInt(isp); bitDepth = isp.ReadByte(); colorType = isp.ReadByte(); compressionMethod = isp.ReadByte(); filterMethod = isp.ReadByte(); interlaceMethod = isp.ReadByte(); } else if (PLTE.Equals(marker)) { if (colorType == 3) { PdfArray colorspace = new PdfArray(); colorspace.Add(PdfName.INDEXED); colorspace.Add(GetColorspace()); colorspace.Add(new PdfNumber(len / 3 - 1)); ByteBuffer colortable = new ByteBuffer(); while ((len--) > 0) { colortable.Append_i(isp.ReadByte()); } colorspace.Add(new PdfString(colorTable = colortable.ToByteArray())); additional.Put(PdfName.COLORSPACE, colorspace); } else { Utilities.Skip(isp, len); } } else if (pHYs.Equals(marker)) { int dx = GetInt(isp); int dy = GetInt(isp); int unit = isp.ReadByte(); if (unit == 1) { dpiX = (int)((float)dx * 0.0254f + 0.5f); dpiY = (int)((float)dy * 0.0254f + 0.5f); } else { if (dy != 0) { XYRatio = (float)dx / (float)dy; } } } else if (cHRM.Equals(marker)) { xW = (float)GetInt(isp) / 100000f; yW = (float)GetInt(isp) / 100000f; xR = (float)GetInt(isp) / 100000f; yR = (float)GetInt(isp) / 100000f; xG = (float)GetInt(isp) / 100000f; yG = (float)GetInt(isp) / 100000f; xB = (float)GetInt(isp) / 100000f; yB = (float)GetInt(isp) / 100000f; hasCHRM = !(Math.Abs(xW) < 0.0001f || Math.Abs(yW) < 0.0001f || Math.Abs(xR) < 0.0001f || Math.Abs(yR) < 0.0001f || Math.Abs(xG) < 0.0001f || Math.Abs(yG) < 0.0001f || Math.Abs(xB) < 0.0001f || Math.Abs(yB) < 0.0001f); } else if (sRGB.Equals(marker)) { int ri = isp.ReadByte(); intent = intents[ri]; gamma = 2.2f; xW = 0.3127f; yW = 0.329f; xR = 0.64f; yR = 0.33f; xG = 0.3f; yG = 0.6f; xB = 0.15f; yB = 0.06f; hasCHRM = true; } else if (gAMA.Equals(marker)) { int gm = GetInt(isp); if (gm != 0) { gamma = 100000f / (float)gm; if (!hasCHRM) { xW = 0.3127f; yW = 0.329f; xR = 0.64f; yR = 0.33f; xG = 0.3f; yG = 0.6f; xB = 0.15f; yB = 0.06f; hasCHRM = true; } } } else if (iCCP.Equals(marker)) { do { --len; } while (isp.ReadByte() != 0); isp.ReadByte(); --len; byte[] icccom = new byte[len]; int p = 0; while (len > 0) { int r = isp.Read(icccom, p, len); if (r < 0) { throw new IOException("Premature end of file."); } p += r; len -= r; } byte[] iccp = PdfReader.FlateDecode(icccom, true); icccom = null; try { icc_profile = ICC_Profile.GetInstance(iccp); } catch { icc_profile = null; } } else if (IEND.Equals(marker)) { break; } else { Utilities.Skip(isp, len); } Utilities.Skip(isp, 4); } }
/// <summary> /// Creates and sets two identical new document IDs. /// </summary> internal PdfArray CreateNewDocumentIDs() { PdfArray array = new PdfArray(this.document); string id = PdfEncoders.RawEncoding.GetString(Guid.NewGuid().ToByteArray()); array.Elements.Add(new PdfString(id, PdfStringFlags.HexLiteral)); array.Elements.Add(new PdfString(id, PdfStringFlags.HexLiteral)); Elements[Keys.ID] = array; return array; }
public CalGray(PdfArray pdfObject) : base(pdfObject) { }
private Image IndexedModel(byte[] bdata, int bpc, int paletteEntries) { Image img = new ImgRaw(width, height, 1, bpc, bdata); PdfArray colorspace = new PdfArray(); colorspace.Add(PdfName.INDEXED); colorspace.Add(PdfName.DEVICERGB); byte[] np = GetPalette(paletteEntries); int len = np.Length; colorspace.Add(new PdfNumber(len / 3 - 1)); colorspace.Add(new PdfString(np)); PdfDictionary ad = new PdfDictionary(); ad.Put(PdfName.COLORSPACE, colorspace); img.Additional = ad; return img; }
/** Creates a FieldLock instance */ public FieldLock(PdfName action, PdfArray fields) { this.action = action; this.fields = fields; }
private static void DeleteOldReferences(PdfArray all, PdfArray toDelete) { if (all == null || toDelete == null) return; foreach (PdfObject pi in toDelete) { if (!pi.IsIndirect()) continue; PRIndirectReference pir = (PRIndirectReference)pi; for (int k = 0; k < all.Size; ++k) { PdfObject po = all[k]; if (!po.IsIndirect()) continue; PRIndirectReference pod = (PRIndirectReference)po; if (pir.Number == pod.Number) { all.Remove(k); --k; } } } }
private void OutputDss(PdfDictionary dss, PdfDictionary vrim, PdfArray ocsps, PdfArray crls, PdfArray certs) { writer.AddDeveloperExtension(PdfDeveloperExtension.ESIC_1_7_EXTENSIONLEVEL5); PdfDictionary catalog = reader.Catalog; stp.MarkUsed(catalog); foreach (PdfName vkey in validated.Keys) { PdfArray ocsp = new PdfArray(); PdfArray crl = new PdfArray(); PdfArray cert = new PdfArray(); PdfDictionary vri = new PdfDictionary(); foreach (byte[] b in validated[vkey].crls) { PdfStream ps = new PdfStream(b); ps.FlateCompress(); PdfIndirectReference iref = writer.AddToBody(ps, false).IndirectReference; crl.Add(iref); crls.Add(iref); } foreach (byte[] b in validated[vkey].ocsps) { PdfStream ps = new PdfStream(b); ps.FlateCompress(); PdfIndirectReference iref = writer.AddToBody(ps, false).IndirectReference; ocsp.Add(iref); ocsps.Add(iref); } foreach (byte[] b in validated[vkey].certs) { PdfStream ps = new PdfStream(b); ps.FlateCompress(); PdfIndirectReference iref = writer.AddToBody(ps, false).IndirectReference; cert.Add(iref); certs.Add(iref); } if (ocsp.Size > 0) vri.Put(PdfName.OCSP, writer.AddToBody(ocsp, false).IndirectReference); if (crl.Size > 0) vri.Put(PdfName.CRL, writer.AddToBody(crl, false).IndirectReference); if (cert.Size > 0) vri.Put(PdfName.CERT, writer.AddToBody(cert, false).IndirectReference); vrim.Put(vkey, writer.AddToBody(vri, false).IndirectReference); } dss.Put(PdfName.VRI, writer.AddToBody(vrim, false).IndirectReference); if (ocsps.Size > 0) dss.Put(PdfName.OCSPS, writer.AddToBody(ocsps, false).IndirectReference); if (crls.Size > 0) dss.Put(PdfName.CRLS, writer.AddToBody(crls, false).IndirectReference); if (certs.Size > 0) dss.Put(PdfName.CERTS, writer.AddToBody(certs, false).IndirectReference); catalog.Put(PdfName.DSS, writer.AddToBody(dss, false).IndirectReference); }
/** <summary>Parses the current PDF object [PDF:1.6:3.2].</summary> */ public virtual PdfDataObject ParsePdfObject( ) { switch(TokenType) { case TokenTypeEnum.Integer: return PdfInteger.Get((int)Token); case TokenTypeEnum.Name: return new PdfName((string)Token,true); case TokenTypeEnum.DictionaryBegin: { PdfDictionary dictionary = new PdfDictionary(); dictionary.Updateable = false; while(true) { // Key. MoveNext(); if(TokenType == TokenTypeEnum.DictionaryEnd) break; PdfName key = (PdfName)ParsePdfObject(); // Value. MoveNext(); PdfDirectObject value = (PdfDirectObject)ParsePdfObject(); // Add the current entry to the dictionary! dictionary[key] = value; } dictionary.Updateable = true; return dictionary; } case TokenTypeEnum.ArrayBegin: { PdfArray array = new PdfArray(); array.Updateable = false; while(true) { // Value. MoveNext(); if(TokenType == TokenTypeEnum.ArrayEnd) break; // Add the current item to the array! array.Add((PdfDirectObject)ParsePdfObject()); } array.Updateable = true; return array; } case TokenTypeEnum.Literal: if(Token is DateTime) return PdfDate.Get((DateTime)Token); else return new PdfTextString( Encoding.Pdf.Encode((string)Token) ); case TokenTypeEnum.Hex: return new PdfTextString( (string)Token, PdfString.SerializationModeEnum.Hex ); case TokenTypeEnum.Real: return PdfReal.Get((double)Token); case TokenTypeEnum.Boolean: return PdfBoolean.Get((bool)Token); case TokenTypeEnum.Null: return null; default: throw new Exception("Unknown type: " + TokenType); } }
private void UpdateDss() { PdfDictionary catalog = reader.Catalog; stp.MarkUsed(catalog); PdfDictionary dss = catalog.GetAsDict(PdfName.DSS); PdfArray ocsps = dss.GetAsArray(PdfName.OCSPS); PdfArray crls = dss.GetAsArray(PdfName.CRLS); PdfArray certs = dss.GetAsArray(PdfName.CERTS); dss.Remove(PdfName.OCSPS); dss.Remove(PdfName.CRLS); dss.Remove(PdfName.CERTS); PdfDictionary vrim = dss.GetAsDict(PdfName.VRI); //delete old validations if (vrim != null) { foreach (PdfName n in vrim.Keys) { if (validated.ContainsKey(n)) { PdfDictionary vri = vrim.GetAsDict(n); if (vri != null) { DeleteOldReferences(ocsps, vri.GetAsArray(PdfName.OCSP)); DeleteOldReferences(crls, vri.GetAsArray(PdfName.CRL)); DeleteOldReferences(certs, vri.GetAsArray(PdfName.CERT)); } } } } if (ocsps == null) ocsps = new PdfArray(); if (crls == null) crls = new PdfArray(); if (certs == null) certs = new PdfArray(); OutputDss(dss, vrim, ocsps, crls, certs); }
public PdfType0Font(PdfDocument document, XFont font, bool vertical) : base(document) { Elements.SetName(Keys.Type, "/Font"); Elements.SetName(Keys.Subtype, "/Type0"); Elements.SetName(Keys.Encoding, vertical ? "/Identity-V" : "/Identity-H"); OpenTypeDescriptor ttDescriptor = (OpenTypeDescriptor)FontDescriptorStock.Global.CreateDescriptor(font); this.fontDescriptor = new PdfFontDescriptor(document, ttDescriptor); this.fontOptions = font.PdfOptions; Debug.Assert(this.fontOptions != null); this.cmapInfo = new CMapInfo(ttDescriptor); this.descendantFont = new PdfCIDFont(document, this.fontDescriptor, font); this.descendantFont.CMapInfo = this.cmapInfo; // Create ToUnicode map this.toUnicode = new PdfToUnicodeMap(document, this.cmapInfo); document.Internals.AddObject(toUnicode); Elements.Add(Keys.ToUnicode, toUnicode); //if (this.fontOptions.BaseFont != "") //{ // BaseFont = this.fontOptions.BaseFont; //} //else { BaseFont = font.Name.Replace(" ", ""); switch (font.Style & (XFontStyle.Bold | XFontStyle.Italic)) { case XFontStyle.Bold: this.BaseFont += ",Bold"; break; case XFontStyle.Italic: this.BaseFont += ",Italic"; break; case XFontStyle.Bold | XFontStyle.Italic: this.BaseFont += ",BoldItalic"; break; } } // CID fonts are always embedded BaseFont = PdfFont.CreateEmbeddedFontSubsetName(BaseFont); this.fontDescriptor.FontName = BaseFont; this.descendantFont.BaseFont = BaseFont; PdfArray descendantFonts = new PdfArray(document); Owner.irefTable.Add(descendantFont); descendantFonts.Elements.Add(descendantFont.Reference); Elements[Keys.DescendantFonts] = descendantFonts; }
public PdfType0Font(PdfDocument document, string idName, byte[] fontData, bool vertical) : base(document) { Elements.SetName(Keys.Type, "/Font"); Elements.SetName(Keys.Subtype, "/Type0"); Elements.SetName(Keys.Encoding, vertical ? "/Identity-V" : "/Identity-H"); OpenTypeDescriptor ttDescriptor = (OpenTypeDescriptor)FontDescriptorStock.Global.CreateDescriptor(idName, fontData); this.fontDescriptor = new PdfFontDescriptor(document, ttDescriptor); this.fontOptions = new XPdfFontOptions(PdfFontEncoding.Unicode, PdfFontEmbedding.Always); Debug.Assert(this.fontOptions != null); this.cmapInfo = new CMapInfo(ttDescriptor); this.descendantFont = new PdfCIDFont(document, this.fontDescriptor, fontData); this.descendantFont.CMapInfo = this.cmapInfo; // Create ToUnicode map this.toUnicode = new PdfToUnicodeMap(document, this.cmapInfo); document.Internals.AddObject(toUnicode); Elements.Add(Keys.ToUnicode, toUnicode); BaseFont = ttDescriptor.FontName.Replace(" ", ""); //switch (font.Style & (XFontStyle.Bold | XFontStyle.Italic)) //{ // case XFontStyle.Bold: // this.BaseFont += ",Bold"; // break; // case XFontStyle.Italic: // this.BaseFont += ",Italic"; // break; // case XFontStyle.Bold | XFontStyle.Italic: // this.BaseFont += ",BoldItalic"; // break; //} // CID fonts are always embedded if (!BaseFont.Contains("+")) // HACK in PdfType0Font BaseFont = PdfFont.CreateEmbeddedFontSubsetName(BaseFont); this.fontDescriptor.FontName = BaseFont; this.descendantFont.BaseFont = BaseFont; PdfArray descendantFonts = new PdfArray(document); Owner.irefTable.Add(descendantFont); descendantFonts.Elements.Add(descendantFont.Reference); Elements[Keys.DescendantFonts] = descendantFonts; }
/** <summary>Gets the color corresponding to the specified components.</summary> <param name="components">Color components to convert.</param> */ public static SeparationColor Get( PdfArray components ) { return (components != null ? new SeparationColor(components) : Default ); }
internal PdfAnnotations(PdfArray array) : base(array) { }
public PdfType0Font(PdfDocument document, XFont font, bool vertical) : base(document) { Elements.SetName(Keys.Type, "/Font"); Elements.SetName(Keys.Subtype, "/Type0"); Elements.SetName(Keys.Encoding, vertical ? "/Identity-V" : "/Identity-H"); OpenTypeDescriptor ttDescriptor = (OpenTypeDescriptor)FontDescriptorCache.GetOrCreateDescriptorFor(font); FontDescriptor = new PdfFontDescriptor(document, ttDescriptor); _fontOptions = font.PdfOptions; Debug.Assert(_fontOptions != null); _cmapInfo = new CMapInfo(ttDescriptor); _descendantFont = new PdfCIDFont(document, FontDescriptor, font); _descendantFont.CMapInfo = _cmapInfo; // Create ToUnicode map _toUnicode = new PdfToUnicodeMap(document, _cmapInfo); document.Internals.AddObject(_toUnicode); Elements.Add(Keys.ToUnicode, _toUnicode); BaseFont = font.GlyphTypeface.GetBaseName(); // CID fonts are always embedded BaseFont = PdfFont.CreateEmbeddedFontSubsetName(BaseFont); FontDescriptor.FontName = BaseFont; _descendantFont.BaseFont = BaseFont; PdfArray descendantFonts = new PdfArray(document); Owner._irefTable.Add(_descendantFont); descendantFonts.Elements.Add(_descendantFont.Reference); Elements[Keys.DescendantFonts] = descendantFonts; }