private void ThrowReadOnlyError() { throw new InvalidOperationException(MessageLocalization.GetComposedMessage("rectanglereadonly.this.rectangle.is.read.only")); }
/** * Always throws an exception since PDF/X conformance level cannot be set for PDF/A conformant documents. * @param pdfx */ virtual public void SetPDFXConformance(int pdfx) { throw new PdfXConformanceException( MessageLocalization.GetComposedMessage("pdfx.conformance.cannot.be.set.for.PdfAWriter.instance")); }
/** * Does the actual parsing. Perform this immediately * after creating the parser object. */ private void Go(TextReader reader) { doc.StartDocument(); while (true) { // read a new character if (previousCharacter == -1) { character = reader.Read(); } // or re-examin the previous character else { character = previousCharacter; previousCharacter = -1; } // the end of the file was reached if (character == -1) { if (html) { if (html && state == TEXT) { Flush(); } doc.EndDocument(); } else { ThrowException(MessageLocalization.GetComposedMessage("missing.end.tag")); } return; } // dealing with \n and \r if (character == '\n' && eol) { eol = false; continue; } else if (eol) { eol = false; } else if (character == '\n') { lines++; columns = 0; } else if (character == '\r') { eol = true; character = '\n'; lines++; columns = 0; } else { columns++; } switch (state) { // we are in an unknown state before there's actual content case UNKNOWN: if (character == '<') { SaveState(TEXT); state = TAG_ENCOUNTERED; } break; // we can encounter any content case TEXT: if (character == '<') { Flush(); SaveState(state); state = TAG_ENCOUNTERED; } else if (character == '&') { SaveState(state); entity.Length = 0; state = ENTITY; nowhite = true; } else if (character == ' ') { if (html && nowhite) { text.Append(' '); nowhite = false; } else { if (nowhite) { text.Append((char)character); } nowhite = false; } } else if (Char.IsWhiteSpace((char)character)) { if (html) { // totally ignore other whitespace } else { if (nowhite) { text.Append((char)character); } nowhite = false; } } else { text.Append((char)character); nowhite = true; } break; // we have just seen a < and are wondering what we are looking at // <foo>, </foo>, <!-- ... --->, etc. case TAG_ENCOUNTERED: InitTag(); if (character == '/') { state = IN_CLOSETAG; } else if (character == '?') { RestoreState(); state = PI; } else { text.Append((char)character); state = EXAMIN_TAG; } break; // we are processing something like this <foo ... >. // It could still be a <!-- ... --> or something. case EXAMIN_TAG: if (character == '>') { DoTag(); ProcessTag(true); InitTag(); state = RestoreState(); } else if (character == '/') { state = SINGLE_TAG; } else if (character == '-' && text.ToString().Equals("!-")) { Flush(); state = COMMENT; } else if (character == '[' && text.ToString().Equals("![CDATA")) { Flush(); state = CDATA; } else if (character == 'E' && text.ToString().Equals("!DOCTYP")) { Flush(); state = PI; } else if (char.IsWhiteSpace((char)character)) { DoTag(); state = TAG_EXAMINED; } else { text.Append((char)character); } break; // we know the name of the tag now. case TAG_EXAMINED: if (character == '>') { ProcessTag(true); InitTag(); state = RestoreState(); } else if (character == '/') { state = SINGLE_TAG; } else if (char.IsWhiteSpace((char)character)) { // empty } else { text.Append((char)character); state = ATTRIBUTE_KEY; } break; // we are processing a closing tag: e.g. </foo> case IN_CLOSETAG: if (character == '>') { DoTag(); ProcessTag(false); if (!html && nested == 0) { return; } state = RestoreState(); } else { if (!char.IsWhiteSpace((char)character)) { text.Append((char)character); } } break; // we have just seen something like this: <foo a="b"/ // and are looking for the final >. case SINGLE_TAG: if (character != '>') { ThrowException(MessageLocalization.GetComposedMessage("expected.gt.for.tag.lt.1.gt", tag)); } DoTag(); ProcessTag(true); ProcessTag(false); InitTag(); if (!html && nested == 0) { doc.EndDocument(); return; } state = RestoreState(); break; // we are processing CDATA case CDATA: if (character == '>' && text.ToString().EndsWith("]]")) { text.Length = text.Length - 2; Flush(); state = RestoreState(); } else { text.Append((char)character); } break; // we are processing a comment. We are inside // the <!-- .... --> looking for the -->. case COMMENT: if (character == '>' && text.ToString().EndsWith("--")) { text.Length = text.Length - 2; Flush(); state = RestoreState(); } else { text.Append((char)character); } break; // We are inside one of these <? ... ?> or one of these <!DOCTYPE ... > case PI: if (character == '>') { state = RestoreState(); if (state == TEXT) { state = UNKNOWN; } } break; // we are processing an entity, e.g. <, », etc. case ENTITY: if (character == ';') { state = RestoreState(); String cent = entity.ToString(); entity.Length = 0; char ce = EntitiesToUnicode.DecodeEntity(cent); if (ce == '\0') { text.Append('&').Append(cent).Append(';'); } else { text.Append(ce); } } else if ((character != '#' && (character < '0' || character > '9') && (character < 'a' || character > 'z') && (character < 'A' || character > 'Z')) || entity.Length >= 7) { state = RestoreState(); previousCharacter = character; text.Append('&').Append(entity.ToString()); entity.Length = 0; } else { entity.Append((char)character); } break; // We are processing the quoted right-hand side of an element's attribute. case QUOTE: if (html && quoteCharacter == ' ' && character == '>') { Flush(); ProcessTag(true); InitTag(); state = RestoreState(); } else if (html && quoteCharacter == ' ' && char.IsWhiteSpace((char)character)) { Flush(); state = TAG_EXAMINED; } else if (html && quoteCharacter == ' ') { text.Append((char)character); } else if (character == quoteCharacter) { Flush(); state = TAG_EXAMINED; } else if (" \r\n\u0009".IndexOf((char)character) >= 0) { text.Append(' '); } else if (character == '&') { SaveState(state); state = ENTITY; entity.Length = 0; } else { text.Append((char)character); } break; case ATTRIBUTE_KEY: if (char.IsWhiteSpace((char)character)) { Flush(); state = ATTRIBUTE_EQUAL; } else if (character == '=') { Flush(); state = ATTRIBUTE_VALUE; } else if (html && character == '>') { text.Length = 0; ProcessTag(true); InitTag(); state = RestoreState(); } else { text.Append((char)character); } break; case ATTRIBUTE_EQUAL: if (character == '=') { state = ATTRIBUTE_VALUE; } else if (char.IsWhiteSpace((char)character)) { // empty } else if (html && character == '>') { text.Length = 0; ProcessTag(true); InitTag(); state = RestoreState(); } else if (html && character == '/') { Flush(); state = SINGLE_TAG; } else if (html) { Flush(); text.Append((char)character); state = ATTRIBUTE_KEY; } else { ThrowException(MessageLocalization.GetComposedMessage("error.in.attribute.processing")); } break; case ATTRIBUTE_VALUE: if (character == '"' || character == '\'') { quoteCharacter = character; state = QUOTE; } else if (char.IsWhiteSpace((char)character)) { // empty } else if (html && character == '>') { Flush(); ProcessTag(true); InitTag(); state = RestoreState(); } else if (html) { text.Append((char)character); quoteCharacter = ' '; state = QUOTE; } else { ThrowException(MessageLocalization.GetComposedMessage("error.in.attribute.processing")); } break; } } }
/** * Process the text so that it will render with a combination of fonts * if needed. * @param text the text * @return a <CODE>Phrase</CODE> with one or more chunks */ public Phrase Process(String text) { int fsize = fonts.Count; if (fsize == 0) { throw new ArgumentException(MessageLocalization.GetComposedMessage("no.font.is.defined")); } char[] cc = text.ToCharArray(); int len = cc.Length; StringBuilder sb = new StringBuilder(); Font font = null; int lastidx = -1; Phrase ret = new Phrase(); for (int k = 0; k < len; ++k) { char c = cc[k]; if (c == '\n' || c == '\r') { sb.Append(c); continue; } if (Utilities.IsSurrogatePair(cc, k)) { int u = Utilities.ConvertToUtf32(cc, k); for (int f = 0; f < fsize; ++f) { font = fonts[f]; if (font.BaseFont.CharExists(u)) { if (lastidx != f) { if (sb.Length > 0 && lastidx != -1) { Chunk ck = new Chunk(sb.ToString(), fonts[lastidx]); ret.Add(ck); sb.Length = 0; } lastidx = f; } sb.Append(c); sb.Append(cc[++k]); break; } } } else { for (int f = 0; f < fsize; ++f) { font = fonts[f]; if (font.BaseFont.CharExists(c)) { if (lastidx != f) { if (sb.Length > 0 && lastidx != -1) { Chunk ck = new Chunk(sb.ToString(), fonts[lastidx]); ret.Add(ck); sb.Length = 0; } lastidx = f; } sb.Append(c); break; } } } } if (sb.Length > 0) { Chunk ck = new Chunk(sb.ToString(), fonts[lastidx == -1 ? 0 : lastidx]); ret.Add(ck); } return(ret); }
/** * @see com.itextpdf.text.pdf.PdfArray#add(int[]) */ public override bool Add(int[] values) { throw new ArgumentException(MessageLocalization.GetComposedMessage("illegal.ve.value")); }
// returns the top parent to include in the catalog internal PdfIndirectReference WritePageTree() { if (pages.Count == 0) { throw new IOException(MessageLocalization.GetComposedMessage("the.document.has.no.pages")); } int leaf = 1; List <PdfIndirectReference> tParents = parents; List <PdfIndirectReference> tPages = pages; List <PdfIndirectReference> nextParents = new List <PdfIndirectReference>(); while (true) { leaf *= leafSize; int stdCount = leafSize; int rightCount = tPages.Count % leafSize; if (rightCount == 0) { rightCount = leafSize; } for (int p = 0; p < tParents.Count; ++p) { int count; int thisLeaf = leaf; if (p == tParents.Count - 1) { count = rightCount; thisLeaf = pages.Count % leaf; if (thisLeaf == 0) { thisLeaf = leaf; } } else { count = stdCount; } PdfDictionary top = new PdfDictionary(PdfName.PAGES); top.Put(PdfName.COUNT, new PdfNumber(thisLeaf)); PdfArray kids = new PdfArray(); List <PdfObject> intern = kids.ArrayList; foreach (PdfObject obb in tPages.GetRange(p * stdCount, count)) { intern.Add(obb); } top.Put(PdfName.KIDS, kids); if (tParents.Count > 1) { if ((p % leafSize) == 0) { nextParents.Add(writer.PdfIndirectReference); } top.Put(PdfName.PARENT, nextParents[p / leafSize]); } else { top.Put(PdfName.ITXT, new PdfString(Document.Release)); } writer.AddToBody(top, tParents[p]); } if (tParents.Count == 1) { topParent = tParents[0]; return(topParent); } tPages = tParents; tParents = nextParents; nextParents = new List <PdfIndirectReference>(); } }
/** * Gives you a BaseColor based on a name. * * @param name * a name such as black, violet, cornflowerblue or #RGB or #RRGGBB * or RGB or RRGGBB or rgb(R,G,B) * @return the corresponding BaseColor object. Never returns null. * @throws IllegalArgumentException * if the String isn't a know representation of a color. */ public static BaseColor GetRGBColor(String name) { int[] c = { 0, 0, 0, 255 }; name = name.ToLowerInvariant(); bool colorStrWithoutHash = MissingHashColorFormat(name); if (name.StartsWith("#") || colorStrWithoutHash) { if (!colorStrWithoutHash) { name = name.Substring(1); // lop off the # to unify hex parsing. } if (name.Length == 3) { String s = name.Substring(0, 1); c[0] = int.Parse(s + s, NumberStyles.HexNumber); String s2 = name.Substring(1, 1); c[1] = int.Parse(s2 + s2, NumberStyles.HexNumber); String s3 = name.Substring(2); c[2] = int.Parse(s3 + s3, NumberStyles.HexNumber); return(new BaseColor(c[0], c[1], c[2], c[3])); } if (name.Length == 6) { c[0] = int.Parse(name.Substring(0, 2), NumberStyles.HexNumber); c[1] = int.Parse(name.Substring(2, 2), NumberStyles.HexNumber); c[2] = int.Parse(name.Substring(4), NumberStyles.HexNumber); return(new BaseColor(c[0], c[1], c[2], c[3])); } throw new ArgumentException(MessageLocalization.GetComposedMessage("unknown.color.format.must.be.rgb.or.rrggbb")); } else if (name.StartsWith("rgb(")) { StringTokenizer tok = new StringTokenizer(name, "rgb(), \t\r\n\f"); for (int k = 0; k < 3; ++k) { String v = tok.NextToken(); if (v.EndsWith("%")) { c[k] = int.Parse(v.Substring(0, v.Length - 1)) * 255 / 100; } else { c[k] = int.Parse(v); } if (c[k] < 0) { c[k] = 0; } else if (c[k] > 255) { c[k] = 255; } } return(new BaseColor(c[0], c[1], c[2], c[3])); } name = name.ToLower(CultureInfo.InvariantCulture); if (!NAMES.ContainsKey(name)) { throw new ArgumentException(MessageLocalization.GetComposedMessage("color.not.found", new String[] { name })); } c = NAMES[name]; return(new BaseColor(c[0], c[1], c[2], c[3])); }
/// <summary> /// This method throws an Exception. /// </summary> /// <param name="margin">new value</param> /// <returns>none</returns> public float GetRight(int margin) { throw new Exception(MessageLocalization.GetComposedMessage("dimensions.of.a.cell.can.t.be.calculated.see.the.faq")); }
public override System.Drawing.Image CreateDrawingImage(System.Drawing.Color foreground, System.Drawing.Color background) { int width = 0; byte[] bars = null; switch (codeType) { case EAN13: bars = GetBarsEAN13(code); width = 11 + 12 * 7; break; case EAN8: bars = GetBarsEAN8(code); width = 11 + 8 * 7; break; case UPCA: bars = GetBarsEAN13("0" + code); width = 11 + 12 * 7; break; case UPCE: bars = GetBarsUPCE(code); width = 9 + 6 * 7; break; case SUPP2: bars = GetBarsSupplemental2(code); width = 6 + 2 * 7; break; case SUPP5: bars = GetBarsSupplemental5(code); width = 4 + 5 * 7 + 4 * 2; break; default: throw new InvalidOperationException(MessageLocalization.GetComposedMessage("invalid.code.type")); } int height = (int)barHeight; System.Drawing.Bitmap bmp = new System.Drawing.Bitmap(width, height); for (int h = 0; h < height; ++h) { bool print = true; int ptr = 0; for (int k = 0; k < bars.Length; ++k) { int w = bars[k]; System.Drawing.Color c = background; if (print) { c = foreground; } print = !print; for (int j = 0; j < w; ++j) { bmp.SetPixel(ptr++, h, c); } } } return(bmp); }
/** * Add verification for a particular signature * @param signatureName the signature to validate (it may be a timestamp) * @param ocsp the interface to get the OCSP * @param crl the interface to get the CRL * @param certOption * @param level the validation options to include * @param certInclude * @return true if a validation was generated, false otherwise * @throws Exception */ public bool AddVerification(String signatureName, IOcspClient ocsp, ICrlClient crl, CertificateOption certOption, Level level, CertificateInclusion certInclude) { if (used) { throw new InvalidOperationException(MessageLocalization.GetComposedMessage("verification.already.output")); } PdfPKCS7 pk = acroFields.VerifySignature(signatureName); LOGGER.Info("Adding verification for " + signatureName); X509Certificate[] xc = pk.Certificates; X509Certificate cert; X509Certificate signingCert = pk.SigningCertificate; ValidationData vd = new ValidationData(); for (int k = 0; k < xc.Length; ++k) { cert = xc[k]; LOGGER.Info("Certificate: " + cert.SubjectDN); if (certOption == CertificateOption.SIGNING_CERTIFICATE && !cert.Equals(signingCert)) { continue; } byte[] ocspEnc = null; if (ocsp != null && level != Level.CRL) { ocspEnc = ocsp.GetEncoded(cert, GetParent(cert, xc), null); if (ocspEnc != null) { vd.ocsps.Add(BuildOCSPResponse(ocspEnc)); LOGGER.Info("OCSP added"); } } if (crl != null && (level == Level.CRL || level == Level.OCSP_CRL || (level == Level.OCSP_OPTIONAL_CRL && ocspEnc == null))) { ICollection <byte[]> cims = crl.GetEncoded(xc[k], null); if (cims != null) { foreach (byte[] cim in cims) { bool dup = false; foreach (byte[] b in vd.crls) { if (Arrays.AreEqual(b, cim)) { dup = true; break; } } if (!dup) { vd.crls.Add(cim); LOGGER.Info("CRL added"); } } } } if (certInclude == CertificateInclusion.YES) { vd.certs.Add(xc[k].GetEncoded()); } } if (vd.crls.Count == 0 && vd.ocsps.Count == 0) { return(false); } validated[GetSignatureHashKey(signatureName)] = vd; return(true); }
// methods to set the membervariables /** * Adds an element to this Cell. * <P> * Remark: you can't add ListItems, Rows, Cells, * JPEGs, GIFs or PNGs to a Cell. * * @param element The Element to add * @throws BadElementException if the method was called with a ListItem, Row or Cell */ /// <summary> /// Adds an element to this Cell. /// </summary> /// <remarks> /// You can't add ListItems, Rows, Cells, /// JPEGs, GIFs or PNGs to a Cell. /// </remarks> /// <param name="element">the Element to add</param> public void AddElement(IElement element) { if (IsTable()) { Table table = (Table)arrayList[0]; Cell tmp = new Cell(element); tmp.Border = NO_BORDER; tmp.Colspan = table.Columns; table.AddCell(tmp); return; } switch (element.Type) { case Element.LISTITEM: case Element.ROW: case Element.CELL: throw new BadElementException(MessageLocalization.GetComposedMessage("you.can.t.add.listitems.rows.or.cells.to.a.cell")); case Element.JPEG: case Element.IMGRAW: case Element.IMGTEMPLATE: arrayList.Add(element); break; case Element.LIST: if (float.IsNaN(this.Leading)) { leading = ((List)element).TotalLeading; } if (((List)element).IsEmpty()) { return; } arrayList.Add(element); return; case Element.ANCHOR: case Element.PARAGRAPH: case Element.PHRASE: if (float.IsNaN(leading)) { leading = ((Phrase)element).Leading; } if (((Phrase)element).IsEmpty()) { return; } arrayList.Add(element); return; case Element.CHUNK: if (((Chunk)element).IsEmpty()) { return; } arrayList.Add(element); return; case Element.TABLE: Table table = new Table(3); float[] widths = new float[3]; widths[1] = ((Table)element).Width; switch (((Table)element).Alignment) { case Element.ALIGN_LEFT: widths[0] = 0f; widths[2] = 100f - widths[1]; break; case Element.ALIGN_CENTER: widths[0] = (100f - widths[1]) / 2f; widths[2] = widths[0]; break; case Element.ALIGN_RIGHT: widths[0] = 100f - widths[1]; widths[2] = 0f; break; } table.Widths = widths; Cell tmp; if (arrayList.Count == 0) { table.AddCell(Cell.DummyCell); } else { tmp = new Cell(); tmp.Border = NO_BORDER; tmp.Colspan = 3; foreach (IElement ele in arrayList) { tmp.Add(ele); } table.AddCell(tmp); } tmp = new Cell(); tmp.Border = NO_BORDER; table.AddCell(tmp); table.InsertTable((Table)element); tmp = new Cell(); tmp.Border = NO_BORDER; table.AddCell(tmp); table.AddCell(Cell.DummyCell); Clear(); arrayList.Add(table); return; default: arrayList.Add(element); break; } }
/** * This method checks if the image is a valid JPEG and processes some parameters. * @throws BadElementException * @throws IOException */ private void ProcessParameters() { type = JPEG2000; originalType = ORIGINAL_JPEG2000; inp = null; try { if (rawData == null) { WebRequest w = WebRequest.Create(url); w.Credentials = CredentialCache.DefaultCredentials; inp = w.GetResponse().GetResponseStream(); } else { inp = new MemoryStream(rawData); } boxLength = Cio_read(4); if (boxLength == 0x0000000c) { isJp2 = true; boxType = Cio_read(4); if (JP2_JP != boxType) { throw new IOException(MessageLocalization.GetComposedMessage("expected.jp.marker")); } if (0x0d0a870a != Cio_read(4)) { throw new IOException(MessageLocalization.GetComposedMessage("error.with.jp.marker")); } Jp2_read_boxhdr(); if (JP2_FTYP != boxType) { throw new IOException(MessageLocalization.GetComposedMessage("expected.ftyp.marker")); } Utilities.Skip(inp, boxLength - 8); Jp2_read_boxhdr(); do { if (JP2_JP2H != boxType) { if (boxType == JP2_JP2C) { throw new IOException(MessageLocalization.GetComposedMessage("expected.jp2h.marker")); } Utilities.Skip(inp, boxLength - 8); Jp2_read_boxhdr(); } } while (JP2_JP2H != boxType); Jp2_read_boxhdr(); if (JP2_IHDR != boxType) { throw new IOException(MessageLocalization.GetComposedMessage("expected.ihdr.marker")); } scaledHeight = Cio_read(4); Top = scaledHeight; scaledWidth = Cio_read(4); Right = scaledWidth; numOfComps = Cio_read(2); bpc = -1; bpc = Cio_read(1); Utilities.Skip(inp, 3); Jp2_read_boxhdr(); if (boxType == JP2_BPCC) { bpcBoxData = new byte[boxLength - 8]; inp.Read(bpcBoxData, 0, boxLength - 8); } else if (boxType == JP2_COLR) { do { if (colorSpecBoxes == null) { colorSpecBoxes = new List <ColorSpecBox>(); } colorSpecBoxes.Add(Jp2_read_colr()); try { Jp2_read_boxhdr(); } catch (ZeroBoxSiteException e) { //Probably we have reached the contiguous codestream box which is the last in jpeg2000 and has no length. } } while (JP2_COLR == boxType); } } else if ((uint)boxLength == 0xff4fff51) { Utilities.Skip(inp, 4); int x1 = Cio_read(4); int y1 = Cio_read(4); int x0 = Cio_read(4); int y0 = Cio_read(4); Utilities.Skip(inp, 16); colorspace = Cio_read(2); bpc = 8; scaledHeight = y1 - y0; Top = scaledHeight; scaledWidth = x1 - x0; Right = scaledWidth; } else { throw new IOException(MessageLocalization.GetComposedMessage("not.a.valid.jpeg2000.file")); } } finally { if (inp != null) { try { inp.Close(); } catch { } inp = null; } } plainWidth = this.Width; plainHeight = this.Height; }
/** * Business logic that checks if a certain object is in conformance with PDF/X. * @param writer the writer that is supposed to write the PDF/X file * @param key the type of PDF ISO conformance that has to be checked * @param obj1 the object that is checked for conformance */ public static void CheckPDFXConformance(PdfWriter writer, int key, Object obj1) { if (writer == null || !writer.IsPdfX()) { return; } int conf = writer.PDFXConformance; switch (key) { case PdfIsoKeys.PDFISOKEY_COLOR: switch (conf) { case PdfWriter.PDFX1A2001: if (obj1 is ExtendedColor) { ExtendedColor ec = (ExtendedColor)obj1; switch (ec.Type) { case ExtendedColor.TYPE_CMYK: case ExtendedColor.TYPE_GRAY: return; case ExtendedColor.TYPE_RGB: throw new PdfXConformanceException(MessageLocalization.GetComposedMessage("colorspace.rgb.is.not.allowed")); case ExtendedColor.TYPE_SEPARATION: SpotColor sc = (SpotColor)ec; CheckPDFXConformance(writer, PdfIsoKeys.PDFISOKEY_COLOR, sc.PdfSpotColor.AlternativeCS); break; case ExtendedColor.TYPE_SHADING: ShadingColor xc = (ShadingColor)ec; CheckPDFXConformance(writer, PdfIsoKeys.PDFISOKEY_COLOR, xc.PdfShadingPattern.Shading.ColorSpace); break; case ExtendedColor.TYPE_PATTERN: PatternColor pc = (PatternColor)ec; CheckPDFXConformance(writer, PdfIsoKeys.PDFISOKEY_COLOR, pc.Painter.DefaultColor); break; } } else if (obj1 is BaseColor) { throw new PdfXConformanceException(MessageLocalization.GetComposedMessage("colorspace.rgb.is.not.allowed")); } break; } break; case PdfIsoKeys.PDFISOKEY_CMYK: break; case PdfIsoKeys.PDFISOKEY_RGB: if (conf == PdfWriter.PDFX1A2001) { throw new PdfXConformanceException(MessageLocalization.GetComposedMessage("colorspace.rgb.is.not.allowed")); } break; case PdfIsoKeys.PDFISOKEY_FONT: if (!((BaseFont)obj1).IsEmbedded()) { throw new PdfXConformanceException(MessageLocalization.GetComposedMessage("all.the.fonts.must.be.embedded.this.one.isn.t.1", ((BaseFont)obj1).PostscriptFontName)); } break; case PdfIsoKeys.PDFISOKEY_IMAGE: PdfImage image = (PdfImage)obj1; if (image.Get(PdfName.SMASK) != null) { throw new PdfXConformanceException(MessageLocalization.GetComposedMessage("the.smask.key.is.not.allowed.in.images")); } switch (conf) { case PdfWriter.PDFX1A2001: PdfObject cs = image.Get(PdfName.COLORSPACE); if (cs == null) { return; } if (cs.IsName()) { if (PdfName.DEVICERGB.Equals(cs)) { throw new PdfXConformanceException(MessageLocalization.GetComposedMessage("colorspace.rgb.is.not.allowed")); } } else if (cs.IsArray()) { if (PdfName.CALRGB.Equals(((PdfArray)cs)[0])) { throw new PdfXConformanceException(MessageLocalization.GetComposedMessage("colorspace.calrgb.is.not.allowed")); } } break; } break; case PdfIsoKeys.PDFISOKEY_GSTATE: PdfDictionary gs = (PdfDictionary)obj1; PdfObject obj = gs.Get(PdfName.BM); if (obj != null && !PdfGState.BM_NORMAL.Equals(obj) && !PdfGState.BM_COMPATIBLE.Equals(obj)) { throw new PdfXConformanceException(MessageLocalization.GetComposedMessage("blend.mode.1.not.allowed", obj.ToString())); } obj = gs.Get(PdfName.CA); double v = 0.0; if (obj != null && (v = ((PdfNumber)obj).DoubleValue) != 1.0) { throw new PdfXConformanceException(MessageLocalization.GetComposedMessage("transparency.is.not.allowed.ca.eq.1", v)); } obj = gs.Get(PdfName.ca_); v = 0.0; if (obj != null && (v = ((PdfNumber)obj).DoubleValue) != 1.0) { throw new PdfXConformanceException(MessageLocalization.GetComposedMessage("transparency.is.not.allowed.ca.eq.1", v)); } break; case PdfIsoKeys.PDFISOKEY_LAYER: throw new PdfXConformanceException(MessageLocalization.GetComposedMessage("layers.are.not.allowed")); } }
// constructor /** * Constructs a <CODE>PdfImage</CODE>-object. * * @param image the <CODE>Image</CODE>-object * @param name the <CODE>PdfName</CODE> for this image * @throws BadPdfFormatException on error */ public PdfImage(Image image, String name, PdfIndirectReference maskRef) : base() { this.image = image; if (name == null) { GenerateImgResName(image); } else { this.name = new PdfName(name); } Put(PdfName.TYPE, PdfName.XOBJECT); Put(PdfName.SUBTYPE, PdfName.IMAGE); Put(PdfName.WIDTH, new PdfNumber(image.Width)); Put(PdfName.HEIGHT, new PdfNumber(image.Height)); if (image.Layer != null) { Put(PdfName.OC, image.Layer.Ref); } if (image.IsMask() && (image.Bpc == 1 || image.Bpc > 0xff)) { Put(PdfName.IMAGEMASK, PdfBoolean.PDFTRUE); } if (maskRef != null) { if (image.Smask) { Put(PdfName.SMASK, maskRef); } else { Put(PdfName.MASK, maskRef); } } if (image.IsMask() && image.Inverted) { Put(PdfName.DECODE, new PdfLiteral("[1 0]")); } if (image.Interpolation) { Put(PdfName.INTERPOLATE, PdfBoolean.PDFTRUE); } Stream isp = null; try { // deal with transparency int[] transparency = image.Transparency; if (transparency != null && !image.IsMask() && maskRef == null) { StringBuilder s = new StringBuilder("["); for (int k = 0; k < transparency.Length; ++k) { s.Append(transparency[k]).Append(' '); } s.Append(']'); Put(PdfName.MASK, new PdfLiteral(s.ToString())); } // Raw Image data if (image.IsImgRaw()) { // will also have the CCITT parameters int colorspace = image.Colorspace; bytes = image.RawData; Put(PdfName.LENGTH, new PdfNumber(bytes.Length)); int bpc = image.Bpc; if (bpc > 0xff) { if (!image.IsMask()) { Put(PdfName.COLORSPACE, PdfName.DEVICEGRAY); } Put(PdfName.BITSPERCOMPONENT, new PdfNumber(1)); Put(PdfName.FILTER, PdfName.CCITTFAXDECODE); int k = bpc - Image.CCITTG3_1D; PdfDictionary decodeparms = new PdfDictionary(); if (k != 0) { decodeparms.Put(PdfName.K, new PdfNumber(k)); } if ((colorspace & Image.CCITT_BLACKIS1) != 0) { decodeparms.Put(PdfName.BLACKIS1, PdfBoolean.PDFTRUE); } if ((colorspace & Image.CCITT_ENCODEDBYTEALIGN) != 0) { decodeparms.Put(PdfName.ENCODEDBYTEALIGN, PdfBoolean.PDFTRUE); } if ((colorspace & Image.CCITT_ENDOFLINE) != 0) { decodeparms.Put(PdfName.ENDOFLINE, PdfBoolean.PDFTRUE); } if ((colorspace & Image.CCITT_ENDOFBLOCK) != 0) { decodeparms.Put(PdfName.ENDOFBLOCK, PdfBoolean.PDFFALSE); } decodeparms.Put(PdfName.COLUMNS, new PdfNumber(image.Width)); decodeparms.Put(PdfName.ROWS, new PdfNumber(image.Height)); Put(PdfName.DECODEPARMS, decodeparms); } else { switch (colorspace) { case 1: Put(PdfName.COLORSPACE, PdfName.DEVICEGRAY); if (image.Inverted) { Put(PdfName.DECODE, new PdfLiteral("[1 0]")); } break; case 3: Put(PdfName.COLORSPACE, PdfName.DEVICERGB); if (image.Inverted) { Put(PdfName.DECODE, new PdfLiteral("[1 0 1 0 1 0]")); } break; case 4: default: Put(PdfName.COLORSPACE, PdfName.DEVICECMYK); if (image.Inverted) { Put(PdfName.DECODE, new PdfLiteral("[1 0 1 0 1 0 1 0]")); } break; } PdfDictionary additional = image.Additional; if (additional != null) { Merge(additional); } if (image.IsMask() && (image.Bpc == 1 || image.Bpc > 8)) { Remove(PdfName.COLORSPACE); } Put(PdfName.BITSPERCOMPONENT, new PdfNumber(image.Bpc)); if (image.Deflated) { Put(PdfName.FILTER, PdfName.FLATEDECODE); } else { FlateCompress(image.CompressionLevel); } } return; } // GIF, JPEG or PNG String errorID; if (image.RawData == null) { WebRequest wr = WebRequest.Create(image.Url); wr.Credentials = CredentialCache.DefaultCredentials; isp = wr.GetResponse().GetResponseStream(); errorID = image.Url.ToString(); } else { isp = new MemoryStream(image.RawData); errorID = "Byte array"; } switch (image.Type) { case Image.JPEG: Put(PdfName.FILTER, PdfName.DCTDECODE); if (image.ColorTransform == 0) { PdfDictionary decodeparms = new PdfDictionary(); decodeparms.Put(PdfName.COLORTRANSFORM, new PdfNumber(0)); Put(PdfName.DECODEPARMS, decodeparms); } switch (image.Colorspace) { case 1: Put(PdfName.COLORSPACE, PdfName.DEVICEGRAY); break; case 3: Put(PdfName.COLORSPACE, PdfName.DEVICERGB); break; default: Put(PdfName.COLORSPACE, PdfName.DEVICECMYK); if (image.Inverted) { Put(PdfName.DECODE, new PdfLiteral("[1 0 1 0 1 0 1 0]")); } break; } Put(PdfName.BITSPERCOMPONENT, new PdfNumber(8)); if (image.RawData != null) { bytes = image.RawData; Put(PdfName.LENGTH, new PdfNumber(bytes.Length)); return; } streamBytes = new MemoryStream(); TransferBytes(isp, streamBytes, -1); break; case Image.JPEG2000: Put(PdfName.FILTER, PdfName.JPXDECODE); if (image.Colorspace > 0) { switch (image.Colorspace) { case 1: Put(PdfName.COLORSPACE, PdfName.DEVICEGRAY); break; case 3: Put(PdfName.COLORSPACE, PdfName.DEVICERGB); break; default: Put(PdfName.COLORSPACE, PdfName.DEVICECMYK); break; } Put(PdfName.BITSPERCOMPONENT, new PdfNumber(image.Bpc)); } if (image.RawData != null) { bytes = image.RawData; Put(PdfName.LENGTH, new PdfNumber(bytes.Length)); return; } streamBytes = new MemoryStream(); TransferBytes(isp, streamBytes, -1); break; case Image.JBIG2: Put(PdfName.FILTER, PdfName.JBIG2DECODE); Put(PdfName.COLORSPACE, PdfName.DEVICEGRAY); Put(PdfName.BITSPERCOMPONENT, new PdfNumber(1)); if (image.RawData != null) { bytes = image.RawData; Put(PdfName.LENGTH, new PdfNumber(bytes.Length)); return; } streamBytes = new MemoryStream(); TransferBytes(isp, streamBytes, -1); break; default: throw new IOException(MessageLocalization.GetComposedMessage("1.is.an.unknown.image.format", errorID)); } if (image.CompressionLevel > NO_COMPRESSION) { FlateCompress(image.CompressionLevel); } Put(PdfName.LENGTH, new PdfNumber(streamBytes.Length)); } finally { if (isp != null) { try{ isp.Close(); } catch { // empty on purpose } } } }
/// <summary> /// Gives you a BaseColor based on a name. /// </summary> /// <param name="name">a name such as black, violet, cornflowerblue or #RGB or #RRGGBB or RGB or RRGGBB or rgb(R,G,B)</param> /// <returns>the corresponding BaseColor object. Never returns null. @throws IllegalArgumentException if the String isn't a know representation of a color.</returns> public static BaseColor GetRGBColor(String name) { int[] color = { 0, 0, 0, 255 }; String colorName = name.ToLower(); bool colorStrWithoutHash = MissingHashColorFormat(colorName); if (colorName.StartsWith("#") || colorStrWithoutHash) { if (!colorStrWithoutHash) { // lop off the # to unify hex parsing. colorName = colorName.Substring(1); } if (colorName.Length == 3) { String red = colorName.Substring(0, 1); color[0] = int.Parse(red + red, NumberStyles.HexNumber); String green = colorName.Substring(1, 1); color[1] = int.Parse(green + green, NumberStyles.HexNumber); String blue = colorName.Substring(2); color[2] = int.Parse(blue + blue, NumberStyles.HexNumber); return(new BaseColor(color[0], color[1], color[2], color[3])); } if (colorName.Length == 6) { color[0] = int.Parse(colorName.Substring(0, 2), NumberStyles.HexNumber); color[1] = int.Parse(colorName.Substring(2, 2), NumberStyles.HexNumber); color[2] = int.Parse(colorName.Substring(4), NumberStyles.HexNumber); return(new BaseColor(color[0], color[1], color[2], color[3])); } throw new FormatException( MessageLocalization .GetComposedMessage("unknown.color.format.must.be.rgb.or.rrggbb")); } if (colorName.StartsWith("rgb(")) { String delim = "rgb(), \t\r\n\f"; StringTokenizer tok = new StringTokenizer(colorName, delim); for (int k = 0; k < 3; ++k) { if (tok.HasMoreTokens()) { color[k] = GetRGBChannelValue(tok.NextToken()); color[k] = Math.Max(0, color[k]); color[k] = Math.Min(255, color[k]); } } return(new BaseColor(color[0], color[1], color[2], color[3])); } if (colorName.StartsWith("rgba(")) { const String delim = "rgba(), \t\r\n\f"; StringTokenizer tok = new StringTokenizer(colorName, delim); for (int k = 0; k < 3; ++k) { if (tok.HasMoreTokens()) { color[k] = GetRGBChannelValue(tok.NextToken()); color[k] = Math.Max(0, color[k]); color[k] = Math.Min(255, color[k]); } } if (tok.HasMoreTokens()) { color[3] = (int)(255 * float.Parse(tok.NextToken()) + 0.5); } return(new BaseColor(color[0], color[1], color[2], color[3])); } if (!NAMES.ContainsKey(colorName)) { throw new FormatException( MessageLocalization.GetComposedMessage("color.not.found", new String[] { colorName })); } color = NAMES[colorName]; return(new BaseColor(color[0], color[1], color[2], color[3])); }
virtual public void VerifyParamReplacementNoParam() { Assert.AreEqual("{1}: unsupported JPEG marker: {2}", MessageLocalization .GetComposedMessage("1.unsupported.jpeg.marker.2")); }
/** * Creates a file specification with the file embedded. The file may * come from the file system or from a byte array. * @param writer the <CODE>PdfWriter</CODE> * @param filePath the file path * @param fileDisplay the file information that is presented to the user * @param fileStore the byte array with the file. If it is not <CODE>null</CODE> * it takes precedence over <CODE>filePath</CODE> * @param mimeType the optional mimeType * @param fileParameter the optional extra file parameters such as the creation or modification date * @param compressionLevel the level of compression * @throws IOException on error * @return the file specification * @since 2.1.3 */ public static PdfFileSpecification FileEmbedded(PdfWriter writer, String filePath, String fileDisplay, byte[] fileStore, String mimeType, PdfDictionary fileParameter, int compressionLevel) { PdfFileSpecification fs = new PdfFileSpecification(); fs.writer = writer; fs.Put(PdfName.F, new PdfString(fileDisplay)); PdfEFStream stream; Stream inp = null; PdfIndirectReference refi; PdfIndirectReference refFileLength = null; try { if (fileStore == null) { refFileLength = writer.PdfIndirectReference; if (File.Exists(filePath)) { inp = new FileStream(filePath, FileMode.Open, FileAccess.Read); } else { if (filePath.StartsWith("file:/") || filePath.StartsWith("http://") || filePath.StartsWith("https://")) { WebRequest w = WebRequest.Create(filePath); inp = w.GetResponse().GetResponseStream(); } else { inp = BaseFont.GetResourceStream(filePath); if (inp == null) { throw new IOException(MessageLocalization.GetComposedMessage("1.not.found.as.file.or.resource", filePath)); } } } stream = new PdfEFStream(inp, writer); } else { stream = new PdfEFStream(fileStore); } stream.Put(PdfName.TYPE, PdfName.EMBEDDEDFILE); stream.FlateCompress(compressionLevel); PdfDictionary param = new PdfDictionary(); if (fileParameter != null) { param.Merge(fileParameter); } if (fileStore != null) { param.Put(PdfName.SIZE, new PdfNumber(stream.RawLength)); stream.Put(PdfName.PARAMS, param); } else { stream.Put(PdfName.PARAMS, refFileLength); } if (mimeType != null) { stream.Put(PdfName.SUBTYPE, new PdfName(mimeType)); } refi = writer.AddToBody(stream).IndirectReference; if (fileStore == null) { stream.WriteLength(); param.Put(PdfName.SIZE, new PdfNumber(stream.RawLength)); writer.AddToBody(param, refFileLength); } } finally { if (inp != null) { try{ inp.Close(); }catch {} } } PdfDictionary f = new PdfDictionary(); f.Put(PdfName.F, refi); fs.Put(PdfName.EF, f); return(fs); }
virtual public void VerifyParamReplacement2Param() { Assert.AreEqual("one: unsupported JPEG marker: two", MessageLocalization.GetComposedMessage( "1.unsupported.jpeg.marker.2", "one", "two")); }
/** Converts the human readable text to the characters needed to * create a barcode. Some optimization is done to get the shortest code. * @param text the text to convert * @param ucc <CODE>true</CODE> if it is an UCC/EAN-128. In this case * the character FNC1 is added * @return the code ready to be fed to GetBarsCode128Raw() */ public static string GetRawText(string text, bool ucc) { String outs = ""; int tLen = text.Length; if (tLen == 0) { outs += START_B; if (ucc) { outs += FNC1_INDEX; } return(outs); } int c = 0; for (int k = 0; k < tLen; ++k) { c = text[k]; if (c > 127 && c != FNC1) { throw new ArgumentException(MessageLocalization.GetComposedMessage("there.are.illegal.characters.for.barcode.128.in.1", text)); } } c = text[0]; char currentCode = START_B; int index = 0; if (IsNextDigits(text, index, 2)) { currentCode = START_C; outs += currentCode; if (ucc) { outs += FNC1_INDEX; } String out2 = GetPackedRawDigits(text, index, 2); index += (int)out2[0]; outs += out2.Substring(1); } else if (c < ' ') { currentCode = START_A; outs += currentCode; if (ucc) { outs += FNC1_INDEX; } outs += (char)(c + 64); ++index; } else { outs += currentCode; if (ucc) { outs += FNC1_INDEX; } if (c == FNC1) { outs += FNC1_INDEX; } else { outs += (char)(c - ' '); } ++index; } while (index < tLen) { switch (currentCode) { case START_A: { if (IsNextDigits(text, index, 4)) { currentCode = START_C; outs += CODE_AB_TO_C; String out2 = GetPackedRawDigits(text, index, 4); index += (int)out2[0]; outs += out2.Substring(1); } else { c = text[index++]; if (c == FNC1) { outs += FNC1_INDEX; } else if (c > '_') { currentCode = START_B; outs += CODE_AC_TO_B; outs += (char)(c - ' '); } else if (c < ' ') { outs += (char)(c + 64); } else { outs += (char)(c - ' '); } } } break; case START_B: { if (IsNextDigits(text, index, 4)) { currentCode = START_C; outs += CODE_AB_TO_C; String out2 = GetPackedRawDigits(text, index, 4); index += (int)out2[0]; outs += out2.Substring(1); } else { c = text[index++]; if (c == FNC1) { outs += FNC1_INDEX; } else if (c < ' ') { currentCode = START_A; outs += CODE_BC_TO_A; outs += (char)(c + 64); } else { outs += (char)(c - ' '); } } } break; case START_C: { if (IsNextDigits(text, index, 2)) { String out2 = GetPackedRawDigits(text, index, 2); index += (int)out2[0]; outs += out2.Substring(1); } else { c = text[index++]; if (c == FNC1) { outs += FNC1_INDEX; } else if (c < ' ') { currentCode = START_A; outs += CODE_BC_TO_A; outs += (char)(c + 64); } else { currentCode = START_B; outs += CODE_AC_TO_B; outs += (char)(c - ' '); } } } break; } } return(outs); }
internal void AddClass(PdfObject obj) { obj = GetDirectObject(obj); if (obj.IsDictionary()) { PdfObject curClass = ((PdfDictionary)obj).Get(PdfName.C); if (curClass == null) { return; } if (curClass.IsArray()) { PdfArray array = (PdfArray)curClass; for (int i = 0; i < array.Size; ++i) { AddClass(array[i]); } } else if (curClass.IsName()) { AddClass(curClass); } } else if (obj.IsName()) { PdfName name = (PdfName)obj; if (sourceClassMap == null) { obj = GetDirectObject(structTreeRoot.Get(PdfName.CLASSMAP)); if (obj == null || !obj.IsDictionary()) { return; } sourceClassMap = (PdfDictionary)obj; } obj = GetDirectObject(sourceClassMap.Get(name)); if (obj == null) { return; } PdfObject put = structureTreeRoot.GetMappedClass(name); if (put != null) { if (!CompareObjects(put, obj)) { throw new BadPdfFormatException(MessageLocalization.GetComposedMessage("conflict.input.classmap", name)); } } else { if (obj.IsDictionary()) { structureTreeRoot.MapClass(name, GetDirectDict((PdfDictionary)obj)); } else if (obj.IsArray()) { structureTreeRoot.MapClass(name, GetDirectArray((PdfArray)obj)); } } } }
internal void Propagate(PdfObject obj, PdfIndirectReference refo, bool restricted) { if (obj == null) { return; } // if (refo != null) // AddToBody(obj, refo); if (obj is PdfIndirectReference) { return; } switch (obj.Type) { case PdfObject.DICTIONARY: case PdfObject.STREAM: { PdfDictionary dic = (PdfDictionary)obj; foreach (PdfName key in dic.Keys) { if (restricted && (key.Equals(PdfName.PARENT) || key.Equals(PdfName.KIDS))) { continue; } PdfObject ob = dic.Get(key); if (ob != null && ob.IsIndirect()) { PRIndirectReference ind = (PRIndirectReference)ob; if (!SetVisited(ind) && !IsPage(ind)) { PdfIndirectReference refi = GetNewReference(ind); Propagate(PdfReader.GetPdfObjectRelease(ind), refi, restricted); } } else { Propagate(ob, null, restricted); } } break; } case PdfObject.ARRAY: { //PdfArray arr = new PdfArray(); for (ListIterator <PdfObject> it = ((PdfArray)obj).GetListIterator(); it.HasNext();) { PdfObject ob = it.Next(); if (ob != null && ob.IsIndirect()) { PRIndirectReference ind = (PRIndirectReference)ob; if (!IsVisited(ind) && !IsPage(ind)) { PdfIndirectReference refi = GetNewReference(ind); Propagate(PdfReader.GetPdfObjectRelease(ind), refi, restricted); } } else { Propagate(ob, null, restricted); } } break; } case PdfObject.INDIRECT: { throw new Exception(MessageLocalization.GetComposedMessage("reference.pointing.to.reference")); } } }
virtual public void ReadAll() { if (meta.ReadInt() != unchecked ((int)0x9AC6CDD7)) { throw new DocumentException(MessageLocalization.GetComposedMessage("not.a.placeable.windows.metafile")); } meta.ReadWord(); left = meta.ReadShort(); top = meta.ReadShort(); right = meta.ReadShort(); bottom = meta.ReadShort(); inch = meta.ReadWord(); state.ScalingX = (float)(right - left) / (float)inch * 72f; state.ScalingY = (float)(bottom - top) / (float)inch * 72f; state.OffsetWx = left; state.OffsetWy = top; state.ExtentWx = right - left; state.ExtentWy = bottom - top; meta.ReadInt(); meta.ReadWord(); meta.Skip(18); int tsize; int function; cb.SetLineCap(1); cb.SetLineJoin(1); for (;;) { int lenMarker = meta.Length; tsize = meta.ReadInt(); if (tsize < 3) { break; } function = meta.ReadWord(); switch (function) { case 0: break; case META_CREATEPALETTE: case META_CREATEREGION: case META_DIBCREATEPATTERNBRUSH: state.AddMetaObject(new MetaObject()); break; case META_CREATEPENINDIRECT: { MetaPen pen = new MetaPen(); pen.Init(meta); state.AddMetaObject(pen); break; } case META_CREATEBRUSHINDIRECT: { MetaBrush brush = new MetaBrush(); brush.Init(meta); state.AddMetaObject(brush); break; } case META_CREATEFONTINDIRECT: { MetaFont font = new MetaFont(); font.Init(meta); state.AddMetaObject(font); break; } case META_SELECTOBJECT: { int idx = meta.ReadWord(); state.SelectMetaObject(idx, cb); break; } case META_DELETEOBJECT: { int idx = meta.ReadWord(); state.DeleteMetaObject(idx); break; } case META_SAVEDC: state.SaveState(cb); break; case META_RESTOREDC: { int idx = meta.ReadShort(); state.RestoreState(idx, cb); break; } case META_SETWINDOWORG: state.OffsetWy = meta.ReadShort(); state.OffsetWx = meta.ReadShort(); break; case META_SETWINDOWEXT: state.ExtentWy = meta.ReadShort(); state.ExtentWx = meta.ReadShort(); break; case META_MOVETO: { int y = meta.ReadShort(); Point p = new Point(meta.ReadShort(), y); state.CurrentPoint = p; break; } case META_LINETO: { int y = meta.ReadShort(); int x = meta.ReadShort(); Point p = state.CurrentPoint; cb.MoveTo(state.TransformX(p.x), state.TransformY(p.y)); cb.LineTo(state.TransformX(x), state.TransformY(y)); cb.Stroke(); state.CurrentPoint = new Point(x, y); break; } case META_POLYLINE: { state.LineJoinPolygon = cb; int len = meta.ReadWord(); int x = meta.ReadShort(); int y = meta.ReadShort(); cb.MoveTo(state.TransformX(x), state.TransformY(y)); for (int k = 1; k < len; ++k) { x = meta.ReadShort(); y = meta.ReadShort(); cb.LineTo(state.TransformX(x), state.TransformY(y)); } cb.Stroke(); break; } case META_POLYGON: { if (IsNullStrokeFill(false)) { break; } int len = meta.ReadWord(); int sx = meta.ReadShort(); int sy = meta.ReadShort(); cb.MoveTo(state.TransformX(sx), state.TransformY(sy)); for (int k = 1; k < len; ++k) { int x = meta.ReadShort(); int y = meta.ReadShort(); cb.LineTo(state.TransformX(x), state.TransformY(y)); } cb.LineTo(state.TransformX(sx), state.TransformY(sy)); StrokeAndFill(); break; } case META_POLYPOLYGON: { if (IsNullStrokeFill(false)) { break; } int numPoly = meta.ReadWord(); int[] lens = new int[numPoly]; for (int k = 0; k < lens.Length; ++k) { lens[k] = meta.ReadWord(); } for (int j = 0; j < lens.Length; ++j) { int len = lens[j]; int sx = meta.ReadShort(); int sy = meta.ReadShort(); cb.MoveTo(state.TransformX(sx), state.TransformY(sy)); for (int k = 1; k < len; ++k) { int x = meta.ReadShort(); int y = meta.ReadShort(); cb.LineTo(state.TransformX(x), state.TransformY(y)); } cb.LineTo(state.TransformX(sx), state.TransformY(sy)); } StrokeAndFill(); break; } case META_ELLIPSE: { if (IsNullStrokeFill(state.LineNeutral)) { break; } int b = meta.ReadShort(); int r = meta.ReadShort(); int t = meta.ReadShort(); int l = meta.ReadShort(); cb.Arc(state.TransformX(l), state.TransformY(b), state.TransformX(r), state.TransformY(t), 0, 360); StrokeAndFill(); break; } case META_ARC: { if (IsNullStrokeFill(state.LineNeutral)) { break; } float yend = state.TransformY(meta.ReadShort()); float xend = state.TransformX(meta.ReadShort()); float ystart = state.TransformY(meta.ReadShort()); float xstart = state.TransformX(meta.ReadShort()); float b = state.TransformY(meta.ReadShort()); float r = state.TransformX(meta.ReadShort()); float t = state.TransformY(meta.ReadShort()); float l = state.TransformX(meta.ReadShort()); float cx = (r + l) / 2; float cy = (t + b) / 2; float arc1 = GetArc(cx, cy, xstart, ystart); float arc2 = GetArc(cx, cy, xend, yend); arc2 -= arc1; if (arc2 <= 0) { arc2 += 360; } cb.Arc(l, b, r, t, arc1, arc2); cb.Stroke(); break; } case META_PIE: { if (IsNullStrokeFill(state.LineNeutral)) { break; } float yend = state.TransformY(meta.ReadShort()); float xend = state.TransformX(meta.ReadShort()); float ystart = state.TransformY(meta.ReadShort()); float xstart = state.TransformX(meta.ReadShort()); float b = state.TransformY(meta.ReadShort()); float r = state.TransformX(meta.ReadShort()); float t = state.TransformY(meta.ReadShort()); float l = state.TransformX(meta.ReadShort()); float cx = (r + l) / 2; float cy = (t + b) / 2; float arc1 = GetArc(cx, cy, xstart, ystart); float arc2 = GetArc(cx, cy, xend, yend); arc2 -= arc1; if (arc2 <= 0) { arc2 += 360; } List <float[]> ar = PdfContentByte.BezierArc(l, b, r, t, arc1, arc2); if (ar.Count == 0) { break; } float[] pt = ar[0]; cb.MoveTo(cx, cy); cb.LineTo(pt[0], pt[1]); for (int k = 0; k < ar.Count; ++k) { pt = ar[k]; cb.CurveTo(pt[2], pt[3], pt[4], pt[5], pt[6], pt[7]); } cb.LineTo(cx, cy); StrokeAndFill(); break; } case META_CHORD: { if (IsNullStrokeFill(state.LineNeutral)) { break; } float yend = state.TransformY(meta.ReadShort()); float xend = state.TransformX(meta.ReadShort()); float ystart = state.TransformY(meta.ReadShort()); float xstart = state.TransformX(meta.ReadShort()); float b = state.TransformY(meta.ReadShort()); float r = state.TransformX(meta.ReadShort()); float t = state.TransformY(meta.ReadShort()); float l = state.TransformX(meta.ReadShort()); float cx = (r + l) / 2; float cy = (t + b) / 2; float arc1 = GetArc(cx, cy, xstart, ystart); float arc2 = GetArc(cx, cy, xend, yend); arc2 -= arc1; if (arc2 <= 0) { arc2 += 360; } List <float[]> ar = PdfContentByte.BezierArc(l, b, r, t, arc1, arc2); if (ar.Count == 0) { break; } float[] pt = ar[0]; cx = pt[0]; cy = pt[1]; cb.MoveTo(cx, cy); for (int k = 0; k < ar.Count; ++k) { pt = ar[k]; cb.CurveTo(pt[2], pt[3], pt[4], pt[5], pt[6], pt[7]); } cb.LineTo(cx, cy); StrokeAndFill(); break; } case META_RECTANGLE: { if (IsNullStrokeFill(true)) { break; } float b = state.TransformY(meta.ReadShort()); float r = state.TransformX(meta.ReadShort()); float t = state.TransformY(meta.ReadShort()); float l = state.TransformX(meta.ReadShort()); cb.Rectangle(l, b, r - l, t - b); StrokeAndFill(); break; } case META_ROUNDRECT: { if (IsNullStrokeFill(true)) { break; } float h = state.TransformY(0) - state.TransformY(meta.ReadShort()); float w = state.TransformX(meta.ReadShort()) - state.TransformX(0); float b = state.TransformY(meta.ReadShort()); float r = state.TransformX(meta.ReadShort()); float t = state.TransformY(meta.ReadShort()); float l = state.TransformX(meta.ReadShort()); cb.RoundRectangle(l, b, r - l, t - b, (h + w) / 4); StrokeAndFill(); break; } case META_INTERSECTCLIPRECT: { float b = state.TransformY(meta.ReadShort()); float r = state.TransformX(meta.ReadShort()); float t = state.TransformY(meta.ReadShort()); float l = state.TransformX(meta.ReadShort()); cb.Rectangle(l, b, r - l, t - b); cb.EoClip(); cb.NewPath(); break; } case META_EXTTEXTOUT: { int y = meta.ReadShort(); int x = meta.ReadShort(); int count = meta.ReadWord(); int flag = meta.ReadWord(); int x1 = 0; int y1 = 0; int x2 = 0; int y2 = 0; if ((flag & (MetaFont.ETO_CLIPPED | MetaFont.ETO_OPAQUE)) != 0) { x1 = meta.ReadShort(); y1 = meta.ReadShort(); x2 = meta.ReadShort(); y2 = meta.ReadShort(); } byte[] text = new byte[count]; int k; for (k = 0; k < count; ++k) { byte c = (byte)meta.ReadByte(); if (c == 0) { break; } text[k] = c; } string s; try { s = System.Text.Encoding.GetEncoding(1252).GetString(text, 0, k); } catch { s = System.Text.ASCIIEncoding.ASCII.GetString(text, 0, k); } OutputText(x, y, flag, x1, y1, x2, y2, s); break; } case META_TEXTOUT: { int count = meta.ReadWord(); byte[] text = new byte[count]; int k; for (k = 0; k < count; ++k) { byte c = (byte)meta.ReadByte(); if (c == 0) { break; } text[k] = c; } string s; try { s = System.Text.Encoding.GetEncoding(1252).GetString(text, 0, k); } catch { s = System.Text.ASCIIEncoding.ASCII.GetString(text, 0, k); } count = (count + 1) & 0xfffe; meta.Skip(count - k); int y = meta.ReadShort(); int x = meta.ReadShort(); OutputText(x, y, 0, 0, 0, 0, 0, s); break; } case META_SETBKCOLOR: state.CurrentBackgroundColor = meta.ReadColor(); break; case META_SETTEXTCOLOR: state.CurrentTextColor = meta.ReadColor(); break; case META_SETTEXTALIGN: state.TextAlign = meta.ReadWord(); break; case META_SETBKMODE: state.BackgroundMode = meta.ReadWord(); break; case META_SETPOLYFILLMODE: state.PolyFillMode = meta.ReadWord(); break; case META_SETPIXEL: { BaseColor color = meta.ReadColor(); int y = meta.ReadShort(); int x = meta.ReadShort(); cb.SaveState(); cb.SetColorFill(color); cb.Rectangle(state.TransformX(x), state.TransformY(y), .2f, .2f); cb.Fill(); cb.RestoreState(); break; } case META_DIBSTRETCHBLT: case META_STRETCHDIB: { int rop = meta.ReadInt(); if (function == META_STRETCHDIB) { /*int usage = */ meta.ReadWord(); } int srcHeight = meta.ReadShort(); int srcWidth = meta.ReadShort(); int ySrc = meta.ReadShort(); int xSrc = meta.ReadShort(); float destHeight = state.TransformY(meta.ReadShort()) - state.TransformY(0); float destWidth = state.TransformX(meta.ReadShort()) - state.TransformX(0); float yDest = state.TransformY(meta.ReadShort()); float xDest = state.TransformX(meta.ReadShort()); byte[] b = new byte[(tsize * 2) - (meta.Length - lenMarker)]; for (int k = 0; k < b.Length; ++k) { b[k] = (byte)meta.ReadByte(); } try { MemoryStream inb = new MemoryStream(b); Image bmp = BmpImage.GetImage(inb, true, b.Length); cb.SaveState(); cb.Rectangle(xDest, yDest, destWidth, destHeight); cb.Clip(); cb.NewPath(); bmp.ScaleAbsolute(destWidth * bmp.Width / srcWidth, -destHeight * bmp.Height / srcHeight); bmp.SetAbsolutePosition(xDest - destWidth * xSrc / srcWidth, yDest + destHeight * ySrc / srcHeight - bmp.ScaledHeight); cb.AddImage(bmp); cb.RestoreState(); } catch { // empty on purpose } break; } } meta.Skip((tsize * 2) - (meta.Length - lenMarker)); } state.Cleanup(cb); }
/** * @see com.itextpdf.text.pdf.PdfArray#addFirst(com.itextpdf.text.pdf.PdfObject) */ public override void AddFirst(PdfObject obj) { throw new ArgumentException(MessageLocalization.GetComposedMessage("illegal.ve.value")); }
public static byte[] WrapBMP(Image image) { if (image.OriginalType != Image.ORIGINAL_BMP) { throw new IOException(MessageLocalization.GetComposedMessage("only.bmp.can.be.wrapped.in.wmf")); } Stream imgIn; byte[] data = null; if (image.OriginalData == null) { WebRequest wr = WebRequest.Create(image.Url); wr.Credentials = CredentialCache.DefaultCredentials; imgIn = wr.GetResponse().GetResponseStream(); MemoryStream outp = new MemoryStream(); int b = 0; while ((b = imgIn.ReadByte()) != -1) { outp.WriteByte((byte)b); } imgIn.Close(); data = outp.ToArray(); } else { data = image.OriginalData; } int sizeBmpWords = (data.Length - 14 + 1) >> 1; MemoryStream os = new MemoryStream(); // write metafile header WriteWord(os, 1); WriteWord(os, 9); WriteWord(os, 0x0300); WriteDWord(os, 9 + 4 + 5 + 5 + (13 + sizeBmpWords) + 3); // total metafile size WriteWord(os, 1); WriteDWord(os, 14 + sizeBmpWords); // max record size WriteWord(os, 0); // write records WriteDWord(os, 4); WriteWord(os, META_SETMAPMODE); WriteWord(os, 8); WriteDWord(os, 5); WriteWord(os, META_SETWINDOWORG); WriteWord(os, 0); WriteWord(os, 0); WriteDWord(os, 5); WriteWord(os, META_SETWINDOWEXT); WriteWord(os, (int)image.Height); WriteWord(os, (int)image.Width); WriteDWord(os, 13 + sizeBmpWords); WriteWord(os, META_DIBSTRETCHBLT); WriteDWord(os, 0x00cc0020); WriteWord(os, (int)image.Height); WriteWord(os, (int)image.Width); WriteWord(os, 0); WriteWord(os, 0); WriteWord(os, (int)image.Height); WriteWord(os, (int)image.Width); WriteWord(os, 0); WriteWord(os, 0); os.Write(data, 14, data.Length - 14); if ((data.Length & 1) == 1) { os.WriteByte(0); } // WriteDWord(os, 14 + sizeBmpWords); // WriteWord(os, META_STRETCHDIB); // WriteDWord(os, 0x00cc0020); // WriteWord(os, 0); // WriteWord(os, (int)image.Height); // WriteWord(os, (int)image.Width); // WriteWord(os, 0); // WriteWord(os, 0); // WriteWord(os, (int)image.Height); // WriteWord(os, (int)image.Width); // WriteWord(os, 0); // WriteWord(os, 0); // os.Write(data, 14, data.length - 14); // if ((data.length & 1) == 1) // os.Write(0); WriteDWord(os, 3); WriteWord(os, 0); os.Close(); return(os.ToArray()); }
/** * @see com.itextpdf.text.pdf.PdfArray#add(int, com.itextpdf.text.pdf.PdfObject) */ public override void Add(int index, PdfObject element) { throw new ArgumentException(MessageLocalization.GetComposedMessage("illegal.ve.value")); }
void ReadPng() { for (int i = 0; i < PNGID.Length; i++) { if (PNGID[i] != isp.ReadByte()) { throw new IOException(MessageLocalization.GetComposedMessage("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(MessageLocalization.GetComposedMessage("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(MessageLocalization.GetComposedMessage("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); } }
internal override void WriteFont(PdfWriter writer, PdfIndirectReference piRef, Object[] oParams) { if (this.writer != writer) { throw new ArgumentException(MessageLocalization.GetComposedMessage("type3.font.used.with.the.wrong.pdfwriter")); } // Get first & lastchar ... int firstChar = 0; while (firstChar < usedSlot.Length && !usedSlot[firstChar]) { firstChar++; } if (firstChar == usedSlot.Length) { throw new DocumentException(MessageLocalization.GetComposedMessage("no.glyphs.defined.for.type3.font")); } int lastChar = usedSlot.Length - 1; while (lastChar >= firstChar && !usedSlot[lastChar]) { lastChar--; } int[] widths = new int[lastChar - firstChar + 1]; int[] invOrd = new int[lastChar - firstChar + 1]; int invOrdIndx = 0, w = 0; for (int u = firstChar; u <= lastChar; u++, w++) { if (usedSlot[u]) { invOrd[invOrdIndx++] = u; widths[w] = widths3[u]; } } PdfArray diffs = new PdfArray(); PdfDictionary charprocs = new PdfDictionary(); int last = -1; for (int k = 0; k < invOrdIndx; ++k) { int c = invOrd[k]; if (c > last) { last = c; diffs.Add(new PdfNumber(last)); } ++last; int c2 = invOrd[k]; String s = GlyphList.UnicodeToName(c2); if (s == null) { s = "a" + c2; } PdfName n = new PdfName(s); diffs.Add(n); Type3Glyph glyph = (Type3Glyph)char2glyph[(char)c2]; PdfStream stream = new PdfStream(glyph.ToPdf(null)); stream.FlateCompress(compressionLevel); PdfIndirectReference refp = writer.AddToBody(stream).IndirectReference; charprocs.Put(n, refp); } PdfDictionary font = new PdfDictionary(PdfName.FONT); font.Put(PdfName.SUBTYPE, PdfName.TYPE3); if (colorized) { font.Put(PdfName.FONTBBOX, new PdfRectangle(0, 0, 0, 0)); } else { font.Put(PdfName.FONTBBOX, new PdfRectangle(llx, lly, urx, ury)); } font.Put(PdfName.FONTMATRIX, new PdfArray(new float[] { 0.001f, 0, 0, 0.001f, 0, 0 })); font.Put(PdfName.CHARPROCS, writer.AddToBody(charprocs).IndirectReference); PdfDictionary encoding = new PdfDictionary(); encoding.Put(PdfName.DIFFERENCES, diffs); font.Put(PdfName.ENCODING, writer.AddToBody(encoding).IndirectReference); font.Put(PdfName.FIRSTCHAR, new PdfNumber(firstChar)); font.Put(PdfName.LASTCHAR, new PdfNumber(lastChar)); font.Put(PdfName.WIDTHS, writer.AddToBody(new PdfArray(widths)).IndirectReference); if (pageResources.HasResources()) { font.Put(PdfName.RESOURCES, writer.AddToBody(pageResources.Resources).IndirectReference); } writer.AddToBody(font, piRef); }
void DecodePass(int xOffset, int yOffset, int xStep, int yStep, int passWidth, int passHeight) { if ((passWidth == 0) || (passHeight == 0)) { return; } int bytesPerRow = (inputBands * passWidth * bitDepth + 7) / 8; byte[] curr = new byte[bytesPerRow]; byte[] prior = new byte[bytesPerRow]; // Decode the (sub)image row-by-row int srcY, dstY; for (srcY = 0, dstY = yOffset; srcY < passHeight; srcY++, dstY += yStep) { // Read the filter type byte and a row of data int filter = 0; try { filter = dataStream.ReadByte(); ReadFully(dataStream, curr, 0, bytesPerRow); } catch { // empty on purpose } switch (filter) { case PNG_FILTER_NONE: break; case PNG_FILTER_SUB: DecodeSubFilter(curr, bytesPerRow, bytesPerPixel); break; case PNG_FILTER_UP: DecodeUpFilter(curr, prior, bytesPerRow); break; case PNG_FILTER_AVERAGE: DecodeAverageFilter(curr, prior, bytesPerRow, bytesPerPixel); break; case PNG_FILTER_PAETH: DecodePaethFilter(curr, prior, bytesPerRow, bytesPerPixel); break; default: // Error -- uknown filter type throw new Exception(MessageLocalization.GetComposedMessage("png.filter.unknown")); } ProcessPixels(curr, xOffset, xStep, dstY, passWidth); // Swap curr and prior byte[] tmp = prior; prior = curr; curr = tmp; } }
/** Throws an exception */ private void ThrowException(String s) { throw new IOException(MessageLocalization.GetComposedMessage("1.near.line.2.column.3", s, lines, columns)); }
/** * This will parse the stream and create a cmap object. * * @param input The CMAP stream to parse. * @return The parsed stream as a java object. * * @throws IOException If there is an error parsing the stream. */ public CMap Parse(Stream input) { PushbackStream cmapStream = new PushbackStream(input); CMap result = new CMap(); Object previousToken = null; Object token = null; while ((token = ParseNextToken(cmapStream)) != null) { if (token is Operator) { Operator op = (Operator)token; if (op.op.Equals(BEGIN_CODESPACE_RANGE)) { IConvertible cosCount = (IConvertible)previousToken; for (int j = 0; j < cosCount.ToInt32(CultureInfo.InvariantCulture); j++) { byte[] startRange = (byte[])ParseNextToken(cmapStream); byte[] endRange = (byte[])ParseNextToken(cmapStream); CodespaceRange range = new CodespaceRange(); range.SetStart(startRange); range.SetEnd(endRange); result.AddCodespaceRange(range); } } else if (op.op.Equals(BEGIN_BASE_FONT_CHAR)) { IConvertible cosCount = (IConvertible)previousToken; for (int j = 0; j < cosCount.ToInt32(CultureInfo.InvariantCulture); j++) { byte[] inputCode = (byte[])ParseNextToken(cmapStream); Object nextToken = ParseNextToken(cmapStream); if (nextToken is byte[]) { byte[] bytes = (byte[])nextToken; String value = CreateStringFromBytes(bytes); result.AddMapping(inputCode, value); } else if (nextToken is LiteralName) { result.AddMapping(inputCode, ((LiteralName)nextToken).name); } else { throw new IOException(MessageLocalization.GetComposedMessage("error.parsing.cmap.beginbfchar.expected.cosstring.or.cosname.and.not.1", nextToken)); } } } else if (op.op.Equals(BEGIN_BASE_FONT_RANGE)) { IConvertible cosCount = (IConvertible)previousToken; for (int j = 0; j < cosCount.ToInt32(CultureInfo.InvariantCulture); j++) { byte[] startCode = (byte[])ParseNextToken(cmapStream); byte[] endCode = (byte[])ParseNextToken(cmapStream); Object nextToken = ParseNextToken(cmapStream); IList <byte[]> array = null; byte[] tokenBytes = null; if (nextToken is IList <byte[]> ) { array = (IList <byte[]>)nextToken; tokenBytes = array[0]; } else { tokenBytes = (byte[])nextToken; } String value = null; int arrayIndex = 0; bool done = false; while (!done) { if (Compare(startCode, endCode) >= 0) { done = true; } value = CreateStringFromBytes(tokenBytes); result.AddMapping(startCode, value); Increment(startCode); if (array == null) { Increment(tokenBytes); } else { arrayIndex++; if (arrayIndex < array.Count) { tokenBytes = array[arrayIndex]; } } } } } } previousToken = token; } return(result); }