From 47560bc308d81aab8bc16f7205f0b895b2c640ef Mon Sep 17 00:00:00 2001 From: VahidN Date: Sun, 24 Nov 2024 22:31:24 +0330 Subject: [PATCH] Apply CA1859: Change type of field from INullValueDictionary to NullValueDictionary for improved performance --- .../System/util/Properties.cs | 38 +- .../text/html/simpleparser/IncTable.cs | 21 +- .../iTextSharp/text/pdf/AcroFields.cs | 264 ++++---- .../iTextSharp/text/pdf/BarcodeDatamatrix.cs | 495 +++++++------- .../iTextSharp/text/pdf/GlyphList.cs | 33 +- .../iTextSharp/text/pdf/ICC_Profile.cs | 79 +-- .../iTextSharp/text/pdf/PdfContentByte.cs | 611 +++++++++--------- .../iTextSharp/text/pdf/PdfCopyFieldsImp.cs | 142 ++-- .../iTextSharp/text/pdf/PdfPKCS7.cs | 316 +++++---- .../iTextSharp/text/pdf/PdfSmartCopy.cs | 45 +- .../iTextSharp/text/pdf/SimpleBookmark.cs | 217 +++---- .../text/pdf/SimpleNamedDestination.cs | 66 +- .../iTextSharp/text/pdf/Type1Font.cs | 121 ++-- .../iTextSharp/text/pdf/Type3Font.cs | 56 +- .../iTextSharp/text/pdf/events/IndexEvents.cs | 49 +- .../text/rtf/parser/RtfImportMappings.cs | 27 +- .../destinations/RtfDestinationColorTable.cs | 20 +- .../destinations/RtfDestinationFontTable.cs | 188 +++--- 18 files changed, 1482 insertions(+), 1306 deletions(-) diff --git a/src/iTextSharp.LGPLv2.Core/System/util/Properties.cs b/src/iTextSharp.LGPLv2.Core/System/util/Properties.cs index 156836a..e465dc3 100644 --- a/src/iTextSharp.LGPLv2.Core/System/util/Properties.cs +++ b/src/iTextSharp.LGPLv2.Core/System/util/Properties.cs @@ -26,10 +26,7 @@ public virtual string this[string key] set => _col[key] = value; } - public virtual void Add(string key, string value) - { - _col[key] = value; - } + public virtual void Add(string key, string value) => _col[key] = value; public void AddAll(Properties col) { @@ -44,10 +41,7 @@ public void AddAll(Properties col) } } - public void Clear() - { - _col.Clear(); - } + public void Clear() => _col.Clear(); public bool ContainsKey(string key) => _col.ContainsKey(key); @@ -55,11 +49,13 @@ public void Clear() public void Load(Stream inStream) { - using var inp = new StreamReader(inStream, EncodingsRegistry.GetEncoding(1252)); + using var inp = new StreamReader(inStream, EncodingsRegistry.GetEncoding(codepage: 1252)); + while (true) { // Get next line var line = inp.ReadLine(); + if (line == null) { return; @@ -70,6 +66,7 @@ public void Load(Stream inStream) // Find start of key var len = line.Length; int keyStart; + for (keyStart = 0; keyStart < len; keyStart++) { if (WhiteSpaceChars.IndexOf(line[keyStart].ToString(), StringComparison.Ordinal) == -1) @@ -86,19 +83,23 @@ public void Load(Stream inStream) // Continue lines that end in slashes if they are not comments var firstChar = line[keyStart]; + if (firstChar != '#' && firstChar != '!') { while (continueLine(line)) { var nextLine = inp.ReadLine(); + if (nextLine == null) { nextLine = ""; } - var loppedLine = line.Substring(0, len - 1); + var loppedLine = line.Substring(startIndex: 0, len - 1); + // Advance beyond whitespace on new line int startIndex; + for (startIndex = 0; startIndex < nextLine.Length; startIndex++) { if (WhiteSpaceChars.IndexOf(nextLine[startIndex].ToString(), StringComparison.Ordinal) == @@ -108,16 +109,18 @@ public void Load(Stream inStream) } } - nextLine = nextLine.Substring(startIndex, nextLine.Length - startIndex); + nextLine = nextLine.Substring(startIndex); line = loppedLine + nextLine; len = line.Length; } // Find separation between key and value int separatorIndex; + for (separatorIndex = keyStart; separatorIndex < len; separatorIndex++) { var currentChar = line[separatorIndex]; + if (currentChar == '\\') { separatorIndex++; @@ -130,6 +133,7 @@ public void Load(Stream inStream) // Skip over whitespace after key if any int valueIndex; + for (valueIndex = separatorIndex; valueIndex < len; valueIndex++) { if (WhiteSpaceChars.IndexOf(line[valueIndex].ToString(), StringComparison.Ordinal) == -1) @@ -175,6 +179,7 @@ public string Remove(string key) { var retval = _col[key]; _col.Remove(key); + return retval; } @@ -182,6 +187,7 @@ private static bool continueLine(string line) { var slashCount = 0; var index = line.Length - 1; + while (index >= 0 && line[index--] == '\\') { slashCount++; @@ -203,16 +209,20 @@ private static string loadConvert(string theString) for (var x = 0; x < len;) { aChar = theString[x++]; + if (aChar == '\\') { aChar = theString[x++]; + if (aChar == 'u') { // Read the xxxx var value = 0; + for (var i = 0; i < 4; i++) { aChar = theString[x++]; + switch (aChar) { case '0': @@ -226,6 +236,7 @@ private static string loadConvert(string theString) case '8': case '9': value = (value << 4) + aChar - '0'; + break; case 'a': case 'b': @@ -234,6 +245,7 @@ private static string loadConvert(string theString) case 'e': case 'f': value = (value << 4) + 10 + aChar - 'a'; + break; case 'A': case 'B': @@ -242,10 +254,10 @@ private static string loadConvert(string theString) case 'E': case 'F': value = (value << 4) + 10 + aChar - 'A'; + break; default: - throw new ArgumentException( - "Malformed \\uxxxx encoding."); + throw new ArgumentException(message: "Malformed \\uxxxx encoding."); } } diff --git a/src/iTextSharp.LGPLv2.Core/iTextSharp/text/html/simpleparser/IncTable.cs b/src/iTextSharp.LGPLv2.Core/iTextSharp/text/html/simpleparser/IncTable.cs index d6c58ee..4d96d01 100644 --- a/src/iTextSharp.LGPLv2.Core/iTextSharp/text/html/simpleparser/IncTable.cs +++ b/src/iTextSharp.LGPLv2.Core/iTextSharp/text/html/simpleparser/IncTable.cs @@ -8,7 +8,7 @@ namespace iTextSharp.text.html.simpleparser; /// public class IncTable : IElement { - private readonly INullValueDictionary _props = new NullValueDictionary(); + private readonly NullValueDictionary _props = new(); private List _cols; /// @@ -65,12 +65,13 @@ public PdfPTable BuildTable() { if (Rows.Count == 0) { - return new PdfPTable(1); + return new PdfPTable(numColumns: 1); } var ncol = 0; - var c0 = Rows[0]; + var c0 = Rows[index: 0]; + for (var k = 0; k < c0.Count; ++k) { ncol += c0[k].Colspan; @@ -78,10 +79,12 @@ public PdfPTable BuildTable() var table = new PdfPTable(ncol); - var widths = _props["widths"]; + var widths = _props[key: "widths"]; + if (widths != null) { var intWidths = new List(); + foreach (var widthElement in widths.Split(',')) { intWidths.Add(int.Parse(widthElement, CultureInfo.InvariantCulture)); @@ -90,17 +93,18 @@ public PdfPTable BuildTable() table.SetWidths(intWidths.ToArray()); } - var width = _props["width"]; + var width = _props[key: "width"]; + if (width == null) { table.WidthPercentage = 100; } else { - if (width.EndsWith("%", StringComparison.OrdinalIgnoreCase)) + if (width.EndsWith(value: "%", StringComparison.OrdinalIgnoreCase)) { - table.WidthPercentage = - float.Parse(width.Substring(0, width.Length - 1), NumberFormatInfo.InvariantInfo); + table.WidthPercentage = float.Parse(width.Substring(startIndex: 0, width.Length - 1), + NumberFormatInfo.InvariantInfo); } else { @@ -112,6 +116,7 @@ public PdfPTable BuildTable() for (var row = 0; row < Rows.Count; ++row) { var col = Rows[row]; + for (var k = 0; k < col.Count; ++k) { table.AddCell(col[k]); diff --git a/src/iTextSharp.LGPLv2.Core/iTextSharp/text/pdf/AcroFields.cs b/src/iTextSharp.LGPLv2.Core/iTextSharp/text/pdf/AcroFields.cs index 29fca37..2c8707b 100644 --- a/src/iTextSharp.LGPLv2.Core/iTextSharp/text/pdf/AcroFields.cs +++ b/src/iTextSharp.LGPLv2.Core/iTextSharp/text/pdf/AcroFields.cs @@ -59,12 +59,11 @@ public class AcroFields PdfName.Mk, PdfName.F, PdfName.Ff, PdfName.Q, PdfName.Bs, PdfName.Border }; - private static readonly INullValueDictionary _stdFieldFontNames = - new NullValueDictionary(); + private static readonly NullValueDictionary _stdFieldFontNames = new(); private readonly bool _append; private readonly NullValueDictionary _extensionFonts = new(); - private readonly INullValueDictionary _localFonts = new NullValueDictionary(); + private readonly NullValueDictionary _localFonts = new(); internal readonly PdfReader Reader; internal readonly PdfWriter Writer; private float _extraMarginLeft; @@ -89,107 +88,107 @@ public class AcroFields static AcroFields() { - _stdFieldFontNames["CoBO"] = new[] + _stdFieldFontNames[key: "CoBO"] = new[] { "Courier-BoldOblique" }; - _stdFieldFontNames["CoBo"] = new[] + _stdFieldFontNames[key: "CoBo"] = new[] { "Courier-Bold" }; - _stdFieldFontNames["CoOb"] = new[] + _stdFieldFontNames[key: "CoOb"] = new[] { "Courier-Oblique" }; - _stdFieldFontNames["Cour"] = new[] + _stdFieldFontNames[key: "Cour"] = new[] { "Courier" }; - _stdFieldFontNames["HeBO"] = new[] + _stdFieldFontNames[key: "HeBO"] = new[] { "Helvetica-BoldOblique" }; - _stdFieldFontNames["HeBo"] = new[] + _stdFieldFontNames[key: "HeBo"] = new[] { "Helvetica-Bold" }; - _stdFieldFontNames["HeOb"] = new[] + _stdFieldFontNames[key: "HeOb"] = new[] { "Helvetica-Oblique" }; - _stdFieldFontNames["Helv"] = new[] + _stdFieldFontNames[key: "Helv"] = new[] { "Helvetica" }; - _stdFieldFontNames["Symb"] = new[] + _stdFieldFontNames[key: "Symb"] = new[] { "Symbol" }; - _stdFieldFontNames["TiBI"] = new[] + _stdFieldFontNames[key: "TiBI"] = new[] { "Times-BoldItalic" }; - _stdFieldFontNames["TiBo"] = new[] + _stdFieldFontNames[key: "TiBo"] = new[] { "Times-Bold" }; - _stdFieldFontNames["TiIt"] = new[] + _stdFieldFontNames[key: "TiIt"] = new[] { "Times-Italic" }; - _stdFieldFontNames["TiRo"] = new[] + _stdFieldFontNames[key: "TiRo"] = new[] { "Times-Roman" }; - _stdFieldFontNames["ZaDb"] = new[] + _stdFieldFontNames[key: "ZaDb"] = new[] { "ZapfDingbats" }; - _stdFieldFontNames["HySm"] = new[] + _stdFieldFontNames[key: "HySm"] = new[] { "HYSMyeongJo-Medium", "UniKS-UCS2-H" }; - _stdFieldFontNames["HyGo"] = new[] + _stdFieldFontNames[key: "HyGo"] = new[] { "HYGoThic-Medium", "UniKS-UCS2-H" }; - _stdFieldFontNames["KaGo"] = new[] + _stdFieldFontNames[key: "KaGo"] = new[] { "HeiseiKakuGo-W5", "UniKS-UCS2-H" }; - _stdFieldFontNames["KaMi"] = new[] + _stdFieldFontNames[key: "KaMi"] = new[] { "HeiseiMin-W3", "UniJIS-UCS2-H" }; - _stdFieldFontNames["MHei"] = new[] + _stdFieldFontNames[key: "MHei"] = new[] { "MHei-Medium", "UniCNS-UCS2-H" }; - _stdFieldFontNames["MSun"] = new[] + _stdFieldFontNames[key: "MSun"] = new[] { "MSung-Light", "UniCNS-UCS2-H" }; - _stdFieldFontNames["STSo"] = new[] + _stdFieldFontNames[key: "STSo"] = new[] { "STSong-Light", "UniGB-UCS2-H" }; @@ -296,7 +295,7 @@ public int TotalRevisions public static object[] SplitDAelements(string da) { - var tk = new PrTokeniser(PdfEncodings.ConvertToBytes(da, null)); + var tk = new PrTokeniser(PdfEncodings.ConvertToBytes(da, encoding: null)); var stack = new List(); var ret = new object[3]; @@ -311,7 +310,7 @@ public static object[] SplitDAelements(string da) { var oper = tk.StringValue; - if (oper.Equals("Tf", StringComparison.Ordinal)) + if (oper.Equals(value: "Tf", StringComparison.Ordinal)) { if (stack.Count >= 2) { @@ -319,19 +318,19 @@ public static object[] SplitDAelements(string da) ret[DA_SIZE] = float.Parse(stack[stack.Count - 1], NumberFormatInfo.InvariantInfo); } } - else if (oper.Equals("g", StringComparison.Ordinal)) + else if (oper.Equals(value: "g", StringComparison.Ordinal)) { if (stack.Count >= 1) { var gray = float.Parse(stack[stack.Count - 1], NumberFormatInfo.InvariantInfo); - if (gray.ApproxNotEqual(0)) + if (gray.ApproxNotEqual(b: 0)) { ret[DA_COLOR] = new GrayColor(gray); } } } - else if (oper.Equals("rg", StringComparison.Ordinal)) + else if (oper.Equals(value: "rg", StringComparison.Ordinal)) { if (stack.Count >= 3) { @@ -341,7 +340,7 @@ public static object[] SplitDAelements(string da) ret[DA_COLOR] = new BaseColor(red, green, blue); } } - else if (oper.Equals("k", StringComparison.Ordinal)) + else if (oper.Equals(value: "k", StringComparison.Ordinal)) { if (stack.Count >= 4) { @@ -454,8 +453,9 @@ public void DecodeGenericDictionary(PdfDictionary merged, BaseField tx) { try { - porf = BaseFont.CreateFont("font.ttf", BaseFont.IDENTITY_H, true, false, - PdfReader.GetStreamBytes(prs), null); + porf = BaseFont.CreateFont(name: "font.ttf", BaseFont.IDENTITY_H, + embedded: true, cached: false, PdfReader.GetStreamBytes(prs), + pfb: null); } catch { @@ -491,7 +491,7 @@ public void DecodeGenericDictionary(PdfDictionary merged, BaseField tx) enc = fn[1]; } - bf = BaseFont.CreateFont(fn[0], enc, false); + bf = BaseFont.CreateFont(fn[0], enc, embedded: false); tx.Font = bf; } catch @@ -635,7 +635,7 @@ public void DecodeGenericDictionary(PdfDictionary merged, BaseField tx) { if (bd.Size >= 3) { - tx.BorderWidth = bd.GetAsNumber(2).FloatValue; + tx.BorderWidth = bd.GetAsNumber(idx: 2).FloatValue; } if (bd.Size >= 4) @@ -661,7 +661,7 @@ public void ExportAsFdf(FdfWriter writer) { var item = entry.Value; var name = entry.Key; - var v = item.GetMerged(0).Get(PdfName.V); + var v = item.GetMerged(idx: 0).Get(PdfName.V); if (v == null) { @@ -701,7 +701,7 @@ public Stream ExtractRevision(string field) var length = value[0]; var raf = Reader.SafeFile; raf.ReOpen(); - raf.Seek(0); + raf.Seek(pos: 0); return new RevisionStream(raf, length); } @@ -724,7 +724,7 @@ public string[] GetAppearanceStates(string fieldName) } var names = new NullValueDictionary(); - var vals = fd.GetValue(0); + var vals = fd.GetValue(idx: 0); var stringOpt = vals.GetAsString(PdfName.Opt); if (stringOpt != null) @@ -774,7 +774,7 @@ public string[] GetAppearanceStates(string fieldName) } var outs = new string[names.Count]; - names.Keys.CopyTo(outs, 0); + names.Keys.CopyTo(outs, index: 0); return outs; } @@ -791,7 +791,7 @@ public IList GetBlankSignatureNames() foreach (var entry in fields) { var item = entry.Value; - var merged = item.GetMerged(0); + var merged = item.GetMerged(idx: 0); if (!PdfName.Sig.Equals(merged.GetAsName(PdfName.Ft))) { @@ -838,7 +838,7 @@ public string GetField(string name) } _lastWasString = false; - var mergedDict = item.GetMerged(0); + var mergedDict = item.GetMerged(idx: 0); // Jose A. Rodriguez posted a fix to the mailing list (May 11, 2009) // explaining that the value can also be a stream value @@ -885,7 +885,7 @@ public string GetField(string name) value = ((PdfString)v).ToUnicodeString(); } - var opts = item.GetValue(0).GetAsArray(PdfName.Opt); + var opts = item.GetValue(idx: 0).GetAsArray(PdfName.Opt); if (opts != null) { @@ -1016,7 +1016,7 @@ public float[] GetFieldPositions(string name) if (ptr < ret.Length) { var ret2 = new float[ptr]; - Array.Copy(ret, 0, ret2, 0, ptr); + Array.Copy(ret, sourceIndex: 0, ret2, destinationIndex: 0, ptr); return ret2; } @@ -1043,7 +1043,7 @@ public int GetFieldType(string fieldName) return FIELD_TYPE_NONE; } - var merged = fd.GetMerged(0); + var merged = fd.GetMerged(idx: 0); var type = merged.GetAsName(PdfName.Ft); if (type == null) @@ -1104,8 +1104,7 @@ public int GetFieldType(string fieldName) /// /// the field name /// the list of export option values from fields of type list or combo - public string[] GetListOptionDisplay(string fieldName) - => getListOption(fieldName, 1); + public string[] GetListOptionDisplay(string fieldName) => getListOption(fieldName, idx: 1); /// /// Gets the list of export option values from fields of type list or combo. @@ -1114,8 +1113,7 @@ public string[] GetListOptionDisplay(string fieldName) /// /// the field name /// the list of export option values from fields of type list or combo - public string[] GetListOptionExport(string fieldName) - => getListOption(fieldName, 0); + public string[] GetListOptionExport(string fieldName) => getListOption(fieldName, idx: 0); /// /// Gets the field values of a Choice field. @@ -1141,7 +1139,7 @@ public string[] GetListSelection(string name) return ret; } - var values = item.GetMerged(0).GetAsArray(PdfName.I); + var values = item.GetMerged(idx: 0).GetAsArray(PdfName.I); if (values == null) { @@ -1169,8 +1167,7 @@ public string[] GetListSelection(string name) /// /// the field name that should be a pushbutton /// a new pushbutton or null if the field is not a pushbutton - public PushbuttonField GetNewPushbuttonFromField(string field) - => GetNewPushbuttonFromField(field, 0); + public PushbuttonField GetNewPushbuttonFromField(string field) => GetNewPushbuttonFromField(field, order: 0); /// /// Creates a new pushbutton from an existing field. This pushbutton can be changed and be used to replace @@ -1198,7 +1195,7 @@ public PushbuttonField GetNewPushbuttonFromField(string field, int order) var posi = order * 5; var pos = GetFieldPositions(field); var box = new Rectangle(pos[posi + 1], pos[posi + 2], pos[posi + 3], pos[posi + 4]); - var newButton = new PushbuttonField(Writer, box, null); + var newButton = new PushbuttonField(Writer, box, fieldName: null); var dic = item.GetMerged(order); DecodeGenericDictionary(dic, newButton); var mk = dic.GetAsDict(PdfName.Mk); @@ -1259,8 +1256,8 @@ public PushbuttonField GetNewPushbuttonFromField(string field, int order) if (aj != null && aj.Size == 2) { - var left = aj.GetAsNumber(0).FloatValue; - var bottom = aj.GetAsNumber(1).FloatValue; + var left = aj.GetAsNumber(idx: 0).FloatValue; + var bottom = aj.GetAsNumber(idx: 1).FloatValue; newButton.IconHorizontalAdjustment = left; newButton.IconVerticalAdjustment = bottom; } @@ -1319,7 +1316,7 @@ public PdfDictionary GetSignatureDictionary(string name) } var item = fields[name]; - var merged = item.GetMerged(0); + var merged = item.GetMerged(idx: 0); return merged.GetAsDict(PdfName.V); } @@ -1508,8 +1505,7 @@ public bool RemoveField(string name, int page) /// /// the field name /// true if the field exists, false otherwise - public bool RemoveField(string name) - => RemoveField(name, -1); + public bool RemoveField(string name) => RemoveField(name, page: -1); /// /// Removes all the fields from page . @@ -1524,7 +1520,7 @@ public bool RemoveFieldsFromPage(int page) } var names = new string[fields.Count]; - fields.Keys.CopyTo(names, 0); + fields.Keys.CopyTo(names, arrayIndex: 0); var found = false; for (var k = 0; k < names.Length; ++k) @@ -1556,15 +1552,16 @@ public bool RenameField(string oldName, string newName) throw new ArgumentNullException(nameof(newName)); } - var idx1 = oldName.LastIndexOf(".", StringComparison.Ordinal) + 1; - var idx2 = newName.LastIndexOf(".", StringComparison.Ordinal) + 1; + var idx1 = oldName.LastIndexOf(value: ".", StringComparison.Ordinal) + 1; + var idx2 = newName.LastIndexOf(value: ".", StringComparison.Ordinal) + 1; if (idx1 != idx2) { return false; } - if (!oldName.Substring(0, idx1).Equals(newName.Substring(0, idx2), StringComparison.Ordinal)) + if (!oldName.Substring(startIndex: 0, idx1) + .Equals(newName.Substring(startIndex: 0, idx2), StringComparison.Ordinal)) { return false; } @@ -1601,7 +1598,7 @@ public bool RenameField(string oldName, string newName) /// the PdfFormField representing the pushbutton /// true if the field was replaced, false if the field public bool ReplacePushbuttonField(string field, PdfFormField button) - => ReplacePushbuttonField(field, button, 0); + => ReplacePushbuttonField(field, button, order: 0); /// /// Replaces the designated field with a new pushbutton. The pushbutton can be created with @@ -1685,8 +1682,7 @@ public void SetExtraMargin(float extraMarginLeft, float extraMarginTop) /// the fully qualified field name or the partial name in the case of XFA forms /// the field value /// true if the field was found and changed, - public bool SetField(string name, string value) - => SetField(name, value, null); + public bool SetField(string name, string value) => SetField(name, value, display: null); /// /// Sets the field value and the display string. The display string @@ -1711,7 +1707,7 @@ public bool SetField(string name, string value, string display) if (Writer == null) { - throw new DocumentException("This AcroFields instance is read-only."); + throw new DocumentException(message: "This AcroFields instance is read-only."); } if (Xfa.XfaPresent) @@ -1741,7 +1737,7 @@ public bool SetField(string name, string value, string display) return false; } - var merged = item.GetMerged(0); + var merged = item.GetMerged(idx: 0); var type = merged.GetAsName(PdfName.Ft); if (PdfName.Tx.Equals(type)) @@ -1756,7 +1752,7 @@ public bool SetField(string name, string value, string display) if (len > 0) { - value = value.Substring(0, Math.Min(len, value.Length)); + value = value.Substring(startIndex: 0, Math.Min(len, value.Length)); } } @@ -1817,7 +1813,7 @@ public bool SetField(string name, string value, string display) if (PdfName.Btn.Equals(type)) { - var ff = item.GetMerged(0).GetAsNumber(PdfName.Ff); + var ff = item.GetMerged(idx: 0).GetAsNumber(PdfName.Ff); var flags = 0; if (ff != null) @@ -1848,7 +1844,7 @@ public bool SetField(string name, string value, string display) var v = new PdfName(value); var lopt = new List(); - var opts = item.GetValue(0).GetAsArray(PdfName.Opt); + var opts = item.GetValue(idx: 0).GetAsArray(PdfName.Opt); if (opts != null) { @@ -1862,7 +1858,7 @@ public bool SetField(string name, string value, string display) } else { - lopt.Add(null); + lopt.Add(item: null); } } } @@ -1939,7 +1935,7 @@ public bool SetFieldProperty(string field, string name, object value, int[] inst { if (Writer == null) { - throw new InvalidOperationException("This AcroFields instance is read-only."); + throw new InvalidOperationException(message: "This AcroFields instance is read-only."); } var item = fields[field]; @@ -1953,7 +1949,7 @@ public bool SetFieldProperty(string field, string name, object value, int[] inst PdfDictionary merged; PdfString da; - if (Util.EqualsIgnoreCase(name, "textfont")) + if (Util.EqualsIgnoreCase(name, s2: "textfont")) { for (var k = 0; k < item.Size; ++k) { @@ -2027,13 +2023,13 @@ public bool SetFieldProperty(string field, string name, object value, int[] inst if (bf.FontType == BaseFont.FONT_TYPE_DOCUMENT) { - fd = new FontDetails(null, ((DocumentFont)bf).IndirectReference, bf); + fd = new FontDetails(fontName: null, ((DocumentFont)bf).IndirectReference, bf); } else { bf.Subset = false; fd = Writer.AddSimple(bf); - _localFonts[psn.ToString().Substring(1)] = bf; + _localFonts[psn.ToString().Substring(startIndex: 1)] = bf; } fontsTop.Put(psn, fd.IndirectReference); @@ -2041,7 +2037,7 @@ public bool SetFieldProperty(string field, string name, object value, int[] inst } var buf = cb.InternalBuffer; - buf.Append(psn.GetBytes()).Append(' ').Append((float)dao[DA_SIZE]).Append(" Tf "); + buf.Append(psn.GetBytes()).Append(c: ' ').Append((float)dao[DA_SIZE]).Append(str: " Tf "); if (dao[DA_COLOR] != null) { @@ -2057,7 +2053,7 @@ public bool SetFieldProperty(string field, string name, object value, int[] inst } } } - else if (Util.EqualsIgnoreCase(name, "textcolor")) + else if (Util.EqualsIgnoreCase(name, s2: "textcolor")) { for (var k = 0; k < item.Size; ++k) { @@ -2075,8 +2071,10 @@ public bool SetFieldProperty(string field, string name, object value, int[] inst { var buf = cb.InternalBuffer; - buf.Append(new PdfName((string)dao[DA_FONT]).GetBytes()).Append(' ') - .Append((float)dao[DA_SIZE]).Append(" Tf "); + buf.Append(new PdfName((string)dao[DA_FONT]).GetBytes()) + .Append(c: ' ') + .Append((float)dao[DA_SIZE]) + .Append(str: " Tf "); cb.SetColorFill((BaseColor)value); var s = new PdfString(cb.ToString()); @@ -2088,7 +2086,7 @@ public bool SetFieldProperty(string field, string name, object value, int[] inst } } } - else if (Util.EqualsIgnoreCase(name, "textsize")) + else if (Util.EqualsIgnoreCase(name, s2: "textsize")) { for (var k = 0; k < item.Size; ++k) { @@ -2106,8 +2104,10 @@ public bool SetFieldProperty(string field, string name, object value, int[] inst { var buf = cb.InternalBuffer; - buf.Append(new PdfName((string)dao[DA_FONT]).GetBytes()).Append(' ').Append((float)value) - .Append(" Tf "); + buf.Append(new PdfName((string)dao[DA_FONT]).GetBytes()) + .Append(c: ' ') + .Append((float)value) + .Append(str: " Tf "); if (dao[DA_COLOR] != null) { @@ -2123,9 +2123,9 @@ public bool SetFieldProperty(string field, string name, object value, int[] inst } } } - else if (Util.EqualsIgnoreCase(name, "bgcolor") || Util.EqualsIgnoreCase(name, "bordercolor")) + else if (Util.EqualsIgnoreCase(name, s2: "bgcolor") || Util.EqualsIgnoreCase(name, s2: "bordercolor")) { - var dname = Util.EqualsIgnoreCase(name, "bgcolor") ? PdfName.Bg : PdfName.Bc; + var dname = Util.EqualsIgnoreCase(name, s2: "bgcolor") ? PdfName.Bg : PdfName.Bc; for (var k = 0; k < item.Size; ++k) { @@ -2197,7 +2197,7 @@ public bool SetFieldProperty(string field, string name, int value, int[] inst) { if (Writer == null) { - throw new InvalidOperationException("This AcroFields instance is read-only."); + throw new InvalidOperationException(message: "This AcroFields instance is read-only."); } var item = fields[field]; @@ -2209,7 +2209,7 @@ public bool SetFieldProperty(string field, string name, int value, int[] inst) var hit = new InstHit(inst); - if (Util.EqualsIgnoreCase(name, "flags")) + if (Util.EqualsIgnoreCase(name, s2: "flags")) { var num = new PdfNumber(value); @@ -2223,7 +2223,7 @@ public bool SetFieldProperty(string field, string name, int value, int[] inst) } } } - else if (Util.EqualsIgnoreCase(name, "setflags")) + else if (Util.EqualsIgnoreCase(name, s2: "setflags")) { for (var k = 0; k < item.Size; ++k) { @@ -2244,7 +2244,7 @@ public bool SetFieldProperty(string field, string name, int value, int[] inst) } } } - else if (Util.EqualsIgnoreCase(name, "clrflags")) + else if (Util.EqualsIgnoreCase(name, s2: "clrflags")) { for (var k = 0; k < item.Size; ++k) { @@ -2266,7 +2266,7 @@ public bool SetFieldProperty(string field, string name, int value, int[] inst) } } } - else if (Util.EqualsIgnoreCase(name, "fflags")) + else if (Util.EqualsIgnoreCase(name, s2: "fflags")) { var num = new PdfNumber(value); @@ -2280,7 +2280,7 @@ public bool SetFieldProperty(string field, string name, int value, int[] inst) } } } - else if (Util.EqualsIgnoreCase(name, "setfflags")) + else if (Util.EqualsIgnoreCase(name, s2: "setfflags")) { for (var k = 0; k < item.Size; ++k) { @@ -2302,7 +2302,7 @@ public bool SetFieldProperty(string field, string name, int value, int[] inst) } } } - else if (Util.EqualsIgnoreCase(name, "clrfflags")) + else if (Util.EqualsIgnoreCase(name, s2: "clrfflags")) { for (var k = 0; k < item.Size; ++k) { @@ -2412,7 +2412,7 @@ public bool SetListOption(string fieldName, string[] exportValues, string[] disp if (exportValues != null && displayValues != null && exportValues.Length != displayValues.Length) { - throw new ArgumentException("The export and the display array must have the same size."); + throw new ArgumentException(message: "The export and the display array must have the same size."); } var ftype = GetFieldType(fieldName); @@ -2484,7 +2484,7 @@ public bool SetListSelection(string name, string[] value) return false; } - var type = item.GetMerged(0).GetAsName(PdfName.Ft); + var type = item.GetMerged(idx: 0).GetAsName(PdfName.Ft); if (!PdfName.Ch.Equals(type)) { @@ -2506,8 +2506,8 @@ public bool SetListSelection(string name, string[] value) } item.WriteToAll(PdfName.I, array, Item.WRITE_MERGED | Item.WRITE_VALUE); - item.WriteToAll(PdfName.V, null, Item.WRITE_MERGED | Item.WRITE_VALUE); - item.WriteToAll(PdfName.Ap, null, Item.WRITE_MERGED | Item.WRITE_WIDGET); + item.WriteToAll(PdfName.V, value: null, Item.WRITE_MERGED | Item.WRITE_VALUE); + item.WriteToAll(PdfName.Ap, value: null, Item.WRITE_MERGED | Item.WRITE_WIDGET); item.MarkUsed(this, Item.WRITE_VALUE | Item.WRITE_WIDGET); return true; @@ -2695,7 +2695,7 @@ internal void Fill() if (name.Length > 0) { - name = name.Substring(0, name.Length - 1); + name = name.Substring(startIndex: 0, name.Length - 1); } var item = fields[name]; @@ -2780,8 +2780,8 @@ internal void Fill() item.AddWidget(dic); item.AddWidgetRef(arrfds.GetAsIndirectObject(j)); // must be a reference item.AddMerged(dic); - item.AddPage(-1); - item.AddTabOrder(-1); + item.AddPage(pg: -1); + item.AddTabOrder(order: -1); } } @@ -2797,7 +2797,7 @@ internal PdfAppearance GetAppearance(PdfDictionary merged, string text, string f if (_fieldCache == null || !_fieldCache.TryGetValue(fieldName, out var fcValue)) { - tx = new TextField(Writer, null, null); + tx = new TextField(Writer, box: null, fieldName: null); tx.SetExtraMargin(_extraMarginLeft, _extraMarginTop); tx.BorderWidth = 0; tx.SubstitutionFonts = SubstitutionFonts; @@ -2836,7 +2836,7 @@ internal PdfAppearance GetAppearance(PdfDictionary merged, string text, string f if (!PdfName.Ch.Equals(fieldType)) { - throw new DocumentException("An appearance was requested without a variable text field."); + throw new DocumentException(message: "An appearance was requested without a variable text field."); } var opt = merged.GetAsArray(PdfName.Opt); @@ -2871,8 +2871,8 @@ internal PdfAppearance GetAppearance(PdfDictionary merged, string text, string f else { var a = (PdfArray)obj; - choicesExp[k] = a.GetAsString(0).ToUnicodeString(); - choices[k] = a.GetAsString(1).ToUnicodeString(); + choicesExp[k] = a.GetAsString(idx: 0).ToUnicodeString(); + choices[k] = a.GetAsString(idx: 1).ToUnicodeString(); } } @@ -2926,14 +2926,14 @@ internal static BaseColor GetMkColor(PdfArray ar) switch (ar.Size) { case 1: - return new GrayColor(ar.GetAsNumber(0).FloatValue); + return new GrayColor(ar.GetAsNumber(idx: 0).FloatValue); case 3: - return new BaseColor(ExtendedColor.Normalize(ar.GetAsNumber(0).FloatValue), - ExtendedColor.Normalize(ar.GetAsNumber(1).FloatValue), - ExtendedColor.Normalize(ar.GetAsNumber(2).FloatValue)); + return new BaseColor(ExtendedColor.Normalize(ar.GetAsNumber(idx: 0).FloatValue), + ExtendedColor.Normalize(ar.GetAsNumber(idx: 1).FloatValue), + ExtendedColor.Normalize(ar.GetAsNumber(idx: 2).FloatValue)); case 4: - return new CmykColor(ar.GetAsNumber(0).FloatValue, ar.GetAsNumber(1).FloatValue, - ar.GetAsNumber(2).FloatValue, ar.GetAsNumber(3).FloatValue); + return new CmykColor(ar.GetAsNumber(idx: 0).FloatValue, ar.GetAsNumber(idx: 1).FloatValue, + ar.GetAsNumber(idx: 2).FloatValue, ar.GetAsNumber(idx: 3).FloatValue); default: return null; } @@ -2966,7 +2966,7 @@ private void findSignatureNames() foreach (var entry in fields) { var item = entry.Value; - var merged = item.GetMerged(0); + var merged = item.GetMerged(idx: 0); if (!PdfName.Sig.Equals(merged.Get(PdfName.Ft))) { @@ -3045,7 +3045,7 @@ private string[] getListOption(string fieldName, int idx) return null; } - var ar = fd.GetMerged(0).GetAsArray(PdfName.Opt); + var ar = fd.GetMerged(idx: 0).GetAsArray(PdfName.Opt); if (ar == null) { @@ -3138,7 +3138,7 @@ private void updateByteRange(PdfPkcs7 pkcs7, PdfDictionary v) while (length > 0) { - var rd = rf.Read(buf, 0, Math.Min(length, buf.Length)); + var rd = rf.Read(buf, off: 0, Math.Min(length, buf.Length)); if (rd <= 0) { @@ -3146,7 +3146,7 @@ private void updateByteRange(PdfPkcs7 pkcs7, PdfDictionary v) } length -= rd; - pkcs7.Update(buf, 0, rd); + pkcs7.Update(buf, off: 0, rd); } } } @@ -3241,8 +3241,7 @@ public class Item /// /// instance index /// the merged dictionary for the given instance - public PdfDictionary GetMerged(int idx) - => Merged[idx]; + public PdfDictionary GetMerged(int idx) => Merged[idx]; /// /// Retrieve the page number of the given instance @@ -3250,8 +3249,7 @@ public PdfDictionary GetMerged(int idx) /// /// /// remember, pages are "1-indexed", not "0-indexed" like field instances. - public int GetPage(int idx) - => Page[idx]; + public int GetPage(int idx) => Page[idx]; /// /// Gets the tabOrder. @@ -3259,8 +3257,7 @@ public int GetPage(int idx) /// /// /// tab index of the given field instance - public int GetTabOrder(int idx) - => TabOrder[idx]; + public int GetTabOrder(int idx) => TabOrder[idx]; /// /// Retrieve the value dictionary of the given instance @@ -3268,8 +3265,7 @@ public int GetTabOrder(int idx) /// /// instance index /// dictionary storing this instance's value. It may be shared across instances. - public PdfDictionary GetValue(int idx) - => Values[idx]; + public PdfDictionary GetValue(int idx) => Values[idx]; /// /// Retrieve the widget dictionary of the given instance @@ -3277,8 +3273,7 @@ public PdfDictionary GetValue(int idx) /// /// instance index /// The dictionary found in the appropriate page's Annot array. - public PdfDictionary GetWidget(int idx) - => Widgets[idx]; + public PdfDictionary GetWidget(int idx) => Widgets[idx]; /// /// Retrieve the reference to the given instance @@ -3286,8 +3281,7 @@ public PdfDictionary GetWidget(int idx) /// /// instance index /// reference to the given field instance - public PdfIndirectReference GetWidgetRef(int idx) - => WidgetRefs[idx]; + public PdfIndirectReference GetWidgetRef(int idx) => WidgetRefs[idx]; /// /// Mark all the item dictionaries used matching the given flags @@ -3365,55 +3359,48 @@ public void WriteToAll(PdfName key, PdfObject value, int writeFlags) /// @since 2.1.5 /// /// - internal void AddMerged(PdfDictionary mergeDict) - => Merged.Add(mergeDict); + internal void AddMerged(PdfDictionary mergeDict) => Merged.Add(mergeDict); /// /// Adds a page to the current Item. /// @since 2.1.5 /// /// - internal void AddPage(int pg) - => Page.Add(pg); + internal void AddPage(int pg) => Page.Add(pg); /// /// Adds a tab order value to this Item. /// @since 2.1.5 /// /// - internal void AddTabOrder(int order) - => TabOrder.Add(order); + internal void AddTabOrder(int order) => TabOrder.Add(order); /// /// Add a value dict to this Item /// @since 2.1.5 /// /// new value dictionary - internal void AddValue(PdfDictionary value) - => Values.Add(value); + internal void AddValue(PdfDictionary value) => Values.Add(value); /// /// Add a widget dict to this Item /// @since 2.1.5 /// /// - internal void AddWidget(PdfDictionary widget) - => Widgets.Add(widget); + internal void AddWidget(PdfDictionary widget) => Widgets.Add(widget); /// /// Add a widget ref to this Item /// @since 2.1.5 /// /// - internal void AddWidgetRef(PdfIndirectReference widgRef) - => WidgetRefs.Add(widgRef); + internal void AddWidgetRef(PdfIndirectReference widgRef) => WidgetRefs.Add(widgRef); /// /// forces a page value into the Item. /// @since 2.1.5 /// - internal void ForcePage(int idx, int pg) - => Page[idx] = pg; + internal void ForcePage(int idx, int pg) => Page[idx] = pg; /// /// Remove the given instance from this item. It is possible to @@ -3511,7 +3498,7 @@ public override int Read(byte[] buffer, int offset, int count) public override int ReadByte() { - var n = Read(_b, 0, 1); + var n = Read(_b, offset: 0, count: 1); if (n != 1) { @@ -3521,8 +3508,7 @@ public override int ReadByte() return _b[0] & 0xff; } - public override long Seek(long offset, SeekOrigin origin) - => 0; + public override long Seek(long offset, SeekOrigin origin) => 0; public override void SetLength(long value) { diff --git a/src/iTextSharp.LGPLv2.Core/iTextSharp/text/pdf/BarcodeDatamatrix.cs b/src/iTextSharp.LGPLv2.Core/iTextSharp/text/pdf/BarcodeDatamatrix.cs index 42c6b21..a0a8569 100644 --- a/src/iTextSharp.LGPLv2.Core/iTextSharp/text/pdf/BarcodeDatamatrix.cs +++ b/src/iTextSharp.LGPLv2.Core/iTextSharp/text/pdf/BarcodeDatamatrix.cs @@ -85,36 +85,40 @@ public class BarcodeDatamatrix private static readonly DmParams[] _dmSizes = { - new(10, 10, 10, 10, 3, 3, 5), - new(12, 12, 12, 12, 5, 5, 7), - new(8, 18, 8, 18, 5, 5, 7), - new(14, 14, 14, 14, 8, 8, 10), - new(8, 32, 8, 16, 10, 10, 11), - new(16, 16, 16, 16, 12, 12, 12), - new(12, 26, 12, 26, 16, 16, 14), - new(18, 18, 18, 18, 18, 18, 14), - new(20, 20, 20, 20, 22, 22, 18), - new(12, 36, 12, 18, 22, 22, 18), - new(22, 22, 22, 22, 30, 30, 20), - new(16, 36, 16, 18, 32, 32, 24), - new(24, 24, 24, 24, 36, 36, 24), - new(26, 26, 26, 26, 44, 44, 28), - new(16, 48, 16, 24, 49, 49, 28), - new(32, 32, 16, 16, 62, 62, 36), - new(36, 36, 18, 18, 86, 86, 42), - new(40, 40, 20, 20, 114, 114, 48), - new(44, 44, 22, 22, 144, 144, 56), - new(48, 48, 24, 24, 174, 174, 68), - new(52, 52, 26, 26, 204, 102, 42), - new(64, 64, 16, 16, 280, 140, 56), - new(72, 72, 18, 18, 368, 92, 36), - new(80, 80, 20, 20, 456, 114, 48), - new(88, 88, 22, 22, 576, 144, 56), - new(96, 96, 24, 24, 696, 174, 68), - new(104, 104, 26, 26, 816, 136, 56), - new(120, 120, 20, 20, 1050, 175, 68), - new(132, 132, 22, 22, 1304, 163, 62), - new(144, 144, 24, 24, 1558, 156, 62), + new(height: 10, width: 10, heightSection: 10, widthSection: 10, dataSize: 3, dataBlock: 3, errorBlock: 5), + new(height: 12, width: 12, heightSection: 12, widthSection: 12, dataSize: 5, dataBlock: 5, errorBlock: 7), + new(height: 8, width: 18, heightSection: 8, widthSection: 18, dataSize: 5, dataBlock: 5, errorBlock: 7), + new(height: 14, width: 14, heightSection: 14, widthSection: 14, dataSize: 8, dataBlock: 8, errorBlock: 10), + new(height: 8, width: 32, heightSection: 8, widthSection: 16, dataSize: 10, dataBlock: 10, errorBlock: 11), + new(height: 16, width: 16, heightSection: 16, widthSection: 16, dataSize: 12, dataBlock: 12, errorBlock: 12), + new(height: 12, width: 26, heightSection: 12, widthSection: 26, dataSize: 16, dataBlock: 16, errorBlock: 14), + new(height: 18, width: 18, heightSection: 18, widthSection: 18, dataSize: 18, dataBlock: 18, errorBlock: 14), + new(height: 20, width: 20, heightSection: 20, widthSection: 20, dataSize: 22, dataBlock: 22, errorBlock: 18), + new(height: 12, width: 36, heightSection: 12, widthSection: 18, dataSize: 22, dataBlock: 22, errorBlock: 18), + new(height: 22, width: 22, heightSection: 22, widthSection: 22, dataSize: 30, dataBlock: 30, errorBlock: 20), + new(height: 16, width: 36, heightSection: 16, widthSection: 18, dataSize: 32, dataBlock: 32, errorBlock: 24), + new(height: 24, width: 24, heightSection: 24, widthSection: 24, dataSize: 36, dataBlock: 36, errorBlock: 24), + new(height: 26, width: 26, heightSection: 26, widthSection: 26, dataSize: 44, dataBlock: 44, errorBlock: 28), + new(height: 16, width: 48, heightSection: 16, widthSection: 24, dataSize: 49, dataBlock: 49, errorBlock: 28), + new(height: 32, width: 32, heightSection: 16, widthSection: 16, dataSize: 62, dataBlock: 62, errorBlock: 36), + new(height: 36, width: 36, heightSection: 18, widthSection: 18, dataSize: 86, dataBlock: 86, errorBlock: 42), + new(height: 40, width: 40, heightSection: 20, widthSection: 20, dataSize: 114, dataBlock: 114, errorBlock: 48), + new(height: 44, width: 44, heightSection: 22, widthSection: 22, dataSize: 144, dataBlock: 144, errorBlock: 56), + new(height: 48, width: 48, heightSection: 24, widthSection: 24, dataSize: 174, dataBlock: 174, errorBlock: 68), + new(height: 52, width: 52, heightSection: 26, widthSection: 26, dataSize: 204, dataBlock: 102, errorBlock: 42), + new(height: 64, width: 64, heightSection: 16, widthSection: 16, dataSize: 280, dataBlock: 140, errorBlock: 56), + new(height: 72, width: 72, heightSection: 18, widthSection: 18, dataSize: 368, dataBlock: 92, errorBlock: 36), + new(height: 80, width: 80, heightSection: 20, widthSection: 20, dataSize: 456, dataBlock: 114, errorBlock: 48), + new(height: 88, width: 88, heightSection: 22, widthSection: 22, dataSize: 576, dataBlock: 144, errorBlock: 56), + new(height: 96, width: 96, heightSection: 24, widthSection: 24, dataSize: 696, dataBlock: 174, errorBlock: 68), + new(height: 104, width: 104, heightSection: 26, widthSection: 26, dataSize: 816, dataBlock: 136, + errorBlock: 56), + new(height: 120, width: 120, heightSection: 20, widthSection: 20, dataSize: 1050, dataBlock: 175, + errorBlock: 68), + new(height: 132, width: 132, heightSection: 22, widthSection: 22, dataSize: 1304, dataBlock: 163, + errorBlock: 62), + new(height: 144, width: 144, heightSection: 24, widthSection: 24, dataSize: 1558, dataBlock: 156, + errorBlock: 62) }; private int _extOut; @@ -255,9 +259,11 @@ public virtual SKBitmap CreateDrawingImage(Color foreground, Color background) var w = Width + 2 * Ws; var stride = (w + 7) / 8; var bmp = new SKBitmap(w, h); + for (var k = 0; k < h; ++k) { var p = k * stride; + for (var j = 0; j < w; ++j) { var b = BitImage[p + j / 8] & 0xff; @@ -283,7 +289,9 @@ public Image CreateImage() } var g4 = Ccittg4Encoder.Compress(BitImage, Width + 2 * Ws, Height + 2 * Ws); - return Image.GetInstance(Width + 2 * Ws, Height + 2 * Ws, false, Element.CCITTG4, 0, g4, null); + + return Image.GetInstance(Width + 2 * Ws, Height + 2 * Ws, reverseBits: false, Element.CCITTG4, parameters: 0, + g4, transparency: null); } /// @@ -298,8 +306,9 @@ public Image CreateImage() /// the status of the generation. It can be one of this values: public int Generate(string text) { - var t = EncodingsRegistry.GetEncoding(1252).GetBytes(text); - return Generate(t, 0, t.Length); + var t = EncodingsRegistry.GetEncoding(codepage: 1252).GetBytes(text); + + return Generate(t, textOffset: 0, t.Length); } /// @@ -325,23 +334,28 @@ public int Generate(byte[] text, int textOffset, int textSize) var data = new byte[2500]; _extOut = 0; extCount = processExtensions(text, textOffset, textSize, data); + if (extCount < 0) { return DM_ERROR_EXTENSION; } e = -1; + if (Height == 0 || Width == 0) { last = _dmSizes[_dmSizes.Length - 1]; + e = getEncodation(text, textOffset + _extOut, textSize - _extOut, data, extCount, last.DataSize - extCount, - Options, false); + Options, firstMatch: false); + if (e < 0) { return DM_ERROR_TEXT_TOO_BIG; } e += extCount; + for (k = 0; k < _dmSizes.Length; ++k) { if (_dmSizes[k].DataSize >= e) @@ -370,8 +384,10 @@ public int Generate(byte[] text, int textOffset, int textSize) } dm = _dmSizes[k]; + e = getEncodation(text, textOffset + _extOut, textSize - _extOut, data, extCount, dm.DataSize - extCount, - Options, true); + Options, firstMatch: true); + if (e < 0) { return DM_ERROR_TEXT_TOO_BIG; @@ -387,22 +403,30 @@ public int Generate(byte[] text, int textOffset, int textSize) BitImage = new byte[(dm.width + 2 * Ws + 7) / 8 * (dm.height + 2 * Ws)]; makePadding(data, e, dm.DataSize - e); + _place = Placement.DoPlacement(dm.height - dm.height / dm.HeightSection * 2, - dm.width - dm.width / dm.WidthSection * 2); + dm.width - dm.width / dm.WidthSection * 2); + full = dm.DataSize + (dm.DataSize + 2) / dm.DataBlock * dm.ErrorBlock; ReedSolomon.GenerateEcc(data, dm.DataSize, dm.DataBlock, dm.ErrorBlock); draw(data, full, dm); + return DM_NO_ERROR; } - private static int asciiEncodation(byte[] text, int textOffset, int textLength, byte[] data, int dataOffset, - int dataLength) + private static int asciiEncodation(byte[] text, + int textOffset, + int textLength, + byte[] data, + int dataOffset, + int dataLength) { int ptrIn, ptrOut, c; ptrIn = textOffset; ptrOut = dataOffset; textLength += textOffset; dataLength += dataOffset; + while (ptrIn < textLength) { if (ptrOut >= dataLength) @@ -411,6 +435,7 @@ private static int asciiEncodation(byte[] text, int textOffset, int textLength, } c = text[ptrIn++] & 0xff; + if (isDigit(c) && ptrIn < textLength && isDigit(text[ptrIn] & 0xff)) { data[ptrOut++] = (byte)((c - '0') * 10 + (text[ptrIn++] & 0xff) - '0' + 130); @@ -434,10 +459,15 @@ private static int asciiEncodation(byte[] text, int textOffset, int textLength, return ptrOut - dataOffset; } - private static int b256Encodation(byte[] text, int textOffset, int textLength, byte[] data, int dataOffset, - int dataLength) + private static int b256Encodation(byte[] text, + int textOffset, + int textLength, + byte[] data, + int dataOffset, + int dataLength) { int k, j, prn, tv, c; + if (textLength == 0) { return 0; @@ -454,6 +484,7 @@ private static int b256Encodation(byte[] text, int textOffset, int textLength, b } data[dataOffset] = 231; + if (textLength < 250) { data[dataOffset + 1] = (byte)textLength; @@ -468,11 +499,13 @@ private static int b256Encodation(byte[] text, int textOffset, int textLength, b Array.Copy(text, textOffset, data, k + dataOffset, textLength); k += textLength + dataOffset; + for (j = dataOffset + 1; j < k; ++j) { c = data[j] & 0xff; prn = 149 * (j + 1) % 255 + 1; tv = c + prn; + if (tv > 255) { tv -= 256; @@ -484,11 +517,17 @@ private static int b256Encodation(byte[] text, int textOffset, int textLength, b return k - dataOffset; } - private static int c40OrTextEncodation(byte[] text, int textOffset, int textLength, byte[] data, int dataOffset, - int dataLength, bool c40) + private static int c40OrTextEncodation(byte[] text, + int textOffset, + int textLength, + byte[] data, + int dataOffset, + int dataLength, + bool c40) { int ptrIn, ptrOut, encPtr, last0, last1, i, a, c; string basic, shift2, shift3; + if (textLength == 0) { return 0; @@ -496,6 +535,7 @@ private static int c40OrTextEncodation(byte[] text, int textOffset, int textLeng ptrIn = 0; ptrOut = 0; + if (c40) { data[dataOffset + ptrOut++] = 230; @@ -506,6 +546,7 @@ private static int c40OrTextEncodation(byte[] text, int textOffset, int textLeng } shift2 = "!\"#$%&'()*+,-./:;<=>?@[\\]^_"; + if (c40) { basic = " 0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"; @@ -521,6 +562,7 @@ private static int c40OrTextEncodation(byte[] text, int textOffset, int textLeng encPtr = 0; last0 = 0; last1 = 0; + while (ptrIn < textLength) { if (encPtr % 3 == 0) @@ -530,6 +572,7 @@ private static int c40OrTextEncodation(byte[] text, int textOffset, int textLeng } c = text[textOffset + ptrIn++] & 0xff; + if (c > 127) { c -= 128; @@ -538,6 +581,7 @@ private static int c40OrTextEncodation(byte[] text, int textOffset, int textLeng } var idx = basic.IndexOf(((char)c).ToString(), StringComparison.Ordinal); + if (idx >= 0) { enc[encPtr++] = idx + 3; @@ -571,6 +615,7 @@ private static int c40OrTextEncodation(byte[] text, int textOffset, int textLeng } i = 0; + for (; i < encPtr; i += 3) { a = 1600 * enc[i] + 40 * enc[i + 1] + enc[i + 2] + 1; @@ -580,6 +625,7 @@ private static int c40OrTextEncodation(byte[] text, int textOffset, int textLeng data[ptrOut++] = 254; i = asciiEncodation(text, ptrIn, textLength - ptrIn, data, ptrOut, dataLength - ptrOut); + if (i < 0) { return i; @@ -588,10 +634,15 @@ private static int c40OrTextEncodation(byte[] text, int textOffset, int textLeng return ptrOut + i; } - private static int edifactEncodation(byte[] text, int textOffset, int textLength, byte[] data, int dataOffset, - int dataLength) + private static int edifactEncodation(byte[] text, + int textOffset, + int textLength, + byte[] data, + int dataOffset, + int dataLength) { int ptrIn, ptrOut, edi, pedi, c; + if (textLength == 0) { return 0; @@ -602,9 +653,11 @@ private static int edifactEncodation(byte[] text, int textOffset, int textLength edi = 0; pedi = 18; var ascii = true; + for (; ptrIn < textLength; ++ptrIn) { c = text[ptrIn + textOffset] & 0xff; + if (((c & 0xe0) == 0x40 || (c & 0xe0) == 0x20) && c != '_') { if (ascii) @@ -620,6 +673,7 @@ private static int edifactEncodation(byte[] text, int textOffset, int textLength c &= 0x3f; edi |= c << pedi; + if (pedi == 0) { if (ptrOut + 3 > dataLength) @@ -643,12 +697,14 @@ private static int edifactEncodation(byte[] text, int textOffset, int textLength if (!ascii) { edi |= ('_' & 0x3f) << pedi; + if (ptrOut + (3 - pedi / 8) > dataLength) { break; } data[dataOffset + ptrOut++] = (byte)(edi >> 16); + if (pedi <= 12) { data[dataOffset + ptrOut++] = (byte)(edi >> 8); @@ -692,12 +748,14 @@ private static int edifactEncodation(byte[] text, int textOffset, int textLength if (!ascii) { edi |= ('_' & 0x3f) << pedi; + if (ptrOut + (3 - pedi / 8) > dataLength) { return -1; } data[dataOffset + ptrOut++] = (byte)(edi >> 16); + if (pedi <= 12) { data[dataOffset + ptrOut++] = (byte)(edi >> 8); @@ -712,11 +770,18 @@ private static int edifactEncodation(byte[] text, int textOffset, int textLength return ptrOut; } - private static int getEncodation(byte[] text, int textOffset, int textSize, byte[] data, int dataOffset, - int dataSize, int options, bool firstMatch) + private static int getEncodation(byte[] text, + int textOffset, + int textSize, + byte[] data, + int dataOffset, + int dataSize, + int options, + bool firstMatch) { int e, j, k; var e1 = new int[6]; + if (dataSize < 0) { return -1; @@ -724,39 +789,46 @@ private static int getEncodation(byte[] text, int textOffset, int textSize, byte e = -1; options &= 7; + if (options == 0) { e1[0] = asciiEncodation(text, textOffset, textSize, data, dataOffset, dataSize); + if (firstMatch && e1[0] >= 0) { return e1[0]; } - e1[1] = c40OrTextEncodation(text, textOffset, textSize, data, dataOffset, dataSize, false); + e1[1] = c40OrTextEncodation(text, textOffset, textSize, data, dataOffset, dataSize, c40: false); + if (firstMatch && e1[1] >= 0) { return e1[1]; } - e1[2] = c40OrTextEncodation(text, textOffset, textSize, data, dataOffset, dataSize, true); + e1[2] = c40OrTextEncodation(text, textOffset, textSize, data, dataOffset, dataSize, c40: true); + if (firstMatch && e1[2] >= 0) { return e1[2]; } e1[3] = b256Encodation(text, textOffset, textSize, data, dataOffset, dataSize); + if (firstMatch && e1[3] >= 0) { return e1[3]; } e1[4] = x12Encodation(text, textOffset, textSize, data, dataOffset, dataSize); + if (firstMatch && e1[4] >= 0) { return e1[4]; } e1[5] = edifactEncodation(text, textOffset, textSize, data, dataOffset, dataSize); + if (firstMatch && e1[5] >= 0) { return e1[5]; @@ -769,6 +841,7 @@ private static int getEncodation(byte[] text, int textOffset, int textSize, byte j = 0; e = 99999; + for (k = 0; k < 6; ++k) { if (e1[k] >= 0 && e1[k] < e) @@ -784,11 +857,11 @@ private static int getEncodation(byte[] text, int textOffset, int textSize, byte } else if (j == 1) { - e = c40OrTextEncodation(text, textOffset, textSize, data, dataOffset, dataSize, false); + e = c40OrTextEncodation(text, textOffset, textSize, data, dataOffset, dataSize, c40: false); } else if (j == 2) { - e = c40OrTextEncodation(text, textOffset, textSize, data, dataOffset, dataSize, true); + e = c40OrTextEncodation(text, textOffset, textSize, data, dataOffset, dataSize, c40: true); } else if (j == 3) { @@ -807,9 +880,9 @@ private static int getEncodation(byte[] text, int textOffset, int textSize, byte case DM_ASCII: return asciiEncodation(text, textOffset, textSize, data, dataOffset, dataSize); case DM_C40: - return c40OrTextEncodation(text, textOffset, textSize, data, dataOffset, dataSize, true); + return c40OrTextEncodation(text, textOffset, textSize, data, dataOffset, dataSize, c40: true); case DM_TEXT: - return c40OrTextEncodation(text, textOffset, textSize, data, dataOffset, dataSize, false); + return c40OrTextEncodation(text, textOffset, textSize, data, dataOffset, dataSize, c40: false); case DM_B256: return b256Encodation(text, textOffset, textSize, data, dataOffset, dataSize); case DM_X21: @@ -823,6 +896,7 @@ private static int getEncodation(byte[] text, int textOffset, int textSize, byte } Array.Copy(text, textOffset, data, dataOffset, textSize); + return textSize; } @@ -833,9 +907,11 @@ private static int getNumber(byte[] text, int ptrIn, int n) { int v, j, c; v = 0; + for (j = 0; j < n; ++j) { c = text[ptrIn++] & 0xff; + if (c < '0' || c > '9') { return -1; @@ -858,9 +934,11 @@ private static void makePadding(byte[] data, int position, int count) } data[position++] = 129; + while (--count > 0) { var t = 129 + (position + 1) * 149 % 253 + 1; + if (t > 254) { t -= 254; @@ -870,11 +948,16 @@ private static void makePadding(byte[] data, int position, int count) } } - private static int x12Encodation(byte[] text, int textOffset, int textLength, byte[] data, int dataOffset, - int dataLength) + private static int x12Encodation(byte[] text, + int textOffset, + int textLength, + byte[] data, + int dataOffset, + int dataLength) { int ptrIn, ptrOut, count, k, n, ci; byte c; + if (textLength == 0) { return 0; @@ -884,9 +967,11 @@ private static int x12Encodation(byte[] text, int textOffset, int textLength, by ptrOut = 0; var x = new byte[textLength]; count = 0; + for (; ptrIn < textLength; ++ptrIn) { var i = X12.IndexOf(((char)text[ptrIn + textOffset]).ToString(), StringComparison.Ordinal); + if (i >= 0) { x[ptrIn] = (byte)i; @@ -895,6 +980,7 @@ private static int x12Encodation(byte[] text, int textOffset, int textLength, by else { x[ptrIn] = 100; + if (count >= 6) { count -= count / 3 * 3; @@ -921,9 +1007,11 @@ private static int x12Encodation(byte[] text, int textOffset, int textLength, by ptrIn = 0; c = 0; + for (; ptrIn < textLength; ++ptrIn) { c = x[ptrIn]; + if (ptrOut >= dataLength) { break; @@ -954,6 +1042,7 @@ private static int x12Encodation(byte[] text, int textOffset, int textLength, by } ci = text[ptrIn + textOffset] & 0xff; + if (ci > 127) { data[dataOffset + ptrOut++] = 235; @@ -970,6 +1059,7 @@ private static int x12Encodation(byte[] text, int textOffset, int textLength, by } c = 100; + if (textLength > 0) { c = x[textLength - 1]; @@ -992,6 +1082,7 @@ private void draw(byte[] data, int dataSize, DmParams dm) { int i, j, p, x, y, xs, ys, z; var xByte = (dm.width + Ws * 2 + 7) / 8; + for (var k = 0; k < BitImage.Length; ++k) { BitImage[k] = 0; @@ -1035,6 +1126,7 @@ private void draw(byte[] data, int dataSize, DmParams dm) } p = 0; + for (ys = 0; ys < dm.height; ys += dm.HeightSection) { for (y = 1; y < dm.HeightSection - 1; ++y) @@ -1044,6 +1136,7 @@ private void draw(byte[] data, int dataSize, DmParams dm) for (x = 1; x < dm.WidthSection - 1; ++x) { z = _place[p++]; + if (z == 1 || (z > 1 && (data[z / 8 - 1] & 0xff & (128 >> (z % 8))) != 0)) { setBit(x + xs + Ws, y + ys + Ws, xByte); @@ -1057,6 +1150,7 @@ private void draw(byte[] data, int dataSize, DmParams dm) private int processExtensions(byte[] text, int textOffset, int textSize, byte[] data) { int order, ptrIn, ptrOut, eci, fn, ft, fi, c; + if ((Options & DM_EXTENSION) == 0) { return 0; @@ -1065,6 +1159,7 @@ private int processExtensions(byte[] text, int textOffset, int textSize, byte[] order = 0; ptrIn = 0; ptrOut = 0; + while (ptrIn < textSize) { if (order > 20) @@ -1074,10 +1169,12 @@ private int processExtensions(byte[] text, int textOffset, int textSize, byte[] c = text[textOffset + ptrIn++] & 0xff; ++order; + switch (c) { case '.': _extOut = ptrIn; + return ptrOut; case 'e': if (ptrIn + 6 > textSize) @@ -1085,7 +1182,8 @@ private int processExtensions(byte[] text, int textOffset, int textSize, byte[] return -1; } - eci = getNumber(text, textOffset + ptrIn, 6); + eci = getNumber(text, textOffset + ptrIn, n: 6); + if (eci < 0) { return -1; @@ -1093,6 +1191,7 @@ private int processExtensions(byte[] text, int textOffset, int textSize, byte[] ptrIn += 6; data[ptrOut++] = 241; + if (eci < 127) { data[ptrOut++] = (byte)(eci + 1); @@ -1121,21 +1220,24 @@ private int processExtensions(byte[] text, int textOffset, int textSize, byte[] return -1; } - fn = getNumber(text, textOffset + ptrIn, 2); + fn = getNumber(text, textOffset + ptrIn, n: 2); + if (fn <= 0 || fn > 16) { return -1; } ptrIn += 2; - ft = getNumber(text, textOffset + ptrIn, 2); + ft = getNumber(text, textOffset + ptrIn, n: 2); + if (ft <= 1 || ft > 16) { return -1; } ptrIn += 2; - fi = getNumber(text, textOffset + ptrIn, 5); + fi = getNumber(text, textOffset + ptrIn, n: 5); + if (fi < 0 || fn >= 64516) { return -1; @@ -1146,6 +1248,7 @@ private int processExtensions(byte[] text, int textOffset, int textSize, byte[] data[ptrOut++] = (byte)(((fn - 1) << 4) | (17 - ft)); data[ptrOut++] = (byte)(fi / 254 + 1); data[ptrOut++] = (byte)(fi % 254 + 1); + break; case 'p': if (order != 1) @@ -1154,6 +1257,7 @@ private int processExtensions(byte[] text, int textOffset, int textSize, byte[] } data[ptrOut++] = 234; + break; case 'm': if (order != 1) @@ -1167,6 +1271,7 @@ private int processExtensions(byte[] text, int textOffset, int textSize, byte[] } c = text[textOffset + ptrIn++] & 0xff; + if (c != '5' && c != '5') { return -1; @@ -1174,6 +1279,7 @@ private int processExtensions(byte[] text, int textOffset, int textSize, byte[] data[ptrOut++] = 234; data[ptrOut++] = 236; + break; case 'f': if (order != 1 && (order != 2 || (text[textOffset] != 's' && text[textOffset] != 'm'))) @@ -1182,6 +1288,7 @@ private int processExtensions(byte[] text, int textOffset, int textSize, byte[] } data[ptrOut++] = 232; + break; } } @@ -1189,14 +1296,11 @@ private int processExtensions(byte[] text, int textOffset, int textSize, byte[] return -1; } - private void setBit(int x, int y, int xByte) - { - BitImage[y * xByte + x / 8] |= (byte)(128 >> (x & 7)); - } + private void setBit(int x, int y, int xByte) => BitImage[y * xByte + x / 8] |= (byte)(128 >> (x & 7)); internal class Placement { - private static readonly INullValueDictionary _cache = new NullValueDictionary(); + private static readonly NullValueDictionary _cache = new(); private short[] _array; private int _ncol; private int _nrow; @@ -1209,6 +1313,7 @@ internal static short[] DoPlacement(int nrow, int ncol) { var key = nrow * 1000 + ncol; var pc = _cache[key]; + if (pc != null) { return pc; @@ -1220,6 +1325,7 @@ internal static short[] DoPlacement(int nrow, int ncol) p._array = new short[nrow * ncol]; p.ecc200(); _cache[key] = p._array; + return p._array; } @@ -1228,50 +1334,50 @@ internal static short[] DoPlacement(int nrow, int ncol) /// private void corner1(int chr) { - module(_nrow - 1, 0, chr, 0); - module(_nrow - 1, 1, chr, 1); - module(_nrow - 1, 2, chr, 2); - module(0, _ncol - 2, chr, 3); - module(0, _ncol - 1, chr, 4); - module(1, _ncol - 1, chr, 5); - module(2, _ncol - 1, chr, 6); - module(3, _ncol - 1, chr, 7); + module(_nrow - 1, col: 0, chr, bit: 0); + module(_nrow - 1, col: 1, chr, bit: 1); + module(_nrow - 1, col: 2, chr, bit: 2); + module(row: 0, _ncol - 2, chr, bit: 3); + module(row: 0, _ncol - 1, chr, bit: 4); + module(row: 1, _ncol - 1, chr, bit: 5); + module(row: 2, _ncol - 1, chr, bit: 6); + module(row: 3, _ncol - 1, chr, bit: 7); } private void corner2(int chr) { - module(_nrow - 3, 0, chr, 0); - module(_nrow - 2, 0, chr, 1); - module(_nrow - 1, 0, chr, 2); - module(0, _ncol - 4, chr, 3); - module(0, _ncol - 3, chr, 4); - module(0, _ncol - 2, chr, 5); - module(0, _ncol - 1, chr, 6); - module(1, _ncol - 1, chr, 7); + module(_nrow - 3, col: 0, chr, bit: 0); + module(_nrow - 2, col: 0, chr, bit: 1); + module(_nrow - 1, col: 0, chr, bit: 2); + module(row: 0, _ncol - 4, chr, bit: 3); + module(row: 0, _ncol - 3, chr, bit: 4); + module(row: 0, _ncol - 2, chr, bit: 5); + module(row: 0, _ncol - 1, chr, bit: 6); + module(row: 1, _ncol - 1, chr, bit: 7); } private void corner3(int chr) { - module(_nrow - 3, 0, chr, 0); - module(_nrow - 2, 0, chr, 1); - module(_nrow - 1, 0, chr, 2); - module(0, _ncol - 2, chr, 3); - module(0, _ncol - 1, chr, 4); - module(1, _ncol - 1, chr, 5); - module(2, _ncol - 1, chr, 6); - module(3, _ncol - 1, chr, 7); + module(_nrow - 3, col: 0, chr, bit: 0); + module(_nrow - 2, col: 0, chr, bit: 1); + module(_nrow - 1, col: 0, chr, bit: 2); + module(row: 0, _ncol - 2, chr, bit: 3); + module(row: 0, _ncol - 1, chr, bit: 4); + module(row: 1, _ncol - 1, chr, bit: 5); + module(row: 2, _ncol - 1, chr, bit: 6); + module(row: 3, _ncol - 1, chr, bit: 7); } private void corner4(int chr) { - module(_nrow - 1, 0, chr, 0); - module(_nrow - 1, _ncol - 1, chr, 1); - module(0, _ncol - 3, chr, 2); - module(0, _ncol - 2, chr, 3); - module(0, _ncol - 1, chr, 4); - module(1, _ncol - 3, chr, 5); - module(1, _ncol - 2, chr, 6); - module(1, _ncol - 1, chr, 7); + module(_nrow - 1, col: 0, chr, bit: 0); + module(_nrow - 1, _ncol - 1, chr, bit: 1); + module(row: 0, _ncol - 3, chr, bit: 2); + module(row: 0, _ncol - 2, chr, bit: 3); + module(row: 0, _ncol - 1, chr, bit: 4); + module(row: 1, _ncol - 3, chr, bit: 5); + module(row: 1, _ncol - 2, chr, bit: 6); + module(row: 1, _ncol - 1, chr, bit: 7); } /// @@ -1280,6 +1386,7 @@ private void corner4(int chr) private void ecc200() { int row, col, chr; + /* First, fill the array[] with invalid entries */ for (var k = 0; k < _array.Length; ++k) { @@ -1290,6 +1397,7 @@ private void ecc200() chr = 1; row = 4; col = 0; + do { /* repeatedly first check for one of the special corner cases, then... */ @@ -1323,7 +1431,8 @@ private void ecc200() row -= 2; col += 2; - } while (row >= 0 && col < _ncol); + } + while (row >= 0 && col < _ncol); row += 1; col += 3; @@ -1338,12 +1447,14 @@ private void ecc200() row += 2; col -= 2; - } while (row < _nrow && col >= 0); + } + while (row < _nrow && col >= 0); row += 3; col += 1; /* ... until the entire array is scanned */ - } while (row < _nrow || col < _ncol); + } + while (row < _nrow || col < _ncol); /* Lastly, if the lower righthand corner is untouched, fill in fixed pattern */ if (_array[_nrow * _ncol - 1] == 0) @@ -1377,14 +1488,14 @@ private void module(int row, int col, int chr, int bit) /// private void utah(int row, int col, int chr) { - module(row - 2, col - 2, chr, 0); - module(row - 2, col - 1, chr, 1); - module(row - 1, col - 2, chr, 2); - module(row - 1, col - 1, chr, 3); - module(row - 1, col, chr, 4); - module(row, col - 2, chr, 5); - module(row, col - 1, chr, 6); - module(row, col, chr, 7); + module(row - 2, col - 2, chr, bit: 0); + module(row - 2, col - 1, chr, bit: 1); + module(row - 1, col - 2, chr, bit: 2); + module(row - 1, col - 1, chr, bit: 3); + module(row - 1, col, chr, bit: 4); + module(row, col - 2, chr, bit: 5); + module(row, col - 1, chr, bit: 6); + module(row, col, chr, bit: 7); } } @@ -1392,184 +1503,123 @@ internal class ReedSolomon { private static readonly int[] _alog = { - 1, 2, 4, 8, 16, 32, 64, 128, 45, 90, 180, 69, 138, 57, 114, 228, - 229, 231, 227, 235, 251, 219, 155, 27, 54, 108, 216, 157, 23, 46, 92, - 184, - 93, 186, 89, 178, 73, 146, 9, 18, 36, 72, 144, 13, 26, 52, 104, 208, - 141, 55, 110, 220, 149, 7, 14, 28, 56, 112, 224, 237, 247, 195, 171, - 123, - 246, 193, 175, 115, 230, 225, 239, 243, 203, 187, 91, 182, 65, 130, - 41, 82, - 164, 101, 202, 185, 95, 190, 81, 162, 105, 210, 137, 63, 126, 252, - 213, 135, - 35, 70, 140, 53, 106, 212, 133, 39, 78, 156, 21, 42, 84, 168, 125, - 250, - 217, 159, 19, 38, 76, 152, 29, 58, 116, 232, 253, 215, 131, 43, 86, - 172, - 117, 234, 249, 223, 147, 11, 22, 44, 88, 176, 77, 154, 25, 50, 100, - 200, - 189, 87, 174, 113, 226, 233, 255, 211, 139, 59, 118, 236, 245, 199, - 163, 107, - 214, 129, 47, 94, 188, 85, 170, 121, 242, 201, 191, 83, 166, 97, 194, - 169, - 127, 254, 209, 143, 51, 102, 204, 181, 71, 142, 49, 98, 196, 165, 103, - 206, - 177, 79, 158, 17, 34, 68, 136, 61, 122, 244, 197, 167, 99, 198, 161, - 111, - 222, 145, 15, 30, 60, 120, 240, 205, 183, 67, 134, 33, 66, 132, 37, - 74, - 148, 5, 10, 20, 40, 80, 160, 109, 218, 153, 31, 62, 124, 248, 221, - 151, - 3, 6, 12, 24, 48, 96, 192, 173, 119, 238, 241, 207, 179, 75, 150, 1, + 1, 2, 4, 8, 16, 32, 64, 128, 45, 90, 180, 69, 138, 57, 114, 228, 229, 231, 227, 235, 251, 219, 155, 27, 54, + 108, 216, 157, 23, 46, 92, 184, 93, 186, 89, 178, 73, 146, 9, 18, 36, 72, 144, 13, 26, 52, 104, 208, 141, + 55, 110, 220, 149, 7, 14, 28, 56, 112, 224, 237, 247, 195, 171, 123, 246, 193, 175, 115, 230, 225, 239, 243, + 203, 187, 91, 182, 65, 130, 41, 82, 164, 101, 202, 185, 95, 190, 81, 162, 105, 210, 137, 63, 126, 252, 213, + 135, 35, 70, 140, 53, 106, 212, 133, 39, 78, 156, 21, 42, 84, 168, 125, 250, 217, 159, 19, 38, 76, 152, 29, + 58, 116, 232, 253, 215, 131, 43, 86, 172, 117, 234, 249, 223, 147, 11, 22, 44, 88, 176, 77, 154, 25, 50, + 100, 200, 189, 87, 174, 113, 226, 233, 255, 211, 139, 59, 118, 236, 245, 199, 163, 107, 214, 129, 47, 94, + 188, 85, 170, 121, 242, 201, 191, 83, 166, 97, 194, 169, 127, 254, 209, 143, 51, 102, 204, 181, 71, 142, 49, + 98, 196, 165, 103, 206, 177, 79, 158, 17, 34, 68, 136, 61, 122, 244, 197, 167, 99, 198, 161, 111, 222, 145, + 15, 30, 60, 120, 240, 205, 183, 67, 134, 33, 66, 132, 37, 74, 148, 5, 10, 20, 40, 80, 160, 109, 218, 153, + 31, 62, 124, 248, 221, 151, 3, 6, 12, 24, 48, 96, 192, 173, 119, 238, 241, 207, 179, 75, 150, 1 }; private static readonly int[] _log = { - 0, 255, 1, 240, 2, 225, 241, 53, 3, 38, 226, 133, 242, 43, 54, 210, - 4, 195, 39, 114, 227, 106, 134, 28, 243, 140, 44, 23, 55, 118, 211, - 234, - 5, 219, 196, 96, 40, 222, 115, 103, 228, 78, 107, 125, 135, 8, 29, 162, - 244, 186, 141, 180, 45, 99, 24, 49, 56, 13, 119, 153, 212, 199, 235, - 91, - 6, 76, 220, 217, 197, 11, 97, 184, 41, 36, 223, 253, 116, 138, 104, - 193, - 229, 86, 79, 171, 108, 165, 126, 145, 136, 34, 9, 74, 30, 32, 163, 84, - 245, 173, 187, 204, 142, 81, 181, 190, 46, 88, 100, 159, 25, 231, 50, - 207, - 57, 147, 14, 67, 120, 128, 154, 248, 213, 167, 200, 63, 236, 110, 92, - 176, - 7, 161, 77, 124, 221, 102, 218, 95, 198, 90, 12, 152, 98, 48, 185, 179, - 42, 209, 37, 132, 224, 52, 254, 239, 117, 233, 139, 22, 105, 27, 194, - 113, - 230, 206, 87, 158, 80, 189, 172, 203, 109, 175, 166, 62, 127, 247, 146, - 66, - 137, 192, 35, 252, 10, 183, 75, 216, 31, 83, 33, 73, 164, 144, 85, 170, - 246, 65, 174, 61, 188, 202, 205, 157, 143, 169, 82, 72, 182, 215, 191, - 251, - 47, 178, 89, 151, 101, 94, 160, 123, 26, 112, 232, 21, 51, 238, 208, - 131, - 58, 69, 148, 18, 15, 16, 68, 17, 121, 149, 129, 19, 155, 59, 249, 70, - 214, 250, 168, 71, 201, 156, 64, 60, 237, 130, 111, 20, 93, 122, 177, - 150, + 0, 255, 1, 240, 2, 225, 241, 53, 3, 38, 226, 133, 242, 43, 54, 210, 4, 195, 39, 114, 227, 106, 134, 28, 243, + 140, 44, 23, 55, 118, 211, 234, 5, 219, 196, 96, 40, 222, 115, 103, 228, 78, 107, 125, 135, 8, 29, 162, 244, + 186, 141, 180, 45, 99, 24, 49, 56, 13, 119, 153, 212, 199, 235, 91, 6, 76, 220, 217, 197, 11, 97, 184, 41, + 36, 223, 253, 116, 138, 104, 193, 229, 86, 79, 171, 108, 165, 126, 145, 136, 34, 9, 74, 30, 32, 163, 84, + 245, 173, 187, 204, 142, 81, 181, 190, 46, 88, 100, 159, 25, 231, 50, 207, 57, 147, 14, 67, 120, 128, 154, + 248, 213, 167, 200, 63, 236, 110, 92, 176, 7, 161, 77, 124, 221, 102, 218, 95, 198, 90, 12, 152, 98, 48, + 185, 179, 42, 209, 37, 132, 224, 52, 254, 239, 117, 233, 139, 22, 105, 27, 194, 113, 230, 206, 87, 158, 80, + 189, 172, 203, 109, 175, 166, 62, 127, 247, 146, 66, 137, 192, 35, 252, 10, 183, 75, 216, 31, 83, 33, 73, + 164, 144, 85, 170, 246, 65, 174, 61, 188, 202, 205, 157, 143, 169, 82, 72, 182, 215, 191, 251, 47, 178, 89, + 151, 101, 94, 160, 123, 26, 112, 232, 21, 51, 238, 208, 131, 58, 69, 148, 18, 15, 16, 68, 17, 121, 149, 129, + 19, 155, 59, 249, 70, 214, 250, 168, 71, 201, 156, 64, 60, 237, 130, 111, 20, 93, 122, 177, 150 }; private static readonly int[] _poly10 = { - 28, 24, 185, 166, 223, 248, 116, 255, 110, 61, + 28, 24, 185, 166, 223, 248, 116, 255, 110, 61 }; private static readonly int[] _poly11 = { - 175, 138, 205, 12, 194, 168, 39, 245, 60, 97, 120, + 175, 138, 205, 12, 194, 168, 39, 245, 60, 97, 120 }; private static readonly int[] _poly12 = { - 41, 153, 158, 91, 61, 42, 142, 213, 97, 178, 100, 242, + 41, 153, 158, 91, 61, 42, 142, 213, 97, 178, 100, 242 }; private static readonly int[] _poly14 = { - 156, 97, 192, 252, 95, 9, 157, 119, 138, 45, 18, 186, 83, 185, + 156, 97, 192, 252, 95, 9, 157, 119, 138, 45, 18, 186, 83, 185 }; private static readonly int[] _poly18 = { - 83, 195, 100, 39, 188, 75, 66, 61, 241, 213, 109, 129, 94, 254, 225, - 48, - 90, 188, + 83, 195, 100, 39, 188, 75, 66, 61, 241, 213, 109, 129, 94, 254, 225, 48, 90, 188 }; private static readonly int[] _poly20 = { - 15, 195, 244, 9, 233, 71, 168, 2, 188, 160, 153, 145, 253, 79, 108, - 82, - 27, 174, 186, 172, + 15, 195, 244, 9, 233, 71, 168, 2, 188, 160, 153, 145, 253, 79, 108, 82, 27, 174, 186, 172 }; private static readonly int[] _poly24 = { - 52, 190, 88, 205, 109, 39, 176, 21, 155, 197, 251, 223, 155, 21, 5, - 172, - 254, 124, 12, 181, 184, 96, 50, 193, + 52, 190, 88, 205, 109, 39, 176, 21, 155, 197, 251, 223, 155, 21, 5, 172, 254, 124, 12, 181, 184, 96, 50, 193 }; private static readonly int[] _poly28 = { - 211, 231, 43, 97, 71, 96, 103, 174, 37, 151, 170, 53, 75, 34, 249, - 121, - 17, 138, 110, 213, 141, 136, 120, 151, 233, 168, 93, 255, + 211, 231, 43, 97, 71, 96, 103, 174, 37, 151, 170, 53, 75, 34, 249, 121, 17, 138, 110, 213, 141, 136, 120, + 151, 233, 168, 93, 255 }; private static readonly int[] _poly36 = { - 245, 127, 242, 218, 130, 250, 162, 181, 102, 120, 84, 179, 220, 251, - 80, 182, - 229, 18, 2, 4, 68, 33, 101, 137, 95, 119, 115, 44, 175, 184, 59, 25, - 225, 98, 81, 112, + 245, 127, 242, 218, 130, 250, 162, 181, 102, 120, 84, 179, 220, 251, 80, 182, 229, 18, 2, 4, 68, 33, 101, + 137, 95, 119, 115, 44, 175, 184, 59, 25, 225, 98, 81, 112 }; private static readonly int[] _poly42 = { - 77, 193, 137, 31, 19, 38, 22, 153, 247, 105, 122, 2, 245, 133, 242, - 8, - 175, 95, 100, 9, 167, 105, 214, 111, 57, 121, 21, 1, 253, 57, 54, - 101, - 248, 202, 69, 50, 150, 177, 226, 5, 9, 5, + 77, 193, 137, 31, 19, 38, 22, 153, 247, 105, 122, 2, 245, 133, 242, 8, 175, 95, 100, 9, 167, 105, 214, 111, + 57, 121, 21, 1, 253, 57, 54, 101, 248, 202, 69, 50, 150, 177, 226, 5, 9, 5 }; private static readonly int[] _poly48 = { - 245, 132, 172, 223, 96, 32, 117, 22, 238, 133, 238, 231, 205, 188, - 237, 87, - 191, 106, 16, 147, 118, 23, 37, 90, 170, 205, 131, 88, 120, 100, 66, - 138, - 186, 240, 82, 44, 176, 87, 187, 147, 160, 175, 69, 213, 92, 253, - 225, 19, + 245, 132, 172, 223, 96, 32, 117, 22, 238, 133, 238, 231, 205, 188, 237, 87, 191, 106, 16, 147, 118, 23, 37, + 90, 170, 205, 131, 88, 120, 100, 66, 138, 186, 240, 82, 44, 176, 87, 187, 147, 160, 175, 69, 213, 92, 253, + 225, 19 }; private static readonly int[] _poly5 = { - 228, 48, 15, 111, 62, + 228, 48, 15, 111, 62 }; private static readonly int[] _poly56 = { - 175, 9, 223, 238, 12, 17, 220, 208, 100, 29, 175, 170, 230, 192, - 215, 235, - 150, 159, 36, 223, 38, 200, 132, 54, 228, 146, 218, 234, 117, 203, - 29, 232, - 144, 238, 22, 150, 201, 117, 62, 207, 164, 13, 137, 245, 127, 67, - 247, 28, - 155, 43, 203, 107, 233, 53, 143, 46, + 175, 9, 223, 238, 12, 17, 220, 208, 100, 29, 175, 170, 230, 192, 215, 235, 150, 159, 36, 223, 38, 200, 132, + 54, 228, 146, 218, 234, 117, 203, 29, 232, 144, 238, 22, 150, 201, 117, 62, 207, 164, 13, 137, 245, 127, 67, + 247, 28, 155, 43, 203, 107, 233, 53, 143, 46 }; private static readonly int[] _poly62 = { - 242, 93, 169, 50, 144, 210, 39, 118, 202, 188, 201, 189, 143, 108, - 196, 37, - 185, 112, 134, 230, 245, 63, 197, 190, 250, 106, 185, 221, 175, 64, - 114, 71, - 161, 44, 147, 6, 27, 218, 51, 63, 87, 10, 40, 130, 188, 17, 163, 31, - 176, 170, 4, 107, 232, 7, 94, 166, 224, 124, 86, 47, 11, 204, + 242, 93, 169, 50, 144, 210, 39, 118, 202, 188, 201, 189, 143, 108, 196, 37, 185, 112, 134, 230, 245, 63, + 197, 190, 250, 106, 185, 221, 175, 64, 114, 71, 161, 44, 147, 6, 27, 218, 51, 63, 87, 10, 40, 130, 188, 17, + 163, 31, 176, 170, 4, 107, 232, 7, 94, 166, 224, 124, 86, 47, 11, 204 }; private static readonly int[] _poly68 = { - 220, 228, 173, 89, 251, 149, 159, 56, 89, 33, 147, 244, 154, 36, 73, - 127, - 213, 136, 248, 180, 234, 197, 158, 177, 68, 122, 93, 213, 15, 160, - 227, 236, - 66, 139, 153, 185, 202, 167, 179, 25, 220, 232, 96, 210, 231, 136, - 223, 239, - 181, 241, 59, 52, 172, 25, 49, 232, 211, 189, 64, 54, 108, 153, 132, - 63, - 96, 103, 82, 186, + 220, 228, 173, 89, 251, 149, 159, 56, 89, 33, 147, 244, 154, 36, 73, 127, 213, 136, 248, 180, 234, 197, 158, + 177, 68, 122, 93, 213, 15, 160, 227, 236, 66, 139, 153, 185, 202, 167, 179, 25, 220, 232, 96, 210, 231, 136, + 223, 239, 181, 241, 59, 52, 172, 25, 49, 232, 211, 189, 64, 54, 108, 153, 132, 63, 96, 103, 82, 186 }; private static readonly int[] _poly7 = { - 23, 68, 144, 134, 240, 92, 254, + 23, 68, 144, 134, 240, 92, 254 }; internal static void GenerateEcc(byte[] wd, int nd, int datablock, int nc) @@ -1579,9 +1629,11 @@ internal static void GenerateEcc(byte[] wd, int nd, int datablock, int nc) var buf = new byte[256]; var ecc = new byte[256]; var c = getPoly(nc); + for (b = 0; b < blocks; b++) { int n, p = 0; + for (n = b; n < nd; n += blocks) { buf[p++] = wd[n]; @@ -1589,6 +1641,7 @@ internal static void GenerateEcc(byte[] wd, int nd, int datablock, int nc) reedSolomonBlock(buf, p, ecc, nc, c); p = 0; + for (n = b; n < nc * blocks; n += blocks) { wd[nd + n] = ecc[p++]; @@ -1649,6 +1702,7 @@ private static void reedSolomonBlock(byte[] wd, int nd, byte[] ncout, int nc, in for (i = 0; i < nd; i++) { k = (ncout[0] ^ wd[i]) & 0xff; + for (j = 0; j < nc; j++) { ncout[j] = (byte)(ncout[j + 1] ^ (k == 0 ? 0 : (byte)_alog[(_log[k] + _log[c[nc - j - 1]]) % 255])); @@ -1673,8 +1727,13 @@ private class DmParams internal readonly int WidthSection; - internal DmParams(int height, int width, int heightSection, int widthSection, int dataSize, int dataBlock, - int errorBlock) + internal DmParams(int height, + int width, + int heightSection, + int widthSection, + int dataSize, + int dataBlock, + int errorBlock) { this.height = height; this.width = width; diff --git a/src/iTextSharp.LGPLv2.Core/iTextSharp/text/pdf/GlyphList.cs b/src/iTextSharp.LGPLv2.Core/iTextSharp/text/pdf/GlyphList.cs index f2c4480..471c479 100644 --- a/src/iTextSharp.LGPLv2.Core/iTextSharp/text/pdf/GlyphList.cs +++ b/src/iTextSharp.LGPLv2.Core/iTextSharp/text/pdf/GlyphList.cs @@ -6,54 +6,61 @@ namespace iTextSharp.text.pdf; /// public static class GlyphList { - private static readonly INullValueDictionary _names2Unicode = - new NullValueDictionary(); + private static readonly NullValueDictionary _names2Unicode = new(); - private static readonly INullValueDictionary _unicode2Names = new NullValueDictionary(); + private static readonly NullValueDictionary _unicode2Names = new(); static GlyphList() { try { using var resourceStream = BaseFont.GetResourceStream($"{BaseFont.RESOURCE_PATH}glyphlist.txt"); + if (resourceStream == null) { - Console.Error.WriteLine("glyphlist.txt not found as resource."); + Console.Error.WriteLine(value: "glyphlist.txt not found as resource."); + return; } var buf = new byte[1024]; using var outputStream = new MemoryStream(); + while (true) { - var size = resourceStream.Read(buf, 0, buf.Length); + var size = resourceStream.Read(buf, offset: 0, buf.Length); + if (size == 0) { break; } - outputStream.Write(buf, 0, size); + outputStream.Write(buf, offset: 0, size); } - var s = PdfEncodings.ConvertToString(outputStream.ToArray(), null); - var tk = new StringTokenizer(s, "\r\n"); + var s = PdfEncodings.ConvertToString(outputStream.ToArray(), encoding: null); + var tk = new StringTokenizer(s, delim: "\r\n"); + while (tk.HasMoreTokens()) { var line = tk.NextToken(); - if (line.StartsWith("#", StringComparison.Ordinal)) + + if (line.StartsWith(value: "#", StringComparison.Ordinal)) { continue; } - var t2 = new StringTokenizer(line, " ;\r\n\t\f"); + var t2 = new StringTokenizer(line, delim: " ;\r\n\t\f"); string name = null; string hex = null; + if (!t2.HasMoreTokens()) { continue; } name = t2.NextToken(); + if (!t2.HasMoreTokens()) { continue; @@ -62,7 +69,11 @@ static GlyphList() hex = t2.NextToken(); var num = int.Parse(hex, NumberStyles.HexNumber, CultureInfo.InvariantCulture); _unicode2Names[num] = name; - _names2Unicode[name] = new[] { num }; + + _names2Unicode[name] = new[] + { + num + }; } } catch (Exception e) diff --git a/src/iTextSharp.LGPLv2.Core/iTextSharp/text/pdf/ICC_Profile.cs b/src/iTextSharp.LGPLv2.Core/iTextSharp/text/pdf/ICC_Profile.cs index 0727605..5716b04 100644 --- a/src/iTextSharp.LGPLv2.Core/iTextSharp/text/pdf/ICC_Profile.cs +++ b/src/iTextSharp.LGPLv2.Core/iTextSharp/text/pdf/ICC_Profile.cs @@ -8,37 +8,37 @@ namespace iTextSharp.text.pdf; /// public class IccProfile { - private static readonly INullValueDictionary _cstags = new NullValueDictionary(); + private static readonly NullValueDictionary _cstags = new(); protected byte[] data; protected int numComponents; static IccProfile() { - _cstags["XYZ "] = 3; - _cstags["Lab "] = 3; - _cstags["Luv "] = 3; - _cstags["YCbr"] = 3; - _cstags["Yxy "] = 3; - _cstags["RGB "] = 3; - _cstags["GRAY"] = 1; - _cstags["HSV "] = 3; - _cstags["HLS "] = 3; - _cstags["CMYK"] = 4; - _cstags["CMY "] = 3; - _cstags["2CLR"] = 2; - _cstags["3CLR"] = 3; - _cstags["4CLR"] = 4; - _cstags["5CLR"] = 5; - _cstags["6CLR"] = 6; - _cstags["7CLR"] = 7; - _cstags["8CLR"] = 8; - _cstags["9CLR"] = 9; - _cstags["ACLR"] = 10; - _cstags["BCLR"] = 11; - _cstags["CCLR"] = 12; - _cstags["DCLR"] = 13; - _cstags["ECLR"] = 14; - _cstags["FCLR"] = 15; + _cstags[key: "XYZ "] = 3; + _cstags[key: "Lab "] = 3; + _cstags[key: "Luv "] = 3; + _cstags[key: "YCbr"] = 3; + _cstags[key: "Yxy "] = 3; + _cstags[key: "RGB "] = 3; + _cstags[key: "GRAY"] = 1; + _cstags[key: "HSV "] = 3; + _cstags[key: "HLS "] = 3; + _cstags[key: "CMYK"] = 4; + _cstags[key: "CMY "] = 3; + _cstags[key: "2CLR"] = 2; + _cstags[key: "3CLR"] = 3; + _cstags[key: "4CLR"] = 4; + _cstags[key: "5CLR"] = 5; + _cstags[key: "6CLR"] = 6; + _cstags[key: "7CLR"] = 7; + _cstags[key: "8CLR"] = 8; + _cstags[key: "9CLR"] = 9; + _cstags[key: "ACLR"] = 10; + _cstags[key: "BCLR"] = 11; + _cstags[key: "CCLR"] = 12; + _cstags[key: "DCLR"] = 13; + _cstags[key: "ECLR"] = 14; + _cstags[key: "FCLR"] = 15; } protected IccProfile() @@ -56,16 +56,16 @@ public static IccProfile GetInstance(byte[] data) throw new ArgumentNullException(nameof(data)); } - if (data.Length < 128 || data[36] != 0x61 || data[37] != 0x63 - || data[38] != 0x73 || data[39] != 0x70) + if (data.Length < 128 || data[36] != 0x61 || data[37] != 0x63 || data[38] != 0x73 || data[39] != 0x70) { - throw new ArgumentException("Invalid ICC profile"); + throw new ArgumentException(message: "Invalid ICC profile"); } var icc = new IccProfile(); icc.data = data; - object cs = _cstags[Encoding.ASCII.GetString(data, 16, 4)]; + object cs = _cstags[Encoding.ASCII.GetString(data, index: 16, count: 4)]; icc.numComponents = (int)cs; + return icc; } @@ -79,36 +79,38 @@ public static IccProfile GetInstance(Stream file) var head = new byte[128]; var remain = head.Length; var ptr = 0; + while (remain > 0) { var n = file.Read(head, ptr, remain); + if (n <= 0) { - throw new ArgumentException("Invalid ICC profile"); + throw new ArgumentException(message: "Invalid ICC profile"); } remain -= n; ptr += n; } - if (head[36] != 0x61 || head[37] != 0x63 - || head[38] != 0x73 || head[39] != 0x70) + if (head[36] != 0x61 || head[37] != 0x63 || head[38] != 0x73 || head[39] != 0x70) { - throw new ArgumentException("Invalid ICC profile"); + throw new ArgumentException(message: "Invalid ICC profile"); } - remain = ((head[0] & 0xff) << 24) | ((head[1] & 0xff) << 16) - | ((head[2] & 0xff) << 8) | (head[3] & 0xff); + remain = ((head[0] & 0xff) << 24) | ((head[1] & 0xff) << 16) | ((head[2] & 0xff) << 8) | (head[3] & 0xff); var icc = new byte[remain]; - Array.Copy(head, 0, icc, 0, head.Length); + Array.Copy(head, sourceIndex: 0, icc, destinationIndex: 0, head.Length); remain -= head.Length; ptr = head.Length; + while (remain > 0) { var n = file.Read(icc, ptr, remain); + if (n <= 0) { - throw new ArgumentException("Invalid ICC profile"); + throw new ArgumentException(message: "Invalid ICC profile"); } remain -= n; @@ -122,6 +124,7 @@ public static IccProfile GetInstance(string fname) { using var fs = new FileStream(fname, FileMode.Open, FileAccess.Read, FileShare.Read); var icc = GetInstance(fs); + return icc; } } \ No newline at end of file diff --git a/src/iTextSharp.LGPLv2.Core/iTextSharp/text/pdf/PdfContentByte.cs b/src/iTextSharp.LGPLv2.Core/iTextSharp/text/pdf/PdfContentByte.cs index 6ec259d..959dbd3 100644 --- a/src/iTextSharp.LGPLv2.Core/iTextSharp/text/pdf/PdfContentByte.cs +++ b/src/iTextSharp.LGPLv2.Core/iTextSharp/text/pdf/PdfContentByte.cs @@ -97,7 +97,7 @@ public class PdfContentByte /// public const int TEXT_RENDER_MODE_STROKE_CLIP = 5; - private static readonly INullValueDictionary _abrev = new NullValueDictionary(); + private static readonly NullValueDictionary _abrev = new(); private static readonly float[] _unitRect = { @@ -369,7 +369,7 @@ public static PdfTextArray GetKernArray(string text, BaseFont font) if (len >= 0) { - acc.Append(c, 0, 1); + acc.Append(c, startIndex: 0, charCount: 1); } for (var k = 0; k < len; ++k) @@ -385,7 +385,7 @@ public static PdfTextArray GetKernArray(string text, BaseFont font) { pa.Add(acc.ToString()); acc.Length = 0; - acc.Append(c, k + 1, 1); + acc.Append(c, k + 1, charCount: 1); pa.Add(-kern); } } @@ -404,7 +404,7 @@ public void Add(PdfContentByte other) if (other.Writer != null && Writer != other.Writer) { - throw new InvalidOperationException("Inconsistent writers. Are you mixing two documents?"); + throw new InvalidOperationException(message: "Inconsistent writers. Are you mixing two documents?"); } Content.Append(other.Content); @@ -416,8 +416,7 @@ public void Add(PdfContentByte other) /// @throws DocumentException if the Image does not have absolute positioning /// /// the Image object - public virtual void AddImage(Image image) - => AddImage(image, false); + public virtual void AddImage(Image image) => AddImage(image, inlineImage: false); /// /// Adds an Image to the page. The Image must have @@ -435,7 +434,7 @@ public virtual void AddImage(Image image, bool inlineImage) if (!image.HasAbsolutePosition()) { - throw new DocumentException("The image must have absolute positioning."); + throw new DocumentException(message: "The image must have absolute positioning."); } var matrix = image.Matrix; @@ -458,7 +457,7 @@ public virtual void AddImage(Image image, bool inlineImage) /// an element of the transformation matrix /// an element of the transformation matrix public virtual void AddImage(Image image, float a, float b, float c, float d, float e, float f) - => AddImage(image, a, b, c, d, e, f, false); + => AddImage(image, a, b, c, d, e, f, inlineImage: false); /// /// Adds an Image to the page. The positioning of the Image @@ -496,18 +495,18 @@ public virtual void AddImage(Image image, float a, float b, float c, float d, fl } else { - Content.Append("q "); - Content.Append(a).Append(' '); - Content.Append(b).Append(' '); - Content.Append(c).Append(' '); - Content.Append(d).Append(' '); - Content.Append(e).Append(' '); - Content.Append(f).Append(" cm"); + Content.Append(str: "q "); + Content.Append(a).Append(c: ' '); + Content.Append(b).Append(c: ' '); + Content.Append(c).Append(c: ' '); + Content.Append(d).Append(c: ' '); + Content.Append(e).Append(c: ' '); + Content.Append(f).Append(str: " cm"); if (inlineImage) { - Content.Append("\nBI\n"); - var pimage = new PdfImage(image, "", null); + Content.Append(str: "\nBI\n"); + var pimage = new PdfImage(image, name: "", maskRef: null); if (image is ImgJbig2) { @@ -538,8 +537,8 @@ public virtual void AddImage(Image image, float a, float b, float c, float d, fl { var ar = (PdfArray)value; - if (ar.Size == 4 && PdfName.Indexed.Equals(ar.GetAsName(0)) && ar[1].IsName() && - ar[2].IsNumber() && ar[3].IsString()) + if (ar.Size == 4 && PdfName.Indexed.Equals(ar.GetAsName(idx: 0)) && ar[idx: 1].IsName() && + ar[idx: 2].IsNumber() && ar[idx: 3].IsString()) { check = false; } @@ -553,13 +552,13 @@ public virtual void AddImage(Image image, float a, float b, float c, float d, fl value = cs; } - value.ToPdf(null, Content); - Content.Append('\n'); + value.ToPdf(writer: null, Content); + Content.Append(c: '\n'); } - Content.Append("ID\n"); + Content.Append(str: "ID\n"); pimage.WriteContent(Content); - Content.Append("\nEI\nQ").Append_i(Separator); + Content.Append(str: "\nEI\nQ").Append_i(Separator); } else { @@ -575,7 +574,7 @@ public virtual void AddImage(Image image, float a, float b, float c, float d, fl name = Writer.AddDirectImageSimple(image); name = prs.AddXObject(name, Writer.GetImageReference(name)); - Content.Append(' ').Append(name.GetBytes()).Append(" Do Q").Append_i(Separator); + Content.Append(c: ' ').Append(name.GetBytes()).Append(str: " Do Q").Append_i(Separator); } } @@ -662,10 +661,10 @@ public void AddPsxObject(PdfPsxObject psobject) } CheckWriter(); - var name = Writer.AddDirectTemplateSimple(psobject, null); + var name = Writer.AddDirectTemplateSimple(psobject, forcedName: null); var prs = PageResources; name = prs.AddXObject(name, psobject.IndirectReference); - Content.Append(name.GetBytes()).Append(" Do").Append_i(Separator); + Content.Append(name.GetBytes()).Append(str: " Do").Append_i(Separator); } /// @@ -687,17 +686,17 @@ public virtual void AddTemplate(PdfTemplate pdfTemplate, float a, float b, float CheckWriter(); CheckNoPattern(pdfTemplate); - var name = Writer.AddDirectTemplateSimple(pdfTemplate, null); + var name = Writer.AddDirectTemplateSimple(pdfTemplate, forcedName: null); var prs = PageResources; name = prs.AddXObject(name, pdfTemplate.IndirectReference); - Content.Append("q "); - Content.Append(a).Append(' '); - Content.Append(b).Append(' '); - Content.Append(c).Append(' '); - Content.Append(d).Append(' '); - Content.Append(e).Append(' '); - Content.Append(f).Append(" cm "); - Content.Append(name.GetBytes()).Append(" Do Q").Append_i(Separator); + Content.Append(str: "q "); + Content.Append(a).Append(c: ' '); + Content.Append(b).Append(c: ' '); + Content.Append(c).Append(c: ' '); + Content.Append(d).Append(c: ' '); + Content.Append(e).Append(c: ' '); + Content.Append(f).Append(str: " cm "); + Content.Append(name.GetBytes()).Append(str: " Do Q").Append_i(Separator); } /// @@ -707,7 +706,7 @@ public virtual void AddTemplate(PdfTemplate pdfTemplate, float a, float b, float /// the x location of this template /// the y location of this template public void AddTemplate(PdfTemplate pdfTemplate, float x, float y) - => AddTemplate(pdfTemplate, 1, 0, 0, 1, x, y); + => AddTemplate(pdfTemplate, a: 1, b: 0, c: 0, d: 1, x, y); /// /// Draws a partial ellipse inscribed within the rectangle x1,y1,x2,y2, @@ -729,7 +728,7 @@ public void Arc(float x1, float y1, float x2, float y2, float startAng, float ex return; } - var pt = ar[0]; + var pt = ar[index: 0]; MoveTo(pt[0], pt[1]); for (var k = 0; k < ar.Count; ++k) @@ -751,7 +750,7 @@ public void BeginLayer(IPdfOcg layer) { if (layer is PdfLayer && ((PdfLayer)layer).Title != null) { - throw new ArgumentException("A title is not a layer"); + throw new ArgumentException(message: "A title is not a layer"); } if (LayerDepth == null) @@ -761,7 +760,7 @@ public void BeginLayer(IPdfOcg layer) if (layer is PdfLayerMembership) { - LayerDepth.Add(1); + LayerDepth.Add(item: 1); beginLayer2(layer); return; @@ -814,9 +813,9 @@ public void BeginMarkedContentSequence(PdfStructureElement struc) { ar = (PdfArray)obj; - if (!ar[0].IsNumber()) + if (!ar[idx: 0].IsNumber()) { - throw new ArgumentException("The structure has kids."); + throw new ArgumentException(message: "The structure has kids."); } } else @@ -828,7 +827,7 @@ public void BeginMarkedContentSequence(PdfStructureElement struc) dic.Put(PdfName.Pg, Writer.CurrentPage); dic.Put(PdfName.Mcid, new PdfNumber(mark)); ar.Add(dic); - struc.SetPageMark(Writer.PageNumber - 1, -1); + struc.SetPageMark(Writer.PageNumber - 1, mark: -1); } else { @@ -839,7 +838,10 @@ public void BeginMarkedContentSequence(PdfStructureElement struc) Pdf.IncMarkPoint(); _mcDepth++; - Content.Append(struc.Get(PdfName.S).GetBytes()).Append(" <> BDC") + Content.Append(struc.Get(PdfName.S).GetBytes()) + .Append(str: " <> BDC") .Append_i(Separator); } @@ -860,12 +862,12 @@ public void BeginMarkedContentSequence(PdfName tag, PdfDictionary property, bool if (property == null) { - Content.Append(tag.GetBytes()).Append(" BMC").Append_i(Separator); + Content.Append(tag.GetBytes()).Append(str: " BMC").Append_i(Separator); return; } - Content.Append(tag.GetBytes()).Append(' '); + Content.Append(tag.GetBytes()).Append(c: ' '); if (inline) { @@ -877,7 +879,7 @@ public void BeginMarkedContentSequence(PdfName tag, PdfDictionary property, bool if (Writer.PropertyExists(property)) { - objs = Writer.AddSimpleProperty(property, null); + objs = Writer.AddSimpleProperty(property, refi: null); } else { @@ -890,7 +892,7 @@ public void BeginMarkedContentSequence(PdfName tag, PdfDictionary property, bool Content.Append(name.GetBytes()); } - Content.Append(" BDC").Append_i(Separator); + Content.Append(str: " BDC").Append_i(Separator); ++_mcDepth; } @@ -899,7 +901,7 @@ public void BeginMarkedContentSequence(PdfName tag, PdfDictionary property, bool /// /// the tag public void BeginMarkedContentSequence(PdfName tag) - => BeginMarkedContentSequence(tag, null, false); + => BeginMarkedContentSequence(tag, property: null, inline: false); /// /// Starts the writing of text. @@ -908,13 +910,13 @@ public void BeginText() { if (_inText) { - throw new IllegalPdfSyntaxException("Unbalanced begin/end text operators."); + throw new IllegalPdfSyntaxException(message: "Unbalanced begin/end text operators."); } _inText = true; State.XTlm = 0; State.YTlm = 0; - Content.Append("BT").Append_i(Separator); + Content.Append(str: "BT").Append_i(Separator); } /// @@ -933,20 +935,15 @@ public void Circle(float x, float y, float r) CurveTo(x + r * b, y - r, x + r, y - r * b, x + r, y); } - public void Clip() - => Content.Append('W').Append_i(Separator); + public void Clip() => Content.Append(c: 'W').Append_i(Separator); - public void ClosePath() - => Content.Append('h').Append_i(Separator); + public void ClosePath() => Content.Append(c: 'h').Append_i(Separator); - public void ClosePathEoFillStroke() - => Content.Append("b*").Append_i(Separator); + public void ClosePathEoFillStroke() => Content.Append(str: "b*").Append_i(Separator); - public void ClosePathFillStroke() - => Content.Append('b').Append_i(Separator); + public void ClosePathFillStroke() => Content.Append(c: 'b').Append_i(Separator); - public void ClosePathStroke() - => Content.Append('s').Append_i(Separator); + public void ClosePathStroke() => Content.Append(c: 's').Append_i(Separator); /// /// Concatenate a matrix to the current transformation matrix. @@ -959,8 +956,8 @@ public void ClosePathStroke() /// an element of the transformation matrix public void ConcatCtm(float a, float b, float c, float d, float e, float f) { - Content.Append(a).Append(' ').Append(b).Append(' ').Append(c).Append(' '); - Content.Append(d).Append(' ').Append(e).Append(' ').Append(f).Append(" cm").Append_i(Separator); + Content.Append(a).Append(c: ' ').Append(b).Append(c: ' ').Append(c).Append(c: ' '); + Content.Append(d).Append(c: ' ').Append(e).Append(c: ' ').Append(f).Append(str: " cm").Append_i(Separator); } /// @@ -970,7 +967,7 @@ public void ConcatCtm(float a, float b, float c, float d, float e, float f) /// the bounding box height /// the appearance created public PdfAppearance CreateAppearance(float width, float height) - => CreateAppearance(width, height, null); + => CreateAppearance(width, height, forcedName: null); /// /// Create a new colored tiling pattern. @@ -986,9 +983,9 @@ public PdfPatternPainter CreatePattern(float width, float height, float xstep, f { CheckWriter(); - if (xstep.ApproxEquals(0.0f) || ystep.ApproxEquals(0.0f)) + if (xstep.ApproxEquals(d2: 0.0f) || ystep.ApproxEquals(d2: 0.0f)) { - throw new InvalidOperationException("XStep or YStep can not be ZERO."); + throw new InvalidOperationException(message: "XStep or YStep can not be ZERO."); } var painter = new PdfPatternPainter(Writer); @@ -1008,8 +1005,7 @@ public PdfPatternPainter CreatePattern(float width, float height, float xstep, f /// the width of the pattern /// the height of the pattern /// the PdfPatternPainter where the pattern will be created - public PdfPatternPainter CreatePattern(float width, float height) - => CreatePattern(width, height, width, height); + public PdfPatternPainter CreatePattern(float width, float height) => CreatePattern(width, height, width, height); /// /// Create a new uncolored tiling pattern. @@ -1026,9 +1022,9 @@ public PdfPatternPainter CreatePattern(float width, float height, float xstep, f { CheckWriter(); - if (xstep.ApproxEquals(0.0f) || ystep.ApproxEquals(0.0f)) + if (xstep.ApproxEquals(d2: 0.0f) || ystep.ApproxEquals(d2: 0.0f)) { - throw new InvalidOperationException("XStep or YStep can not be ZERO."); + throw new InvalidOperationException(message: "XStep or YStep can not be ZERO."); } var painter = new PdfPatternPainter(Writer, color); @@ -1063,22 +1059,46 @@ public PdfPatternPainter CreatePattern(float width, float height, BaseColor colo /// the bounding box width /// the bounding box height /// the templated created - public PdfTemplate CreateTemplate(float width, float height) - => CreateTemplate(width, height, null); + public PdfTemplate CreateTemplate(float width, float height) => CreateTemplate(width, height, forcedName: null); public void CurveFromTo(float x1, float y1, float x3, float y3) - => Content.Append(x1).Append(' ').Append(y1).Append(' ').Append(x3).Append(' ').Append(y3).Append(" y") + => Content.Append(x1) + .Append(c: ' ') + .Append(y1) + .Append(c: ' ') + .Append(x3) + .Append(c: ' ') + .Append(y3) + .Append(str: " y") .Append_i(Separator); public void CurveTo(double x1, double y1, double x2, double y2, double x3, double y3) - => Content.Append(x1).Append(' ').Append(y1).Append(' ').Append(x2).Append(' ').Append(y2).Append(' ') - .Append(x3).Append(' ').Append(y3).Append(" c").Append_i(Separator); + => Content.Append(x1) + .Append(c: ' ') + .Append(y1) + .Append(c: ' ') + .Append(x2) + .Append(c: ' ') + .Append(y2) + .Append(c: ' ') + .Append(x3) + .Append(c: ' ') + .Append(y3) + .Append(str: " c") + .Append_i(Separator); public void CurveTo(float x1, float y1, float x2, float y2, float x3, float y3) => CurveTo(x1, y1, x2, y2, x3, (double)y3); public void CurveTo(float x2, float y2, float x3, float y3) - => Content.Append(x2).Append(' ').Append(y2).Append(' ').Append(x3).Append(' ').Append(y3).Append(" v") + => Content.Append(x2) + .Append(c: ' ') + .Append(y2) + .Append(c: ' ') + .Append(x3) + .Append(c: ' ') + .Append(y3) + .Append(str: " v") .Append_i(Separator); public void DrawButton(float llx, float lly, float urx, float ury, string text, BaseFont bf, float size) @@ -1098,32 +1118,32 @@ public void DrawButton(float llx, float lly, float urx, float ury, string text, } // black rectangle not filled - SetColorStroke(new BaseColor(0x00, 0x00, 0x00)); - SetLineWidth(1); - SetLineCap(0); + SetColorStroke(new BaseColor(red: 0x00, green: 0x00, blue: 0x00)); + SetLineWidth(value: 1); + SetLineCap(value: 0); Rectangle(llx, lly, urx - llx, ury - lly); Stroke(); // silver rectangle filled - SetLineWidth(1); - SetLineCap(0); - SetColorFill(new BaseColor(0xC0, 0xC0, 0xC0)); + SetLineWidth(value: 1); + SetLineCap(value: 0); + SetColorFill(new BaseColor(red: 0xC0, green: 0xC0, blue: 0xC0)); Rectangle(llx + 0.5f, lly + 0.5f, urx - llx - 1f, ury - lly - 1f); Fill(); // white lines - SetColorStroke(new BaseColor(0xFF, 0xFF, 0xFF)); - SetLineWidth(1); - SetLineCap(0); + SetColorStroke(new BaseColor(red: 0xFF, green: 0xFF, blue: 0xFF)); + SetLineWidth(value: 1); + SetLineCap(value: 0); MoveTo(llx + 1f, lly + 1f); LineTo(llx + 1f, ury - 1f); LineTo(urx - 1f, ury - 1f); Stroke(); // dark grey lines - SetColorStroke(new BaseColor(0xA0, 0xA0, 0xA0)); - SetLineWidth(1); - SetLineCap(0); + SetColorStroke(new BaseColor(red: 0xA0, green: 0xA0, blue: 0xA0)); + SetLineWidth(value: 1); + SetLineCap(value: 0); MoveTo(llx + 1f, lly + 1f); LineTo(urx - 1f, lly + 1f); LineTo(urx - 1f, ury - 1f); @@ -1133,7 +1153,7 @@ public void DrawButton(float llx, float lly, float urx, float ury, string text, ResetRgbColorFill(); BeginText(); SetFontAndSize(bf, size); - ShowTextAligned(ALIGN_CENTER, text, llx + (urx - llx) / 2, lly + (ury - lly - size) / 2, 0); + ShowTextAligned(ALIGN_CENTER, text, llx + (urx - llx) / 2, lly + (ury - lly - size) / 2, rotation: 0); EndText(); } @@ -1154,33 +1174,33 @@ public void DrawRadioField(float llx, float lly, float urx, float ury, bool on) } // silver circle - SetLineWidth(1); - SetLineCap(1); - SetColorStroke(new BaseColor(0xC0, 0xC0, 0xC0)); - Arc(llx + 1f, lly + 1f, urx - 1f, ury - 1f, 0f, 360f); + SetLineWidth(value: 1); + SetLineCap(value: 1); + SetColorStroke(new BaseColor(red: 0xC0, green: 0xC0, blue: 0xC0)); + Arc(llx + 1f, lly + 1f, urx - 1f, ury - 1f, startAng: 0f, extent: 360f); Stroke(); // gray circle-segment - SetLineWidth(1); - SetLineCap(1); - SetColorStroke(new BaseColor(0xA0, 0xA0, 0xA0)); - Arc(llx + 0.5f, lly + 0.5f, urx - 0.5f, ury - 0.5f, 45, 180); + SetLineWidth(value: 1); + SetLineCap(value: 1); + SetColorStroke(new BaseColor(red: 0xA0, green: 0xA0, blue: 0xA0)); + Arc(llx + 0.5f, lly + 0.5f, urx - 0.5f, ury - 0.5f, startAng: 45, extent: 180); Stroke(); // black circle-segment - SetLineWidth(1); - SetLineCap(1); - SetColorStroke(new BaseColor(0x00, 0x00, 0x00)); - Arc(llx + 1.5f, lly + 1.5f, urx - 1.5f, ury - 1.5f, 45, 180); + SetLineWidth(value: 1); + SetLineCap(value: 1); + SetColorStroke(new BaseColor(red: 0x00, green: 0x00, blue: 0x00)); + Arc(llx + 1.5f, lly + 1.5f, urx - 1.5f, ury - 1.5f, startAng: 45, extent: 180); Stroke(); if (on) { // gray circle - SetLineWidth(1); - SetLineCap(1); - SetColorFill(new BaseColor(0x00, 0x00, 0x00)); - Arc(llx + 4f, lly + 4f, urx - 4f, ury - 4f, 0, 360); + SetLineWidth(value: 1); + SetLineCap(value: 1); + SetColorFill(new BaseColor(red: 0x00, green: 0x00, blue: 0x00)); + Arc(llx + 4f, lly + 4f, urx - 4f, ury - 4f, startAng: 0, extent: 360); Fill(); } } @@ -1202,41 +1222,41 @@ public void DrawTextField(float llx, float lly, float urx, float ury) } // silver rectangle not filled - SetColorStroke(new BaseColor(0xC0, 0xC0, 0xC0)); - SetLineWidth(1); - SetLineCap(0); + SetColorStroke(new BaseColor(red: 0xC0, green: 0xC0, blue: 0xC0)); + SetLineWidth(value: 1); + SetLineCap(value: 0); Rectangle(llx, lly, urx - llx, ury - lly); Stroke(); // white rectangle filled - SetLineWidth(1); - SetLineCap(0); - SetColorFill(new BaseColor(0xFF, 0xFF, 0xFF)); + SetLineWidth(value: 1); + SetLineCap(value: 0); + SetColorFill(new BaseColor(red: 0xFF, green: 0xFF, blue: 0xFF)); Rectangle(llx + 0.5f, lly + 0.5f, urx - llx - 1f, ury - lly - 1f); Fill(); // silver lines - SetColorStroke(new BaseColor(0xC0, 0xC0, 0xC0)); - SetLineWidth(1); - SetLineCap(0); + SetColorStroke(new BaseColor(red: 0xC0, green: 0xC0, blue: 0xC0)); + SetLineWidth(value: 1); + SetLineCap(value: 0); MoveTo(llx + 1f, lly + 1.5f); LineTo(urx - 1.5f, lly + 1.5f); LineTo(urx - 1.5f, ury - 1f); Stroke(); // gray lines - SetColorStroke(new BaseColor(0xA0, 0xA0, 0xA0)); - SetLineWidth(1); - SetLineCap(0); + SetColorStroke(new BaseColor(red: 0xA0, green: 0xA0, blue: 0xA0)); + SetLineWidth(value: 1); + SetLineCap(value: 0); MoveTo(llx + 1f, lly + 1); LineTo(llx + 1f, ury - 1f); LineTo(urx - 1f, ury - 1f); Stroke(); // black lines - SetColorStroke(new BaseColor(0x00, 0x00, 0x00)); - SetLineWidth(1); - SetLineCap(0); + SetColorStroke(new BaseColor(red: 0x00, green: 0x00, blue: 0x00)); + SetLineWidth(value: 1); + SetLineCap(value: 0); MoveTo(llx + 2f, lly + 2f); LineTo(llx + 2f, ury - 2f); LineTo(urx - 2f, ury - 2f); @@ -1250,8 +1270,7 @@ public void DrawTextField(float llx, float lly, float urx, float ury) /// a corner of the enclosing rectangle /// a corner of the enclosing rectangle /// a corner of the enclosing rectangle - public void Ellipse(float x1, float y1, float x2, float y2) - => Arc(x1, y1, x2, y2, 0f, 360f); + public void Ellipse(float x1, float y1, float x2, float y2) => Arc(x1, y1, x2, y2, startAng: 0f, extent: 360f); /// /// Ends a layer controled graphic block. It will end the most recent open block. @@ -1267,12 +1286,12 @@ public void EndLayer() } else { - throw new IllegalPdfSyntaxException("Unbalanced layer operators."); + throw new IllegalPdfSyntaxException(message: "Unbalanced layer operators."); } while (n-- > 0) { - Content.Append("EMC").Append_i(Separator); + Content.Append(str: "EMC").Append_i(Separator); } } @@ -1283,11 +1302,11 @@ public void EndMarkedContentSequence() { if (_mcDepth == 0) { - throw new IllegalPdfSyntaxException("Unbalanced begin/end marked content operators."); + throw new IllegalPdfSyntaxException(message: "Unbalanced begin/end marked content operators."); } --_mcDepth; - Content.Append("EMC").Append_i(Separator); + Content.Append(str: "EMC").Append_i(Separator); } /// @@ -1297,27 +1316,22 @@ public void EndText() { if (!_inText) { - throw new IllegalPdfSyntaxException("Unbalanced begin/end text operators."); + throw new IllegalPdfSyntaxException(message: "Unbalanced begin/end text operators."); } _inText = false; - Content.Append("ET").Append_i(Separator); + Content.Append(str: "ET").Append_i(Separator); } - public void EoClip() - => Content.Append("W*").Append_i(Separator); + public void EoClip() => Content.Append(str: "W*").Append_i(Separator); - public void EoFill() - => Content.Append("f*").Append_i(Separator); + public void EoFill() => Content.Append(str: "f*").Append_i(Separator); - public void EoFillStroke() - => Content.Append("B*").Append_i(Separator); + public void EoFillStroke() => Content.Append(str: "B*").Append_i(Separator); - public void Fill() - => Content.Append('f').Append_i(Separator); + public void Fill() => Content.Append(c: 'f').Append_i(Separator); - public void FillStroke() - => Content.Append('B').Append_i(Separator); + public void FillStroke() => Content.Append(c: 'B').Append_i(Separator); public float GetEffectiveStringWidth(string text, bool kerned) { @@ -1339,15 +1353,15 @@ public float GetEffectiveStringWidth(string text, bool kerned) w = bf.GetWidthPoint(text, State.size); } - if (State.CharSpace.ApproxNotEqual(0.0f) && text.Length > 1) + if (State.CharSpace.ApproxNotEqual(b: 0.0f) && text.Length > 1) { w += State.CharSpace * (text.Length - 1); } var ft = bf.FontType; - if (State.WordSpace.ApproxNotEqual(0.0f) && - (ft == BaseFont.FONT_TYPE_T1 || ft == BaseFont.FONT_TYPE_TT || ft == BaseFont.FONT_TYPE_T3)) + if (State.WordSpace.ApproxNotEqual(b: 0.0f) && (ft == BaseFont.FONT_TYPE_T1 || ft == BaseFont.FONT_TYPE_TT || + ft == BaseFont.FONT_TYPE_T3)) { for (var i = 0; i < text.Length - 1; i++) { @@ -1358,7 +1372,7 @@ public float GetEffectiveStringWidth(string text, bool kerned) } } - if (State.Scale.ApproxNotEqual(100.0f)) + if (State.Scale.ApproxNotEqual(b: 100.0f)) { w = w * State.Scale / 100.0f; } @@ -1368,10 +1382,9 @@ public float GetEffectiveStringWidth(string text, bool kerned) } public void LineTo(double x, double y) - => Content.Append(x).Append(' ').Append(y).Append(" l").Append_i(Separator); + => Content.Append(x).Append(c: ' ').Append(y).Append(str: " l").Append_i(Separator); - public void LineTo(float x, float y) - => LineTo(x, (double)y); + public void LineTo(float x, float y) => LineTo(x, (double)y); /// /// The local destination to where a local goto with the same @@ -1413,7 +1426,7 @@ public void MoveText(float x, float y) { State.XTlm += x; State.YTlm += y; - Content.Append(x).Append(' ').Append(y).Append(" Td").Append_i(Separator); + Content.Append(x).Append(c: ' ').Append(y).Append(str: " Td").Append_i(Separator); } /// @@ -1427,11 +1440,11 @@ public void MoveTextWithLeading(float x, float y) State.XTlm += x; State.YTlm += y; State.leading = -y; - Content.Append(x).Append(' ').Append(y).Append(" TD").Append_i(Separator); + Content.Append(x).Append(c: ' ').Append(y).Append(str: " TD").Append_i(Separator); } public void MoveTo(double x, double y) - => Content.Append(x).Append(' ').Append(y).Append(" m").Append_i(Separator); + => Content.Append(x).Append(c: ' ').Append(y).Append(str: " m").Append_i(Separator); /// /// Moves to the next line and shows text . @@ -1441,7 +1454,7 @@ public void NewlineShowText(string text) { State.YTlm -= State.leading; showText2(text); - Content.Append('\'').Append_i(Separator); + Content.Append(c: '\'').Append_i(Separator); } /// @@ -1453,9 +1466,9 @@ public void NewlineShowText(string text) public void NewlineShowText(float wordSpacing, float charSpacing, string text) { State.YTlm -= State.leading; - Content.Append(wordSpacing).Append(' ').Append(charSpacing); + Content.Append(wordSpacing).Append(c: ' ').Append(charSpacing); showText2(text); - Content.Append("\"").Append_i(Separator); + Content.Append(str: "\"").Append_i(Separator); // The " operator sets charSpace and wordSpace into graphics state // (cfr PDF reference v1.6, table 5.6) @@ -1469,11 +1482,10 @@ public void NewlineShowText(float wordSpacing, float charSpacing, string text) public void NewlineText() { State.YTlm -= State.leading; - Content.Append("T*").Append_i(Separator); + Content.Append(str: "T*").Append_i(Separator); } - public void NewPath() - => Content.Append('n').Append_i(Separator); + public void NewPath() => Content.Append(c: 'n').Append_i(Separator); /// /// Paints using a shading object. @@ -1489,7 +1501,7 @@ public virtual void PaintShading(PdfShading shading) Writer.AddSimpleShading(shading); var prs = PageResources; var name = prs.AddShading(shading.ShadingName, shading.ShadingReference); - Content.Append(name.GetBytes()).Append(" sh").Append_i(Separator); + Content.Append(name.GetBytes()).Append(str: " sh").Append_i(Separator); var details = shading.ColorDetails; if (details != null) @@ -1513,7 +1525,14 @@ public virtual void PaintShading(PdfShadingPattern shading) } public void Rectangle(float x, float y, float w, float h) - => Content.Append(x).Append(' ').Append(y).Append(' ').Append(w).Append(' ').Append(h).Append(" re") + => Content.Append(x) + .Append(c: ' ') + .Append(y) + .Append(c: ' ') + .Append(w) + .Append(c: ' ') + .Append(h) + .Append(str: " re") .Append_i(Separator); public void Rectangle(Rectangle rectangle) @@ -1661,8 +1680,7 @@ public void RemoteGoto(string filename, int page, float llx, float lly, float ur /// Makes this PdfContentByte empty. /// Calls reset( true ) /// - public void Reset() - => Reset(true); + public void Reset() => Reset(validateContent: true); /// /// Makes this PdfContentByte empty. @@ -1681,23 +1699,17 @@ public void Reset(bool validateContent) State = new GraphicState(); } - public virtual void ResetCmykColorFill() - => Content.Append("0 0 0 1 k").Append_i(Separator); + public virtual void ResetCmykColorFill() => Content.Append(str: "0 0 0 1 k").Append_i(Separator); - public virtual void ResetCmykColorStroke() - => Content.Append("0 0 0 1 K").Append_i(Separator); + public virtual void ResetCmykColorStroke() => Content.Append(str: "0 0 0 1 K").Append_i(Separator); - public virtual void ResetGrayFill() - => Content.Append("0 g").Append_i(Separator); + public virtual void ResetGrayFill() => Content.Append(str: "0 g").Append_i(Separator); - public virtual void ResetGrayStroke() - => Content.Append("0 G").Append_i(Separator); + public virtual void ResetGrayStroke() => Content.Append(str: "0 G").Append_i(Separator); - public virtual void ResetRgbColorFill() - => Content.Append("0 g").Append_i(Separator); + public virtual void ResetRgbColorFill() => Content.Append(str: "0 g").Append_i(Separator); - public virtual void ResetRgbColorStroke() - => Content.Append("0 G").Append_i(Separator); + public virtual void ResetRgbColorStroke() => Content.Append(str: "0 G").Append_i(Separator); /// /// Restores the graphic state. saveState and @@ -1705,12 +1717,12 @@ public virtual void ResetRgbColorStroke() /// public void RestoreState() { - Content.Append('Q').Append_i(Separator); + Content.Append(c: 'Q').Append_i(Separator); var idx = StateList.Count - 1; if (idx < 0) { - throw new IllegalPdfSyntaxException("Unbalanced save/restore state operators."); + throw new IllegalPdfSyntaxException(message: "Unbalanced save/restore state operators."); } State = StateList[idx]; @@ -1771,22 +1783,22 @@ public void SanityCheck() { if (_mcDepth != 0) { - throw new IllegalPdfSyntaxException("Unbalanced marked content operators."); + throw new IllegalPdfSyntaxException(message: "Unbalanced marked content operators."); } if (_inText) { - throw new IllegalPdfSyntaxException("Unbalanced begin/end text operators."); + throw new IllegalPdfSyntaxException(message: "Unbalanced begin/end text operators."); } if (LayerDepth != null && LayerDepth.Count > 0) { - throw new IllegalPdfSyntaxException("Unbalanced layer operators."); + throw new IllegalPdfSyntaxException(message: "Unbalanced layer operators."); } if (StateList.Count > 0) { - throw new IllegalPdfSyntaxException("Unbalanced save/restore state operators."); + throw new IllegalPdfSyntaxException(message: "Unbalanced save/restore state operators."); } } @@ -1796,7 +1808,7 @@ public void SanityCheck() /// public void SaveState() { - Content.Append('q').Append_i(Separator); + Content.Append(c: 'q').Append_i(Separator); StateList.Add(new GraphicState(State)); } @@ -1818,43 +1830,43 @@ public virtual void SetAction(PdfAction action, float llx, float lly, float urx, public void SetCharacterSpacing(float value) { State.CharSpace = value; - Content.Append(value).Append(" Tc").Append_i(Separator); + Content.Append(value).Append(str: " Tc").Append_i(Separator); } public virtual void SetCmykColorFill(int cyan, int magenta, int yellow, int black) { Content.Append((float)(cyan & 0xFF) / 0xFF); - Content.Append(' '); + Content.Append(c: ' '); Content.Append((float)(magenta & 0xFF) / 0xFF); - Content.Append(' '); + Content.Append(c: ' '); Content.Append((float)(yellow & 0xFF) / 0xFF); - Content.Append(' '); + Content.Append(c: ' '); Content.Append((float)(black & 0xFF) / 0xFF); - Content.Append(" k").Append_i(Separator); + Content.Append(str: " k").Append_i(Separator); } public virtual void SetCmykColorFillF(float cyan, float magenta, float yellow, float black) { helperCmyk(cyan, magenta, yellow, black); - Content.Append(" k").Append_i(Separator); + Content.Append(str: " k").Append_i(Separator); } public virtual void SetCmykColorStroke(int cyan, int magenta, int yellow, int black) { Content.Append((float)(cyan & 0xFF) / 0xFF); - Content.Append(' '); + Content.Append(c: ' '); Content.Append((float)(magenta & 0xFF) / 0xFF); - Content.Append(' '); + Content.Append(c: ' '); Content.Append((float)(yellow & 0xFF) / 0xFF); - Content.Append(' '); + Content.Append(c: ' '); Content.Append((float)(black & 0xFF) / 0xFF); - Content.Append(" K").Append_i(Separator); + Content.Append(str: " K").Append_i(Separator); } public virtual void SetCmykColorStrokeF(float cyan, float magenta, float yellow, float black) { helperCmyk(cyan, magenta, yellow, black); - Content.Append(" K").Append_i(Separator); + Content.Append(str: " K").Append_i(Separator); } /// @@ -1928,7 +1940,7 @@ public virtual void SetColorFill(PdfSpotColor sp, float tint) var prs = PageResources; var name = State.ColorDetails.ColorName; name = prs.AddColor(name, State.ColorDetails.IndirectReference); - Content.Append(name.GetBytes()).Append(" cs ").Append(tint).Append(" scn").Append_i(Separator); + Content.Append(name.GetBytes()).Append(str: " cs ").Append(tint).Append(str: " scn").Append_i(Separator); } /// @@ -2002,7 +2014,7 @@ public virtual void SetColorStroke(PdfSpotColor sp, float tint) var prs = PageResources; var name = State.ColorDetails.ColorName; name = prs.AddColor(name, State.ColorDetails.IndirectReference); - Content.Append(name.GetBytes()).Append(" CS ").Append(tint).Append(" SCN").Append_i(Separator); + Content.Append(name.GetBytes()).Append(str: " CS ").Append(tint).Append(str: " SCN").Append_i(Separator); } /// @@ -2021,7 +2033,7 @@ public void SetFlatness(float value) { if (value >= 0 && value <= 100) { - Content.Append(value).Append(" i").Append_i(Separator); + Content.Append(value).Append(str: " i").Append_i(Separator); } } @@ -2049,14 +2061,12 @@ public virtual void SetFontAndSize(BaseFont bf, float size) var prs = PageResources; var name = State.FontDetails.FontName; name = prs.AddFont(name, State.FontDetails.IndirectReference); - Content.Append(name.GetBytes()).Append(' ').Append(size).Append(" Tf").Append_i(Separator); + Content.Append(name.GetBytes()).Append(c: ' ').Append(size).Append(str: " Tf").Append_i(Separator); } - public virtual void SetGrayFill(float value) - => Content.Append(value).Append(" g").Append_i(Separator); + public virtual void SetGrayFill(float value) => Content.Append(value).Append(str: " g").Append_i(Separator); - public virtual void SetGrayStroke(float value) - => Content.Append(value).Append(" G").Append_i(Separator); + public virtual void SetGrayStroke(float value) => Content.Append(value).Append(str: " G").Append_i(Separator); /// /// Draws a TextField. @@ -2076,7 +2086,7 @@ public void SetGState(PdfGState gstate) var obj = Writer.AddSimpleExtGState(gstate); var prs = PageResources; var name = prs.AddExtGState((PdfName)obj[0], (PdfIndirectReference)obj[1]); - Content.Append(name.GetBytes()).Append(" gs").Append_i(Separator); + Content.Append(name.GetBytes()).Append(str: " gs").Append_i(Separator); } /// @@ -2086,7 +2096,7 @@ public void SetGState(PdfGState gstate) public void SetHorizontalScaling(float value) { State.Scale = value; - Content.Append(value).Append(" Tz").Append_i(Separator); + Content.Append(value).Append(str: " Tz").Append_i(Separator); } /// @@ -2096,25 +2106,31 @@ public void SetHorizontalScaling(float value) public void SetLeading(float v) { State.leading = v; - Content.Append(v).Append(" TL").Append_i(Separator); + Content.Append(v).Append(str: " TL").Append_i(Separator); } public void SetLineCap(int value) { if (value >= 0 && value <= 2) { - Content.Append(value).Append(" J").Append_i(Separator); + Content.Append(value).Append(str: " J").Append_i(Separator); } } public void SetLineDash(float value) - => Content.Append("[] ").Append(value).Append(" d").Append_i(Separator); + => Content.Append(str: "[] ").Append(value).Append(str: " d").Append_i(Separator); public void SetLineDash(float unitsOn, float phase) - => Content.Append('[').Append(unitsOn).Append("] ").Append(phase).Append(" d").Append_i(Separator); + => Content.Append(c: '[').Append(unitsOn).Append(str: "] ").Append(phase).Append(str: " d").Append_i(Separator); public void SetLineDash(float unitsOn, float unitsOff, float phase) - => Content.Append('[').Append(unitsOn).Append(' ').Append(unitsOff).Append("] ").Append(phase).Append(" d") + => Content.Append(c: '[') + .Append(unitsOn) + .Append(c: ' ') + .Append(unitsOff) + .Append(str: "] ") + .Append(phase) + .Append(str: " d") .Append_i(Separator); public void SetLineDash(float[] array, float phase) @@ -2124,7 +2140,7 @@ public void SetLineDash(float[] array, float phase) throw new ArgumentNullException(nameof(array)); } - Content.Append('['); + Content.Append(c: '['); for (var i = 0; i < array.Length; i++) { @@ -2132,50 +2148,46 @@ public void SetLineDash(float[] array, float phase) if (i < array.Length - 1) { - Content.Append(' '); + Content.Append(c: ' '); } } - Content.Append("] ").Append(phase).Append(" d").Append_i(Separator); + Content.Append(str: "] ").Append(phase).Append(str: " d").Append_i(Separator); } public void SetLineJoin(int value) { if (value >= 0 && value <= 2) { - Content.Append(value).Append(" j").Append_i(Separator); + Content.Append(value).Append(str: " j").Append_i(Separator); } } - public void SetLineWidth(float value) - => Content.Append(value).Append(" w").Append_i(Separator); + public void SetLineWidth(float value) => Content.Append(value).Append(str: " w").Append_i(Separator); /// /// Outputs a string directly to the content. /// /// the string - public void SetLiteral(string s) - => Content.Append(s); + public void SetLiteral(string s) => Content.Append(s); /// /// Outputs a char directly to the content. /// /// the char - public void SetLiteral(char c) - => Content.Append(c); + public void SetLiteral(char c) => Content.Append(c); /// /// Outputs a float directly to the content. /// /// the float - public void SetLiteral(float n) - => Content.Append(n); + public void SetLiteral(float n) => Content.Append(n); public void SetMiterLimit(float value) { if (value > 1) { - Content.Append(value).Append(" M").Append_i(Separator); + Content.Append(value).Append(str: " M").Append_i(Separator); } } @@ -2203,7 +2215,10 @@ public virtual void SetPatternFill(PdfPatternPainter p) var name = Writer.AddSimplePattern(p); name = prs.AddPattern(name, p.IndirectReference); - Content.Append(PdfName.Pattern.GetBytes()).Append(" cs ").Append(name.GetBytes()).Append(" scn") + Content.Append(PdfName.Pattern.GetBytes()) + .Append(str: " cs ") + .Append(name.GetBytes()) + .Append(str: " scn") .Append_i(Separator); } @@ -2225,7 +2240,7 @@ public virtual void SetPatternFill(PdfPatternPainter p, BaseColor color) } else { - SetPatternFill(p, color, 0); + SetPatternFill(p, color, tint: 0); } } @@ -2251,7 +2266,7 @@ public virtual void SetPatternFill(PdfPatternPainter p, BaseColor color, float t if (!p.IsStencil()) { - throw new InvalidOperationException("An uncolored pattern was expected."); + throw new InvalidOperationException(message: "An uncolored pattern was expected."); } var prs = PageResources; @@ -2259,9 +2274,9 @@ public virtual void SetPatternFill(PdfPatternPainter p, BaseColor color, float t name = prs.AddPattern(name, p.IndirectReference); var csDetail = Writer.AddSimplePatternColorspace(color); var cName = prs.AddColor(csDetail.ColorName, csDetail.IndirectReference); - Content.Append(cName.GetBytes()).Append(" cs").Append_i(Separator); + Content.Append(cName.GetBytes()).Append(str: " cs").Append_i(Separator); OutputColorNumbers(color, tint); - Content.Append(' ').Append(name.GetBytes()).Append(" scn").Append_i(Separator); + Content.Append(c: ' ').Append(name.GetBytes()).Append(str: " scn").Append_i(Separator); } /// @@ -2282,7 +2297,7 @@ public virtual void SetPatternStroke(PdfPatternPainter p, BaseColor color) } else { - SetPatternStroke(p, color, 0); + SetPatternStroke(p, color, tint: 0); } } @@ -2308,7 +2323,7 @@ public virtual void SetPatternStroke(PdfPatternPainter p, BaseColor color, float if (!p.IsStencil()) { - throw new InvalidOperationException("An uncolored pattern was expected."); + throw new InvalidOperationException(message: "An uncolored pattern was expected."); } var prs = PageResources; @@ -2316,9 +2331,9 @@ public virtual void SetPatternStroke(PdfPatternPainter p, BaseColor color, float name = prs.AddPattern(name, p.IndirectReference); var csDetail = Writer.AddSimplePatternColorspace(color); var cName = prs.AddColor(csDetail.ColorName, csDetail.IndirectReference); - Content.Append(cName.GetBytes()).Append(" CS").Append_i(Separator); + Content.Append(cName.GetBytes()).Append(str: " CS").Append_i(Separator); OutputColorNumbers(color, tint); - Content.Append(' ').Append(name.GetBytes()).Append(" SCN").Append_i(Separator); + Content.Append(c: ' ').Append(name.GetBytes()).Append(str: " SCN").Append_i(Separator); } /// @@ -2345,32 +2360,35 @@ public virtual void SetPatternStroke(PdfPatternPainter p) var name = Writer.AddSimplePattern(p); name = prs.AddPattern(name, p.IndirectReference); - Content.Append(PdfName.Pattern.GetBytes()).Append(" CS ").Append(name.GetBytes()).Append(" SCN") + Content.Append(PdfName.Pattern.GetBytes()) + .Append(str: " CS ") + .Append(name.GetBytes()) + .Append(str: " SCN") .Append_i(Separator); } public virtual void SetRgbColorFill(int red, int green, int blue) { helperRgb((float)(red & 0xFF) / 0xFF, (float)(green & 0xFF) / 0xFF, (float)(blue & 0xFF) / 0xFF); - Content.Append(" rg").Append_i(Separator); + Content.Append(str: " rg").Append_i(Separator); } public virtual void SetRgbColorFillF(float red, float green, float blue) { helperRgb(red, green, blue); - Content.Append(" rg").Append_i(Separator); + Content.Append(str: " rg").Append_i(Separator); } public virtual void SetRgbColorStroke(int red, int green, int blue) { helperRgb((float)(red & 0xFF) / 0xFF, (float)(green & 0xFF) / 0xFF, (float)(blue & 0xFF) / 0xFF); - Content.Append(" RG").Append_i(Separator); + Content.Append(str: " RG").Append_i(Separator); } public virtual void SetRgbColorStrokeF(float red, float green, float blue) { helperRgb(red, green, blue); - Content.Append(" RG").Append_i(Separator); + Content.Append(str: " RG").Append_i(Separator); } /// @@ -2388,7 +2406,10 @@ public virtual void SetShadingFill(PdfShadingPattern shading) var prs = PageResources; var name = prs.AddPattern(shading.PatternName, shading.PatternReference); - Content.Append(PdfName.Pattern.GetBytes()).Append(" cs ").Append(name.GetBytes()).Append(" scn") + Content.Append(PdfName.Pattern.GetBytes()) + .Append(str: " cs ") + .Append(name.GetBytes()) + .Append(str: " scn") .Append_i(Separator); var details = shading.ColorDetails; @@ -2414,7 +2435,10 @@ public virtual void SetShadingStroke(PdfShadingPattern shading) var prs = PageResources; var name = prs.AddPattern(shading.PatternName, shading.PatternReference); - Content.Append(PdfName.Pattern.GetBytes()).Append(" CS ").Append(name.GetBytes()).Append(" SCN") + Content.Append(PdfName.Pattern.GetBytes()) + .Append(str: " CS ") + .Append(name.GetBytes()) + .Append(str: " SCN") .Append_i(Separator); var details = shading.ColorDetails; @@ -2440,8 +2464,19 @@ public void SetTextMatrix(float a, float b, float c, float d, float x, float y) State.XTlm = x; State.YTlm = y; - Content.Append(a).Append(' ').Append(b).Append_i(' ').Append(c).Append_i(' ').Append(d).Append_i(' ').Append(x) - .Append_i(' ').Append(y).Append(" Tm").Append_i(Separator); + Content.Append(a) + .Append(c: ' ') + .Append(b) + .Append_i(b: ' ') + .Append(c) + .Append_i(b: ' ') + .Append(d) + .Append_i(b: ' ') + .Append(x) + .Append_i(b: ' ') + .Append(y) + .Append(str: " Tm") + .Append_i(Separator); } /// @@ -2450,23 +2485,20 @@ public void SetTextMatrix(float a, float b, float c, float d, float x, float y) /// /// operand 3,1 in the matrix /// operand 3,2 in the matrix - public void SetTextMatrix(float x, float y) - => SetTextMatrix(1, 0, 0, 1, x, y); + public void SetTextMatrix(float x, float y) => SetTextMatrix(a: 1, b: 0, c: 0, d: 1, x, y); /// /// Sets the text rendering parameter. /// /// a parameter - public void SetTextRenderingMode(int value) - => Content.Append(value).Append(" Tr").Append_i(Separator); + public void SetTextRenderingMode(int value) => Content.Append(value).Append(str: " Tr").Append_i(Separator); /// /// Sets the text rise parameter. /// This allows to write text in subscript or basescript mode. /// /// a parameter - public void SetTextRise(float value) - => Content.Append(value).Append(" Ts").Append_i(Separator); + public void SetTextRise(float value) => Content.Append(value).Append(str: " Ts").Append_i(Separator); /// /// Sets the word spacing parameter. @@ -2474,7 +2506,7 @@ public void SetTextRise(float value) public void SetWordSpacing(float value) { State.WordSpace = value; - Content.Append(value).Append(" Tw").Append_i(Separator); + Content.Append(value).Append(str: " Tw").Append_i(Separator); } /// @@ -2484,7 +2516,7 @@ public void SetWordSpacing(float value) public void ShowText(string text) { showText2(text); - Content.Append("Tj").Append_i(Separator); + Content.Append(str: "Tj").Append_i(Separator); } /// @@ -2500,10 +2532,10 @@ public void ShowText(PdfTextArray text) if (State.FontDetails == null) { - throw new InvalidOperationException("Font and size must be set before writing any text"); + throw new InvalidOperationException(message: "Font and size must be set before writing any text"); } - Content.Append('['); + Content.Append(c: '['); var arrayList = text.ArrayList; var lastWasNumber = false; @@ -2520,7 +2552,7 @@ public void ShowText(PdfTextArray text) { if (lastWasNumber) { - Content.Append(' '); + Content.Append(c: ' '); } else { @@ -2531,7 +2563,7 @@ public void ShowText(PdfTextArray text) } } - Content.Append("]TJ").Append_i(Separator); + Content.Append(str: "]TJ").Append_i(Separator); } /// @@ -2543,7 +2575,7 @@ public void ShowText(PdfTextArray text) /// the y pivot position /// the rotation to be applied in degrees counterclockwise public void ShowTextAligned(int alignment, string text, float x, float y, float rotation) - => showTextAligned(alignment, text, x, y, rotation, false); + => showTextAligned(alignment, text, x, y, rotation, kerned: false); /// /// Shows text kerned right, left or center aligned with rotation. @@ -2554,7 +2586,7 @@ public void ShowTextAligned(int alignment, string text, float x, float y, float /// the y pivot position /// the rotation to be applied in degrees counterclockwise public void ShowTextAlignedKerned(int alignment, string text, float x, float y, float rotation) - => showTextAligned(alignment, text, x, y, rotation, true); + => showTextAligned(alignment, text, x, y, rotation, kerned: true); /// /// Shows the text kerned. @@ -2564,7 +2596,7 @@ public void ShowTextKerned(string text) { if (State.FontDetails == null) { - throw new InvalidOperationException("Font and size must be set before writing any text"); + throw new InvalidOperationException(message: "Font and size must be set before writing any text"); } var bf = State.FontDetails.BaseFont; @@ -2579,8 +2611,7 @@ public void ShowTextKerned(string text) } } - public void Stroke() - => Content.Append('S').Append_i(Separator); + public void Stroke() => Content.Append(c: 'S').Append_i(Separator); public byte[] ToPdf(PdfWriter writer) { @@ -2589,8 +2620,7 @@ public byte[] ToPdf(PdfWriter writer) return Content.ToByteArray(); } - public override string ToString() - => Content.ToString(); + public override string ToString() => Content.ToString(); /// /// Adds a variable width border to the current path. @@ -2820,7 +2850,7 @@ internal static byte[] EscapeString(byte[] b) /// internal static void EscapeString(byte[] b, ByteBuffer content) { - content.Append_i('('); + content.Append_i(b: '('); for (var k = 0; k < b.Length; ++k) { @@ -2829,29 +2859,29 @@ internal static void EscapeString(byte[] b, ByteBuffer content) switch ((int)c) { case '\r': - content.Append("\\r"); + content.Append(str: "\\r"); break; case '\n': - content.Append("\\n"); + content.Append(str: "\\n"); break; case '\t': - content.Append("\\t"); + content.Append(str: "\\t"); break; case '\b': - content.Append("\\b"); + content.Append(str: "\\b"); break; case '\f': - content.Append("\\f"); + content.Append(str: "\\f"); break; case '(': case ')': case '\\': - content.Append_i('\\').Append_i(c); + content.Append_i(b: '\\').Append_i(c); break; default: @@ -2861,11 +2891,10 @@ internal static void EscapeString(byte[] b, ByteBuffer content) } } - content.Append(')'); + content.Append(c: ')'); } - internal virtual void AddAnnotation(PdfAnnotation annot) - => Writer.AddAnnotation(annot); + internal virtual void AddAnnotation(PdfAnnotation annot) => Writer.AddAnnotation(annot); internal void AddTemplateReference(PdfIndirectReference template, PdfName name, @@ -2879,14 +2908,14 @@ internal void AddTemplateReference(PdfIndirectReference template, CheckWriter(); var prs = PageResources; name = prs.AddXObject(name, template); - Content.Append("q "); - Content.Append(a).Append(' '); - Content.Append(b).Append(' '); - Content.Append(c).Append(' '); - Content.Append(d).Append(' '); - Content.Append(e).Append(' '); - Content.Append(f).Append(" cm "); - Content.Append(name.GetBytes()).Append(" Do Q").Append_i(Separator); + Content.Append(str: "q "); + Content.Append(a).Append(c: ' '); + Content.Append(b).Append(c: ' '); + Content.Append(c).Append(c: ' '); + Content.Append(d).Append(c: ' '); + Content.Append(e).Append(c: ' '); + Content.Append(f).Append(str: " cm "); + Content.Append(name.GetBytes()).Append(str: " Do Q").Append_i(Separator); } /// @@ -2897,7 +2926,7 @@ internal static void CheckNoPattern(PdfTemplate t) { if (t.Type == PdfTemplate.TYPE_PATTERN) { - throw new ArgumentException("Invalid use of a pattern. A template was expected."); + throw new ArgumentException(message: "Invalid use of a pattern. A template was expected."); } } @@ -2937,9 +2966,9 @@ internal void OutputColorNumbers(BaseColor color, float tint) { case ExtendedColor.TYPE_RGB: Content.Append((float)color.R / 0xFF); - Content.Append(' '); + Content.Append(c: ' '); Content.Append((float)color.G / 0xFF); - Content.Append(' '); + Content.Append(c: ' '); Content.Append((float)color.B / 0xFF); break; @@ -2950,8 +2979,8 @@ internal void OutputColorNumbers(BaseColor color, float tint) case ExtendedColor.TYPE_CMYK: { var cmyk = (CmykColor)color; - Content.Append(cmyk.Cyan).Append(' ').Append(cmyk.Magenta); - Content.Append(' ').Append(cmyk.Yellow).Append(' ').Append(cmyk.Black); + Content.Append(cmyk.Cyan).Append(c: ' ').Append(cmyk.Magenta); + Content.Append(c: ' ').Append(cmyk.Yellow).Append(c: ' ').Append(cmyk.Black); break; } @@ -2960,7 +2989,7 @@ internal void OutputColorNumbers(BaseColor color, float tint) break; default: - throw new InvalidOperationException("Invalid color type."); + throw new InvalidOperationException(message: "Invalid color type."); } } @@ -2971,7 +3000,7 @@ protected virtual void CheckWriter() { if (Writer == null) { - throw new ArgumentNullException("The writer in PdfContentByte is null."); + throw new ArgumentNullException(paramName: "The writer in PdfContentByte is null."); } } @@ -2980,7 +3009,7 @@ private void beginLayer2(IPdfOcg layer) var name = (PdfName)Writer.AddSimpleProperty(layer, layer.Ref)[0]; var prs = PageResources; name = prs.AddProperty(name, layer.Ref); - Content.Append("/OC ").Append(name.GetBytes()).Append(" BDC").Append_i(Separator); + Content.Append(str: "/OC ").Append(name.GetBytes()).Append(str: " BDC").Append_i(Separator); } private static bool compareColors(BaseColor c1, BaseColor c2) @@ -3048,7 +3077,7 @@ private void helperCmyk(float cyan, float magenta, float yellow, float black) black = 1.0f; } - Content.Append(cyan).Append(' ').Append(magenta).Append(' ').Append(yellow).Append(' ').Append(black); + Content.Append(cyan).Append(c: ' ').Append(magenta).Append(c: ' ').Append(yellow).Append(c: ' ').Append(black); } /// @@ -3059,7 +3088,7 @@ private void helperCmyk(float cyan, float magenta, float yellow, float black) /// the intensity of blue. A value between 0 and 1 private void helperRgb(float red, float green, float blue) { - PdfXConformanceImp.CheckPdfxConformance(Writer, PdfXConformanceImp.PDFXKEY_RGB, null); + PdfXConformanceImp.CheckPdfxConformance(Writer, PdfXConformanceImp.PDFXKEY_RGB, obj1: null); if (red < 0) { @@ -3088,7 +3117,7 @@ private void helperRgb(float red, float green, float blue) blue = 1.0f; } - Content.Append(red).Append(' ').Append(green).Append(' ').Append(blue); + Content.Append(red).Append(c: ' ').Append(green).Append(c: ' ').Append(blue); } /// @@ -3100,7 +3129,7 @@ private void showText2(string text) { if (State.FontDetails == null) { - throw new InvalidOperationException("Font and size must be set before writing any text"); + throw new InvalidOperationException(message: "Font and size must be set before writing any text"); } var b = State.FontDetails.ConvertToBytes(text); @@ -3114,10 +3143,10 @@ private void showTextAligned(int alignment, string text, float x, float y, float { if (State.FontDetails == null) { - throw new InvalidOperationException("Font and size must be set before writing any text"); + throw new InvalidOperationException(message: "Font and size must be set before writing any text"); } - if (rotation.ApproxEquals(0)) + if (rotation.ApproxEquals(d2: 0)) { switch (alignment) { @@ -3176,7 +3205,7 @@ private void showTextAligned(int alignment, string text, float x, float y, float ShowText(text); } - SetTextMatrix(0f, 0f); + SetTextMatrix(x: 0f, y: 0f); } } @@ -3188,7 +3217,7 @@ public class GraphicState /// /// The current character spacing /// - protected internal float CharSpace; + internal protected float CharSpace; /// /// This is the color in use @@ -3203,12 +3232,12 @@ public class GraphicState /// /// The current text leading. /// - protected internal float leading; + internal protected float leading; /// /// The current horizontal scaling /// - protected internal float Scale = 100; + internal protected float Scale = 100; /// /// This is the font size in use @@ -3218,17 +3247,17 @@ public class GraphicState /// /// The current word spacing /// - protected internal float WordSpace; + internal protected float WordSpace; /// /// The x position of the text line matrix. /// - protected internal float XTlm; + internal protected float XTlm; /// /// The y position of the text line matrix. /// - protected internal float YTlm; + internal protected float YTlm; internal GraphicState() { diff --git a/src/iTextSharp.LGPLv2.Core/iTextSharp/text/pdf/PdfCopyFieldsImp.cs b/src/iTextSharp.LGPLv2.Core/iTextSharp/text/pdf/PdfCopyFieldsImp.cs index c9bdd87..a1330c6 100644 --- a/src/iTextSharp.LGPLv2.Core/iTextSharp/text/pdf/PdfCopyFieldsImp.cs +++ b/src/iTextSharp.LGPLv2.Core/iTextSharp/text/pdf/PdfCopyFieldsImp.cs @@ -8,19 +8,13 @@ namespace iTextSharp.text.pdf; internal class PdfCopyFieldsImp : PdfWriter { private const int _zero = 0; - protected internal static readonly INullValueDictionary FieldKeys = new NullValueDictionary(); - protected internal static readonly INullValueDictionary WidgetKeys = new NullValueDictionary(); + internal protected static readonly NullValueDictionary FieldKeys = new(); + internal protected static readonly NullValueDictionary WidgetKeys = new(); - private static readonly PdfName _iTextTag = new("_iTextTag_"); + private static readonly PdfName _iTextTag = new(name: "_iTextTag_"); private readonly List _calculationOrder = new(); - private List _calculationOrderRefs; - private bool _closing; - private bool _hasSignature; - private INullValueDictionary> _tabOrder; internal readonly List Fields = new(); - internal readonly INullValueDictionary FieldTree = new NullValueDictionary(); - internal RandomAccessFileOrArray File; - internal PdfDictionary Form; + internal readonly NullValueDictionary FieldTree = new(); internal readonly Document Nd; internal readonly List PageDics = new(); internal readonly List PageRefs = new(); @@ -38,6 +32,13 @@ internal class PdfCopyFieldsImp : PdfWriter internal readonly INullValueDictionary> Visited = new NullValueDictionary>(); + private List _calculationOrderRefs; + private bool _closing; + private bool _hasSignature; + private NullValueDictionary> _tabOrder; + internal RandomAccessFileOrArray File; + internal PdfDictionary Form; + static PdfCopyFieldsImp() { var one = 1; @@ -76,13 +77,14 @@ static PdfCopyFieldsImp() FieldKeys[PdfName.Sv] = one; } - internal PdfCopyFieldsImp(Stream os) : this(os, '\0') + internal PdfCopyFieldsImp(Stream os) : this(os, pdfVersion: '\0') { } internal PdfCopyFieldsImp(Stream os, char pdfVersion) : base(new PdfDocument(), os) { Pdf.AddWriter(this); + if (pdfVersion != 0) { PdfVersion = pdfVersion; @@ -97,6 +99,7 @@ public override void Close() if (_closing) { base.Close(); + return; } @@ -118,11 +121,12 @@ internal void AddDocument(PdfReader reader, ICollection pagesToKeep) { if (!Readers2Intrefs.ContainsKey(reader) && reader.Tampered) { - throw new DocumentException("The document was reused."); + throw new DocumentException(message: "The document was reused."); } reader = new PdfReader(reader); reader.SelectPages(pagesToKeep); + if (reader.NumberOfPages == 0) { return; @@ -136,10 +140,11 @@ internal void AddDocument(PdfReader reader) { if (!reader.IsOpenedWithFullPermissions) { - throw new BadPasswordException("PdfReader not opened with owner password"); + throw new BadPasswordException(message: "PdfReader not opened with owner password"); } OpenDoc(); + if (Readers2Intrefs.ContainsKey(reader)) { reader = new PdfReader(reader); @@ -148,7 +153,7 @@ internal void AddDocument(PdfReader reader) { if (reader.Tampered) { - throw new DocumentException("The document was reused."); + throw new DocumentException(message: "The document was reused."); } reader.ConsolidateNamedDestinations(); @@ -160,6 +165,7 @@ internal void AddDocument(PdfReader reader) Readers.Add(reader); var len = reader.NumberOfPages; var refs = new NullValueDictionary(); + for (var p = 1; p <= len; ++p) { refs[reader.GetPageOrigRef(p).Number] = 1; @@ -182,6 +188,7 @@ internal static void AddPageOffsetToField(INullValueDictionary list, AcroFields.Item item) list.Add(item.GetPage(k)); var merged = item.GetMerged(k); var dr = merged.Get(PdfName.Dr); + if (dr != null) { PdfFormField.MergeResources(Resources, (PdfDictionary)PdfReader.GetPdfObject(dr)); } var widget = new PdfDictionary(); + foreach (var key in merged.Keys) { if (WidgetKeys.ContainsKey(key)) @@ -221,7 +230,8 @@ internal void CreateWidgets(IList list, AcroFields.Item item) internal void MergeField(string name, AcroFields.Item item) { var map = FieldTree; - var tk = new StringTokenizer(name, "."); + var tk = new StringTokenizer(name, delim: "."); + if (!tk.HasMoreTokens()) { return; @@ -231,6 +241,7 @@ internal void MergeField(string name, AcroFields.Item item) { var s = tk.NextToken(); var obj = map[s]; + if (tk.HasMoreTokens()) { if (obj == null) @@ -238,6 +249,7 @@ internal void MergeField(string name, AcroFields.Item item) obj = new NullValueDictionary(); map[s] = obj; map = (NullValueDictionary)obj; + continue; } @@ -257,10 +269,12 @@ internal void MergeField(string name, AcroFields.Item item) return; } - var merged = item.GetMerged(0); + var merged = item.GetMerged(idx: 0); + if (obj == null) { var field = new PdfDictionary(); + if (PdfName.Sig.Equals(merged.Get(PdfName.Ft))) { _hasSignature = true; @@ -282,9 +296,10 @@ internal void MergeField(string name, AcroFields.Item item) else { var list = (List)obj; - var field = (PdfDictionary)list[0]; + var field = (PdfDictionary)list[index: 0]; var type1 = (PdfName)field.Get(PdfName.Ft); var type2 = (PdfName)merged.Get(PdfName.Ft); + if (type1 == null || !type1.Equals(type2)) { return; @@ -292,6 +307,7 @@ internal void MergeField(string name, AcroFields.Item item) var flag1 = 0; var f1 = field.Get(PdfName.Ff); + if (f1 != null && f1.IsNumber()) { flag1 = ((PdfNumber)f1).IntValue; @@ -299,6 +315,7 @@ internal void MergeField(string name, AcroFields.Item item) var flag2 = 0; var f2 = merged.Get(PdfName.Ff); + if (f2 != null && f2.IsNumber()) { flag2 = ((PdfNumber)f2).IntValue; @@ -335,6 +352,7 @@ internal void MergeField(string name, AcroFields.Item item) internal virtual void MergeFields() { var pageOffset = 0; + for (var k = 0; k < Fields.Count; ++k) { var fd = Fields[k].Fields; @@ -373,6 +391,7 @@ internal void Propagate(PdfObject obj, PdfIndirectReference refo, bool restricte case PdfObject.STREAM: { var dic = (PdfDictionary)obj; + foreach (var key in dic.Keys) { if (restricted && (key.Equals(PdfName.Parent) || key.Equals(PdfName.Kids))) @@ -381,9 +400,11 @@ internal void Propagate(PdfObject obj, PdfIndirectReference refo, bool restricte } var ob = dic.Get(key); + if (ob != null && ob.IsIndirect()) { var ind = (PrIndirectReference)ob; + if (!SetVisited(ind) && !IsPage(ind)) { var refi = GetNewReference(ind); @@ -392,7 +413,7 @@ internal void Propagate(PdfObject obj, PdfIndirectReference refo, bool restricte } else { - Propagate(ob, null, restricted); + Propagate(ob, refo: null, restricted); } } @@ -404,9 +425,11 @@ internal void Propagate(PdfObject obj, PdfIndirectReference refo, bool restricte for (var it = ((PdfArray)obj).GetListIterator(); it.HasNext();) { var ob = it.Next(); + if (ob != null && ob.IsIndirect()) { var ind = (PrIndirectReference)ob; + if (!IsVisited(ind) && !IsPage(ind)) { var refi = GetNewReference(ind); @@ -415,7 +438,7 @@ internal void Propagate(PdfObject obj, PdfIndirectReference refo, bool restricte } else { - Propagate(ob, null, restricted); + Propagate(ob, refo: null, restricted); } } @@ -423,15 +446,16 @@ internal void Propagate(PdfObject obj, PdfIndirectReference refo, bool restricte } case PdfObject.INDIRECT: { - throw new InvalidOperationException("Reference pointing to reference."); + throw new InvalidOperationException(message: "Reference pointing to reference."); } } } - protected internal override int GetNewObjectNumber(PdfReader reader, int number, int generation) + internal protected override int GetNewObjectNumber(PdfReader reader, int number, int generation) { var refs = Readers2Intrefs[reader]; var n = refs[number]; + if (n == 0) { n = IndirectReferenceNumber; @@ -446,9 +470,10 @@ protected internal override int GetNewObjectNumber(PdfReader reader, int number, /// /// the reference that needs to be checked /// true is the reference refers to a page object. - protected internal bool IsPage(PrIndirectReference refi) + internal protected bool IsPage(PrIndirectReference refi) { var refs = Pages2Intrefs[refi.Reader]; + if (refs != null) { return refs.ContainsKey(refi.Number); @@ -462,9 +487,10 @@ protected internal bool IsPage(PrIndirectReference refi) /// /// the reference that needs to be checked /// true if the reference was already visited - protected internal bool IsVisited(PrIndirectReference refi) + internal protected bool IsVisited(PrIndirectReference refi) { var refs = Visited[refi.Reader]; + if (refs != null) { return refs.ContainsKey(refi.Number); @@ -473,9 +499,10 @@ protected internal bool IsVisited(PrIndirectReference refi) return false; } - protected internal bool IsVisited(PdfReader reader, int number, int generation) + internal protected bool IsVisited(PdfReader reader, int number, int generation) { var refs = Readers2Intrefs[reader]; + return refs.ContainsKey(number); } @@ -484,50 +511,58 @@ protected internal bool IsVisited(PdfReader reader, int number, int generation) /// /// the reference that needs to be set to "visited" /// true if the reference was set to visited - protected internal bool SetVisited(PrIndirectReference refi) + internal protected bool SetVisited(PrIndirectReference refi) { var refs = Visited[refi.Reader]; + if (refs != null) { var old = refs[refi.Number]; refs[refi.Number] = 1; + return old != 0; } return false; } - protected internal void UpdateCalculationOrder(PdfReader reader) + internal protected void UpdateCalculationOrder(PdfReader reader) { var catalog = reader.Catalog; var acro = catalog.GetAsDict(PdfName.Acroform); + if (acro == null) { return; } var co = acro.GetAsArray(PdfName.Co); + if (co == null || co.Size == 0) { return; } var af = reader.AcroFields; + for (var k = 0; k < co.Size; ++k) { var obj = co[k]; + if (obj == null || !obj.IsIndirect()) { continue; } var name = getCoName(reader, (PrIndirectReference)obj); + if (af.GetFieldItem(name) == null) { continue; } name = "." + name; + if (_calculationOrder.Contains(name)) { continue; @@ -540,12 +575,14 @@ protected internal void UpdateCalculationOrder(PdfReader reader) protected PdfArray BranchForm(INullValueDictionary level, PdfIndirectReference parent, string fname) { var arr = new PdfArray(); + foreach (var entry in level) { var name = entry.Key; var obj = entry.Value; var ind = PdfIndirectReference; var dic = new PdfDictionary(); + if (parent != null) { dic.Put(PdfName.Parent, parent); @@ -554,6 +591,7 @@ protected PdfArray BranchForm(INullValueDictionary level, PdfInd dic.Put(PdfName.T, new PdfString(name, PdfObject.TEXT_UNICODE)); var fname2 = $"{fname}.{name}"; var coidx = _calculationOrder.IndexOf(fname2); + if (coidx >= 0) { _calculationOrderRefs[coidx] = ind; @@ -568,13 +606,15 @@ protected PdfArray BranchForm(INullValueDictionary level, PdfInd else { var list = (List)obj; - dic.MergeDifferent((PdfDictionary)list[0]); + dic.MergeDifferent((PdfDictionary)list[index: 0]); + if (list.Count == 3) { - dic.MergeDifferent((PdfDictionary)list[2]); - var page = (int)list[1]; + dic.MergeDifferent((PdfDictionary)list[index: 2]); + var page = (int)list[index: 1]; var pageDic = PageDics[page - 1]; var annots = pageDic.GetAsArray(PdfName.Annots); + if (annots == null) { annots = new PdfArray(); @@ -588,11 +628,13 @@ protected PdfArray BranchForm(INullValueDictionary level, PdfInd else { var kids = new PdfArray(); + for (var k = 1; k < list.Count; k += 2) { var page = (int)list[k]; var pageDic = PageDics[page - 1]; var annots = pageDic.GetAsArray(PdfName.Annots); + if (annots == null) { annots = new PdfArray(); @@ -607,7 +649,7 @@ protected PdfArray BranchForm(INullValueDictionary level, PdfInd var wref = AddToBody(widget).IndirectReference; adjustTabOrder(annots, wref, nn); kids.Add(wref); - Propagate(widget, null, false); + Propagate(widget, refo: null, restricted: false); } dic.Put(PdfName.Kids, kids); @@ -615,7 +657,7 @@ protected PdfArray BranchForm(INullValueDictionary level, PdfInd arr.Add(ind); AddToBody(dic, ind); - Propagate(dic, null, false); + Propagate(dic, refo: null, restricted: false); } } @@ -632,6 +674,7 @@ protected void CloseIt() for (var r = 0; r < Readers.Count; ++r) { var reader = Readers[r]; + for (var page = 1; page <= reader.NumberOfPages; ++page) { PageRefs.Add(GetNewReference(reader.GetPageOrigRef(page))); @@ -641,28 +684,32 @@ protected void CloseIt() MergeFields(); CreateAcroForms(); + for (var r = 0; r < Readers.Count; ++r) { var reader = Readers[r]; + for (var page = 1; page <= reader.NumberOfPages; ++page) { var dic = reader.GetPageN(page); var pageRef = GetNewReference(reader.GetPageOrigRef(page)); var parent = Root.AddPageRef(pageRef); dic.Put(PdfName.Parent, parent); - Propagate(dic, pageRef, false); + Propagate(dic, pageRef, restricted: false); } } foreach (var entry in Readers2Intrefs) { var reader = entry.Key; + try { File = reader.SafeFile; File.ReOpen(); var t = entry.Value; var keys = t.ToOrderedKeys(); + for (var k = 0; k < keys.Count; ++k) { var refi = new PrIndirectReference(reader, keys[k]); @@ -695,20 +742,23 @@ protected void CreateAcroForms() Form = new PdfDictionary(); Form.Put(PdfName.Dr, Resources); - Propagate(Resources, null, false); - Form.Put(PdfName.Da, new PdfString("/Helv 0 Tf 0 g ")); + Propagate(Resources, refo: null, restricted: false); + Form.Put(PdfName.Da, new PdfString(value: "/Helv 0 Tf 0 g ")); _tabOrder = new NullValueDictionary>(); _calculationOrderRefs = new List(_calculationOrder); - Form.Put(PdfName.Fields, BranchForm(FieldTree, null, "")); + Form.Put(PdfName.Fields, BranchForm(FieldTree, parent: null, fname: "")); + if (_hasSignature) { - Form.Put(PdfName.Sigflags, new PdfNumber(3)); + Form.Put(PdfName.Sigflags, new PdfNumber(value: 3)); } var co = new PdfArray(); + for (var k = 0; k < _calculationOrderRefs.Count; ++k) { var obj = _calculationOrderRefs[k]; + if (obj is PdfIndirectReference) { co.Add((PdfIndirectReference)obj); @@ -724,6 +774,7 @@ protected void CreateAcroForms() protected override PdfDictionary GetCatalog(PdfIndirectReference rootObj) { PdfDictionary cat = Pdf.GetCatalog(rootObj); + if (Form != null) { var refi = AddToBody(Form).IndirectReference; @@ -733,15 +784,17 @@ protected override PdfDictionary GetCatalog(PdfIndirectReference rootObj) return cat; } - protected PdfIndirectReference GetNewReference(PrIndirectReference refi) => - new(0, GetNewObjectNumber(refi.Reader, refi.Number, 0)); + protected PdfIndirectReference GetNewReference(PrIndirectReference refi) + => new(type: 0, GetNewObjectNumber(refi.Reader, refi.Number, generation: 0)); private static string getCoName(PdfReader reader, PrIndirectReference refi) { var name = ""; + while (refi != null) { var obj = PdfReader.GetPdfObject(refi); + if (obj == null || obj.Type != PdfObject.DICTIONARY) { break; @@ -749,6 +802,7 @@ private static string getCoName(PdfReader reader, PrIndirectReference refi) var dic = (PdfDictionary)obj; var t = dic.GetAsString(PdfName.T); + if (t != null) { name = t.ToUnicodeString() + "." + name; @@ -757,9 +811,9 @@ private static string getCoName(PdfReader reader, PrIndirectReference refi) refi = (PrIndirectReference)dic.Get(PdfName.Parent); } - if (name.EndsWith(".", StringComparison.Ordinal)) + if (name.EndsWith(value: ".", StringComparison.Ordinal)) { - name = name.Substring(0, name.Length - 1); + name = name.Substring(startIndex: 0, name.Length - 1); } return name; @@ -769,10 +823,12 @@ private void adjustTabOrder(PdfArray annots, PdfIndirectReference ind, PdfNumber { var v = nn.IntValue; var t = _tabOrder[annots]; + if (t == null) { t = new List(); var size = annots.Size - 1; + for (var k = 0; k < size; ++k) { t.Add(_zero); @@ -785,6 +841,7 @@ private void adjustTabOrder(PdfArray annots, PdfIndirectReference ind, PdfNumber else { var size = t.Count - 1; + for (var k = size; k >= 0; --k) { if (t[k] <= v) @@ -792,14 +849,15 @@ private void adjustTabOrder(PdfArray annots, PdfIndirectReference ind, PdfNumber t.Insert(k + 1, v); annots.Add(k + 1, ind); size = -2; + break; } } if (size != -2) { - t.Insert(0, v); - annots.Add(0, ind); + t.Insert(index: 0, v); + annots.Add(index: 0, ind); } } } diff --git a/src/iTextSharp.LGPLv2.Core/iTextSharp/text/pdf/PdfPKCS7.cs b/src/iTextSharp.LGPLv2.Core/iTextSharp/text/pdf/PdfPKCS7.cs index 1b1f265..2d9792f 100644 --- a/src/iTextSharp.LGPLv2.Core/iTextSharp/text/pdf/PdfPKCS7.cs +++ b/src/iTextSharp.LGPLv2.Core/iTextSharp/text/pdf/PdfPKCS7.cs @@ -35,18 +35,15 @@ public class PdfPkcs7 private const string IdRsa = "1.2.840.113549.1.1.1"; private const string IdSigningTime = "1.2.840.113549.1.9.5"; - private static readonly INullValueDictionary _algorithmNames = - new NullValueDictionary(); + private static readonly NullValueDictionary _algorithmNames = new(); - private static readonly INullValueDictionary _allowedDigests = - new NullValueDictionary(); + private static readonly NullValueDictionary _allowedDigests = new(); - private static readonly INullValueDictionary _digestNames = - new NullValueDictionary(); + private static readonly NullValueDictionary _digestNames = new(); private readonly List _certs; private readonly string _digestAlgorithm; - private readonly INullValueDictionary _digestalgos = new NullValueDictionary(); + private readonly NullValueDictionary _digestalgos = new(); private readonly byte[] _digestAttr; private readonly IDigest _messageDigest; @@ -66,70 +63,70 @@ public class PdfPkcs7 static PdfPkcs7() { - _digestNames["1.2.840.113549.2.5"] = "MD5"; - _digestNames["1.2.840.113549.2.2"] = "MD2"; - _digestNames["1.3.14.3.2.26"] = "SHA1"; - _digestNames["2.16.840.1.101.3.4.2.4"] = "SHA224"; - _digestNames["2.16.840.1.101.3.4.2.1"] = "SHA256"; - _digestNames["2.16.840.1.101.3.4.2.2"] = "SHA384"; - _digestNames["2.16.840.1.101.3.4.2.3"] = "SHA512"; - _digestNames["1.3.36.3.2.2"] = "RIPEMD128"; - _digestNames["1.3.36.3.2.1"] = "RIPEMD160"; - _digestNames["1.3.36.3.2.3"] = "RIPEMD256"; - _digestNames["1.2.840.113549.1.1.4"] = "MD5"; - _digestNames["1.2.840.113549.1.1.2"] = "MD2"; - _digestNames["1.2.840.113549.1.1.5"] = "SHA1"; - _digestNames["1.2.840.113549.1.1.14"] = "SHA224"; - _digestNames["1.2.840.113549.1.1.11"] = "SHA256"; - _digestNames["1.2.840.113549.1.1.12"] = "SHA384"; - _digestNames["1.2.840.113549.1.1.13"] = "SHA512"; - _digestNames["1.2.840.113549.2.5"] = "MD5"; - _digestNames["1.2.840.113549.2.2"] = "MD2"; - _digestNames["1.2.840.10040.4.3"] = "SHA1"; - _digestNames["2.16.840.1.101.3.4.3.1"] = "SHA224"; - _digestNames["2.16.840.1.101.3.4.3.2"] = "SHA256"; - _digestNames["2.16.840.1.101.3.4.3.3"] = "SHA384"; - _digestNames["2.16.840.1.101.3.4.3.4"] = "SHA512"; - _digestNames["1.3.36.3.3.1.3"] = "RIPEMD128"; - _digestNames["1.3.36.3.3.1.2"] = "RIPEMD160"; - _digestNames["1.3.36.3.3.1.4"] = "RIPEMD256"; - - _algorithmNames["1.2.840.113549.1.1.1"] = "RSA"; - _algorithmNames["1.2.840.10040.4.1"] = "DSA"; - _algorithmNames["1.2.840.113549.1.1.2"] = "RSA"; - _algorithmNames["1.2.840.113549.1.1.4"] = "RSA"; - _algorithmNames["1.2.840.113549.1.1.5"] = "RSA"; - _algorithmNames["1.2.840.113549.1.1.14"] = "RSA"; - _algorithmNames["1.2.840.113549.1.1.11"] = "RSA"; - _algorithmNames["1.2.840.113549.1.1.12"] = "RSA"; - _algorithmNames["1.2.840.113549.1.1.13"] = "RSA"; - _algorithmNames["1.2.840.10040.4.3"] = "DSA"; - _algorithmNames["2.16.840.1.101.3.4.3.1"] = "DSA"; - _algorithmNames["2.16.840.1.101.3.4.3.2"] = "DSA"; - _algorithmNames["1.3.36.3.3.1.3"] = "RSA"; - _algorithmNames["1.3.36.3.3.1.2"] = "RSA"; - _algorithmNames["1.3.36.3.3.1.4"] = "RSA"; - - _allowedDigests["MD5"] = "1.2.840.113549.2.5"; - _allowedDigests["MD2"] = "1.2.840.113549.2.2"; - _allowedDigests["SHA1"] = "1.3.14.3.2.26"; - _allowedDigests["SHA224"] = "2.16.840.1.101.3.4.2.4"; - _allowedDigests["SHA256"] = "2.16.840.1.101.3.4.2.1"; - _allowedDigests["SHA384"] = "2.16.840.1.101.3.4.2.2"; - _allowedDigests["SHA512"] = "2.16.840.1.101.3.4.2.3"; - _allowedDigests["MD-5"] = "1.2.840.113549.2.5"; - _allowedDigests["MD-2"] = "1.2.840.113549.2.2"; - _allowedDigests["SHA-1"] = "1.3.14.3.2.26"; - _allowedDigests["SHA-224"] = "2.16.840.1.101.3.4.2.4"; - _allowedDigests["SHA-256"] = "2.16.840.1.101.3.4.2.1"; - _allowedDigests["SHA-384"] = "2.16.840.1.101.3.4.2.2"; - _allowedDigests["SHA-512"] = "2.16.840.1.101.3.4.2.3"; - _allowedDigests["RIPEMD128"] = "1.3.36.3.2.2"; - _allowedDigests["RIPEMD-128"] = "1.3.36.3.2.2"; - _allowedDigests["RIPEMD160"] = "1.3.36.3.2.1"; - _allowedDigests["RIPEMD-160"] = "1.3.36.3.2.1"; - _allowedDigests["RIPEMD256"] = "1.3.36.3.2.3"; - _allowedDigests["RIPEMD-256"] = "1.3.36.3.2.3"; + _digestNames[key: "1.2.840.113549.2.5"] = "MD5"; + _digestNames[key: "1.2.840.113549.2.2"] = "MD2"; + _digestNames[key: "1.3.14.3.2.26"] = "SHA1"; + _digestNames[key: "2.16.840.1.101.3.4.2.4"] = "SHA224"; + _digestNames[key: "2.16.840.1.101.3.4.2.1"] = "SHA256"; + _digestNames[key: "2.16.840.1.101.3.4.2.2"] = "SHA384"; + _digestNames[key: "2.16.840.1.101.3.4.2.3"] = "SHA512"; + _digestNames[key: "1.3.36.3.2.2"] = "RIPEMD128"; + _digestNames[key: "1.3.36.3.2.1"] = "RIPEMD160"; + _digestNames[key: "1.3.36.3.2.3"] = "RIPEMD256"; + _digestNames[key: "1.2.840.113549.1.1.4"] = "MD5"; + _digestNames[key: "1.2.840.113549.1.1.2"] = "MD2"; + _digestNames[key: "1.2.840.113549.1.1.5"] = "SHA1"; + _digestNames[key: "1.2.840.113549.1.1.14"] = "SHA224"; + _digestNames[key: "1.2.840.113549.1.1.11"] = "SHA256"; + _digestNames[key: "1.2.840.113549.1.1.12"] = "SHA384"; + _digestNames[key: "1.2.840.113549.1.1.13"] = "SHA512"; + _digestNames[key: "1.2.840.113549.2.5"] = "MD5"; + _digestNames[key: "1.2.840.113549.2.2"] = "MD2"; + _digestNames[key: "1.2.840.10040.4.3"] = "SHA1"; + _digestNames[key: "2.16.840.1.101.3.4.3.1"] = "SHA224"; + _digestNames[key: "2.16.840.1.101.3.4.3.2"] = "SHA256"; + _digestNames[key: "2.16.840.1.101.3.4.3.3"] = "SHA384"; + _digestNames[key: "2.16.840.1.101.3.4.3.4"] = "SHA512"; + _digestNames[key: "1.3.36.3.3.1.3"] = "RIPEMD128"; + _digestNames[key: "1.3.36.3.3.1.2"] = "RIPEMD160"; + _digestNames[key: "1.3.36.3.3.1.4"] = "RIPEMD256"; + + _algorithmNames[key: "1.2.840.113549.1.1.1"] = "RSA"; + _algorithmNames[key: "1.2.840.10040.4.1"] = "DSA"; + _algorithmNames[key: "1.2.840.113549.1.1.2"] = "RSA"; + _algorithmNames[key: "1.2.840.113549.1.1.4"] = "RSA"; + _algorithmNames[key: "1.2.840.113549.1.1.5"] = "RSA"; + _algorithmNames[key: "1.2.840.113549.1.1.14"] = "RSA"; + _algorithmNames[key: "1.2.840.113549.1.1.11"] = "RSA"; + _algorithmNames[key: "1.2.840.113549.1.1.12"] = "RSA"; + _algorithmNames[key: "1.2.840.113549.1.1.13"] = "RSA"; + _algorithmNames[key: "1.2.840.10040.4.3"] = "DSA"; + _algorithmNames[key: "2.16.840.1.101.3.4.3.1"] = "DSA"; + _algorithmNames[key: "2.16.840.1.101.3.4.3.2"] = "DSA"; + _algorithmNames[key: "1.3.36.3.3.1.3"] = "RSA"; + _algorithmNames[key: "1.3.36.3.3.1.2"] = "RSA"; + _algorithmNames[key: "1.3.36.3.3.1.4"] = "RSA"; + + _allowedDigests[key: "MD5"] = "1.2.840.113549.2.5"; + _allowedDigests[key: "MD2"] = "1.2.840.113549.2.2"; + _allowedDigests[key: "SHA1"] = "1.3.14.3.2.26"; + _allowedDigests[key: "SHA224"] = "2.16.840.1.101.3.4.2.4"; + _allowedDigests[key: "SHA256"] = "2.16.840.1.101.3.4.2.1"; + _allowedDigests[key: "SHA384"] = "2.16.840.1.101.3.4.2.2"; + _allowedDigests[key: "SHA512"] = "2.16.840.1.101.3.4.2.3"; + _allowedDigests[key: "MD-5"] = "1.2.840.113549.2.5"; + _allowedDigests[key: "MD-2"] = "1.2.840.113549.2.2"; + _allowedDigests[key: "SHA-1"] = "1.3.14.3.2.26"; + _allowedDigests[key: "SHA-224"] = "2.16.840.1.101.3.4.2.4"; + _allowedDigests[key: "SHA-256"] = "2.16.840.1.101.3.4.2.1"; + _allowedDigests[key: "SHA-384"] = "2.16.840.1.101.3.4.2.2"; + _allowedDigests[key: "SHA-512"] = "2.16.840.1.101.3.4.2.3"; + _allowedDigests[key: "RIPEMD128"] = "1.3.36.3.2.2"; + _allowedDigests[key: "RIPEMD-128"] = "1.3.36.3.2.2"; + _allowedDigests[key: "RIPEMD160"] = "1.3.36.3.2.1"; + _allowedDigests[key: "RIPEMD-160"] = "1.3.36.3.2.1"; + _allowedDigests[key: "RIPEMD256"] = "1.3.36.3.2.3"; + _allowedDigests[key: "RIPEMD-256"] = "1.3.36.3.2.3"; } /// @@ -148,13 +145,13 @@ public PdfPkcs7(byte[] contentsKey, byte[] certsKey) } _signCerts = _certs; - SigningCertificate = _certs[0]; + SigningCertificate = _certs[index: 0]; CrLs = new List(); using var memoryStream = new MemoryStream(contentsKey); using var inp = new Asn1InputStream(memoryStream); _digest = ((DerOctetString)inp.ReadObject()).GetOctets(); - _sig = SignerUtilities.GetSigner("SHA1withRSA"); - _sig.Init(false, SigningCertificate.GetPublicKey()); + _sig = SignerUtilities.GetSigner(algorithm: "SHA1withRSA"); + _sig.Init(forSigning: false, SigningCertificate.GetPublicKey()); } /// @@ -184,22 +181,22 @@ public PdfPkcs7(byte[] contentsKey) } catch { - throw new ArgumentException("can't decode PKCS7SignedData object"); + throw new ArgumentException(message: "can't decode PKCS7SignedData object"); } if (pkcs is not Asn1Sequence signedData) { - throw new ArgumentException("Not a valid PKCS#7 object - not a sequence"); + throw new ArgumentException(message: "Not a valid PKCS#7 object - not a sequence"); } - var objId = (DerObjectIdentifier)signedData[0]; + var objId = (DerObjectIdentifier)signedData[index: 0]; if (!objId.Id.Equals(IdPkcs7SignedData, StringComparison.Ordinal)) { - throw new ArgumentException("Not a valid PKCS#7 object - not signed data"); + throw new ArgumentException(message: "Not a valid PKCS#7 object - not signed data"); } - var content = (Asn1Sequence)((DerTaggedObject)signedData[1]).GetBaseObject(); + var content = (Asn1Sequence)((DerTaggedObject)signedData[index: 1]).GetBaseObject(); // the positions that we care are: // 0 - version @@ -209,16 +206,16 @@ public PdfPkcs7(byte[] contentsKey) // last - signerInfos // the version - Version = ((DerInteger)content[0]).Value.IntValue; + Version = ((DerInteger)content[index: 0]).Value.IntValue; // the digestAlgorithms _digestalgos = new NullValueDictionary(); - var e = ((Asn1Set)content[1]).GetEnumerator(); + var e = ((Asn1Set)content[index: 1]).GetEnumerator(); while (e.MoveNext()) { var s = (Asn1Sequence)e.Current; - var o = (DerObjectIdentifier)s[0]; + var o = (DerObjectIdentifier)s[index: 0]; _digestalgos[o.Id] = null; } @@ -234,11 +231,11 @@ public PdfPkcs7(byte[] contentsKey) CrLs = new List(); // the possible ID_PKCS7_DATA - var rsaData = (Asn1Sequence)content[2]; + var rsaData = (Asn1Sequence)content[index: 2]; if (rsaData.Count > 1) { - var rsaDataContent = (DerOctetString)((DerTaggedObject)rsaData[1]).GetBaseObject(); + var rsaDataContent = (DerOctetString)((DerTaggedObject)rsaData[index: 1]).GetBaseObject(); _rsAdata = rsaDataContent.GetOctets(); } @@ -255,10 +252,10 @@ public PdfPkcs7(byte[] contentsKey) if (signerInfos.Count != 1) { throw new ArgumentException( - "This PKCS#7 object has multiple SignerInfos - only one is supported at this time"); + message: "This PKCS#7 object has multiple SignerInfos - only one is supported at this time"); } - var signerInfo = (Asn1Sequence)signerInfos[0]; + var signerInfo = (Asn1Sequence)signerInfos[index: 0]; // the positions that we care are // 0 - version @@ -266,11 +263,11 @@ public PdfPkcs7(byte[] contentsKey) // 2 - the digest algorithm // 3 or 4 - digestEncryptionAlgorithm // 4 or 5 - encryptedDigest - SigningInfoVersion = ((DerInteger)signerInfo[0]).Value.IntValue; + SigningInfoVersion = ((DerInteger)signerInfo[index: 0]).Value.IntValue; // Get the signing certificate - var issuerAndSerialNumber = (Asn1Sequence)signerInfo[1]; - var serialNumber = ((DerInteger)issuerAndSerialNumber[1]).Value; + var issuerAndSerialNumber = (Asn1Sequence)signerInfo[index: 1]; + var serialNumber = ((DerInteger)issuerAndSerialNumber[index: 1]).Value; foreach (var cert in _certs) { @@ -284,31 +281,32 @@ public PdfPkcs7(byte[] contentsKey) if (SigningCertificate == null) { - throw new ArgumentException("Can't find signing certificate with serial " + serialNumber.ToString(16)); + throw new ArgumentException( + "Can't find signing certificate with serial " + serialNumber.ToString(radix: 16)); } calcSignCertificateChain(); - _digestAlgorithm = ((DerObjectIdentifier)((Asn1Sequence)signerInfo[2])[0]).Id; + _digestAlgorithm = ((DerObjectIdentifier)((Asn1Sequence)signerInfo[index: 2])[index: 0]).Id; next = 3; if (signerInfo[next] is Asn1TaggedObject tagsig) { - var sseq = Asn1Set.GetInstance(tagsig, false); + var sseq = Asn1Set.GetInstance(tagsig, declaredExplicit: false); _sigAttr = sseq.GetEncoded(Asn1Encodable.Der); for (var k = 0; k < sseq.Count; ++k) { var seq2 = (Asn1Sequence)sseq[k]; - if (((DerObjectIdentifier)seq2[0]).Id.Equals(IdMessageDigest, StringComparison.Ordinal)) + if (((DerObjectIdentifier)seq2[index: 0]).Id.Equals(IdMessageDigest, StringComparison.Ordinal)) { - var sset = (Asn1Set)seq2[1]; - _digestAttr = ((DerOctetString)sset[0]).GetOctets(); + var sset = (Asn1Set)seq2[index: 1]; + _digestAttr = ((DerOctetString)sset[index: 0]).GetOctets(); } - else if (((DerObjectIdentifier)seq2[0]).Id.Equals(IdAdbeRevocation, StringComparison.Ordinal)) + else if (((DerObjectIdentifier)seq2[index: 0]).Id.Equals(IdAdbeRevocation, StringComparison.Ordinal)) { - var setout = (Asn1Set)seq2[1]; - var seqout = (Asn1Sequence)setout[0]; + var setout = (Asn1Set)seq2[index: 1]; + var seqout = (Asn1Sequence)setout[index: 0]; for (var j = 0; j < seqout.Count; ++j) { @@ -327,25 +325,25 @@ public PdfPkcs7(byte[] contentsKey) if (_digestAttr == null) { - throw new ArgumentException("Authenticated attribute is missing the digest."); + throw new ArgumentException(message: "Authenticated attribute is missing the digest."); } ++next; } - _digestEncryptionAlgorithm = ((DerObjectIdentifier)((Asn1Sequence)signerInfo[next++])[0]).Id; + _digestEncryptionAlgorithm = ((DerObjectIdentifier)((Asn1Sequence)signerInfo[next++])[index: 0]).Id; _digest = ((DerOctetString)signerInfo[next++]).GetOctets(); if (next < signerInfo.Count && signerInfo[next] is DerTaggedObject taggedObject) { - var unat = Asn1Set.GetInstance(taggedObject, false); + var unat = Asn1Set.GetInstance(taggedObject, declaredExplicit: false); var attble = new AttributeTable(unat); var ts = attble[PkcsObjectIdentifiers.IdAASignatureTimeStampToken]; if (ts != null) { var attributeValues = ts.AttrValues; - var tokenSequence = Asn1Sequence.GetInstance(attributeValues[0]); + var tokenSequence = Asn1Sequence.GetInstance(attributeValues[index: 0]); var contentInfo = ContentInfo.GetInstance(tokenSequence); TimeStampToken = new TimeStampToken(contentInfo); } @@ -357,7 +355,7 @@ public PdfPkcs7(byte[] contentsKey) } _sig = SignerUtilities.GetSigner(GetDigestAlgorithm()); - _sig.Init(false, SigningCertificate.GetPublicKey()); + _sig.Init(forSigning: false, SigningCertificate.GetPublicKey()); } /// @@ -447,7 +445,7 @@ public PdfPkcs7(ICipherParameters privKey, if (privKey != null) { _sig = SignerUtilities.GetSigner(GetDigestAlgorithm()); - _sig.Init(true, privKey); + _sig.Init(forSigning: true, privKey); } } @@ -646,11 +644,11 @@ public static string GetOcspurl(X509Certificate certificate) continue; } - if (accessDescription[0] is DerObjectIdentifier && - ((DerObjectIdentifier)accessDescription[0]).Id.Equals("1.3.6.1.5.5.7.48.1", + if (accessDescription[index: 0] is DerObjectIdentifier && + ((DerObjectIdentifier)accessDescription[index: 0]).Id.Equals(value: "1.3.6.1.5.5.7.48.1", StringComparison.Ordinal)) { - var accessLocation = getStringFromGeneralName((Asn1Object)accessDescription[1]); + var accessLocation = getStringFromGeneralName((Asn1Object)accessDescription[index: 1]); if (accessLocation == null) { @@ -979,7 +977,7 @@ public byte[] GetEncodedPkcs1() /// Gets the bytes for the PKCS7SignedData object. /// /// the bytes for the PKCS7SignedData object - public byte[] GetEncodedPkcs7() => GetEncodedPkcs7(null, DateTime.Now, null, null); + public byte[] GetEncodedPkcs7() => GetEncodedPkcs7(secondDigest: null, DateTime.Now, tsaClient: null, ocsp: null); /// /// Gets the bytes for the PKCS7SignedData object. Optionally the authenticatedAttributes @@ -989,7 +987,7 @@ public byte[] GetEncodedPkcs1() /// the signing time in the authenticatedAttributes /// the bytes for the PKCS7SignedData object public byte[] GetEncodedPkcs7(byte[] secondDigest, DateTime signingTime) - => GetEncodedPkcs7(secondDigest, signingTime, null, null); + => GetEncodedPkcs7(secondDigest, signingTime, tsaClient: null, ocsp: null); /// /// Gets the bytes for the PKCS7SignedData object. Optionally the authenticatedAttributes @@ -1016,7 +1014,7 @@ public byte[] GetEncodedPkcs7(byte[] secondDigest, DateTime signingTime, ITsaCli else if (_externalRsAdata != null && _rsAdata != null) { _rsAdata = _externalRsAdata; - _sig.BlockUpdate(_rsAdata, 0, _rsAdata.Length); + _sig.BlockUpdate(_rsAdata, inOff: 0, _rsAdata.Length); _digest = _sig.GenerateSignature(); } else @@ -1024,8 +1022,8 @@ public byte[] GetEncodedPkcs7(byte[] secondDigest, DateTime signingTime, ITsaCli if (_rsAdata != null) { _rsAdata = new byte[_messageDigest.GetDigestSize()]; - _messageDigest.DoFinal(_rsAdata, 0); - _sig.BlockUpdate(_rsAdata, 0, _rsAdata.Length); + _messageDigest.DoFinal(_rsAdata, outOff: 0); + _sig.BlockUpdate(_rsAdata, inOff: 0, _rsAdata.Length); } _digest = _sig.GenerateSignature(); @@ -1048,7 +1046,7 @@ public byte[] GetEncodedPkcs7(byte[] secondDigest, DateTime signingTime, ITsaCli if (_rsAdata != null) { - v.Add(new DerTaggedObject(0, new DerOctetString(_rsAdata))); + v.Add(new DerTaggedObject(tagNo: 0, new DerOctetString(_rsAdata))); } var contentinfo = new DerSequence(v); @@ -1088,7 +1086,7 @@ public byte[] GetEncodedPkcs7(byte[] secondDigest, DateTime signingTime, ITsaCli // add the authenticated attribute if present if (secondDigest != null /*&& signingTime != null*/) { - signerinfo.Add(new DerTaggedObject(false, 0, + signerinfo.Add(new DerTaggedObject(isExplicit: false, tagNo: 0, getAuthenticatedAttributeSet(secondDigest, signingTime, ocsp))); } @@ -1116,7 +1114,7 @@ public byte[] GetEncodedPkcs7(byte[] secondDigest, DateTime signingTime, ITsaCli if (unauthAttributes != null) { - signerinfo.Add(new DerTaggedObject(false, 1, new DerSet(unauthAttributes))); + signerinfo.Add(new DerTaggedObject(isExplicit: false, tagNo: 1, new DerSet(unauthAttributes))); } } } @@ -1126,7 +1124,7 @@ public byte[] GetEncodedPkcs7(byte[] secondDigest, DateTime signingTime, ITsaCli body.Add(new DerInteger(Version)); body.Add(new DerSet(digestAlgorithms)); body.Add(contentinfo); - body.Add(new DerTaggedObject(false, 0, dercertificates)); + body.Add(new DerTaggedObject(isExplicit: false, tagNo: 0, dercertificates)); // if (crls.Count > 0) { // v = new Asn1EncodableVector(); @@ -1146,7 +1144,7 @@ public byte[] GetEncodedPkcs7(byte[] secondDigest, DateTime signingTime, ITsaCli // var whole = new Asn1EncodableVector(); whole.Add(new DerObjectIdentifier(IdPkcs7SignedData)); - whole.Add(new DerTaggedObject(0, new DerSequence(body))); + whole.Add(new DerTaggedObject(tagNo: 0, new DerSequence(body))); using var bOut = new MemoryStream(); using var dout = Asn1OutputStream.Create(bOut); @@ -1214,11 +1212,11 @@ public void SetExternalDigest(byte[] digest, byte[] rsAdata, string digestEncryp if (digestEncryptionAlgorithm != null) { - if (digestEncryptionAlgorithm.Equals("RSA", StringComparison.Ordinal)) + if (digestEncryptionAlgorithm.Equals(value: "RSA", StringComparison.Ordinal)) { _digestEncryptionAlgorithm = IdRsa; } - else if (digestEncryptionAlgorithm.Equals("DSA", StringComparison.Ordinal)) + else if (digestEncryptionAlgorithm.Equals(value: "DSA", StringComparison.Ordinal)) { _digestEncryptionAlgorithm = IdDsa; } @@ -1263,15 +1261,15 @@ public bool Verify() if (_sigAttr != null) { var msd = new byte[_messageDigest.GetDigestSize()]; - _sig.BlockUpdate(_sigAttr, 0, _sigAttr.Length); + _sig.BlockUpdate(_sigAttr, inOff: 0, _sigAttr.Length); if (_rsAdata != null) { - _messageDigest.DoFinal(msd, 0); - _messageDigest.BlockUpdate(msd, 0, msd.Length); + _messageDigest.DoFinal(msd, outOff: 0); + _messageDigest.BlockUpdate(msd, inOff: 0, msd.Length); } - _messageDigest.DoFinal(msd, 0); + _messageDigest.DoFinal(msd, outOff: 0); _verifyResult = Arrays.AreEqual(msd, _digestAttr) && _sig.VerifySignature(_digest); } else @@ -1279,8 +1277,8 @@ public bool Verify() if (_rsAdata != null) { var msd = new byte[_messageDigest.GetDigestSize()]; - _messageDigest.DoFinal(msd, 0); - _sig.BlockUpdate(msd, 0, msd.Length); + _messageDigest.DoFinal(msd, outOff: 0); + _sig.BlockUpdate(msd, inOff: 0, msd.Length); } _verifyResult = _sig.VerifySignature(_digest); @@ -1342,15 +1340,15 @@ private static Asn1Object getIssuer(byte[] enc) using var inp = new Asn1InputStream(memoryStream); var seq = (Asn1Sequence)inp.ReadObject(); - return (Asn1Object)seq[seq[0] is DerTaggedObject ? 3 : 2]; + return (Asn1Object)seq[seq[index: 0] is DerTaggedObject ? 3 : 2]; } private static string getStringFromGeneralName(Asn1Object names) { var taggedObject = (DerTaggedObject)names; - return EncodingsRegistry.GetEncoding(1252) - .GetString(Asn1OctetString.GetInstance(taggedObject, false).GetOctets()); + return EncodingsRegistry.GetEncoding(codepage: 1252) + .GetString(Asn1OctetString.GetInstance(taggedObject, declaredExplicit: false).GetOctets()); } /// @@ -1364,7 +1362,7 @@ private static Asn1Object getSubject(byte[] enc) using var inp = new Asn1InputStream(memoryStream); var seq = (Asn1Sequence)inp.ReadObject(); - return (Asn1Object)seq[seq[0] is DerTaggedObject ? 5 : 4]; + return (Asn1Object)seq[seq[index: 0] is DerTaggedObject ? 5 : 4]; } /// @@ -1449,8 +1447,8 @@ private void findOcsp(Asn1Sequence seq) while (true) { - if (seq[0] is DerObjectIdentifier && - ((DerObjectIdentifier)seq[0]).Id.Equals(OcspObjectIdentifiers.PkixOcspBasic.Id, + if (seq[index: 0] is DerObjectIdentifier && + ((DerObjectIdentifier)seq[index: 0]).Id.Equals(OcspObjectIdentifiers.PkixOcspBasic.Id, StringComparison.Ordinal)) { break; @@ -1462,7 +1460,7 @@ private void findOcsp(Asn1Sequence seq) { if (seq[k] is Asn1Sequence) { - seq = (Asn1Sequence)seq[0]; + seq = (Asn1Sequence)seq[index: 0]; ret = false; break; @@ -1490,7 +1488,7 @@ private void findOcsp(Asn1Sequence seq) } } - var os = (DerOctetString)seq[1]; + var os = (DerOctetString)seq[index: 1]; using var inp = new Asn1InputStream(os.GetOctets()); var resp = BasicOcspResponse.GetInstance(inp.ReadObject()); Ocsp = new BasicOcspResp(resp); @@ -1521,12 +1519,12 @@ private static DerSet getAuthenticatedAttributeSet(byte[] secondDigest, DateTime var v2 = new Asn1EncodableVector(); v2.Add(OcspObjectIdentifiers.PkixOcspBasic); v2.Add(doctet); - var den = new DerEnumerated(0); + var den = new DerEnumerated(val: 0); var v3 = new Asn1EncodableVector(); v3.Add(den); - v3.Add(new DerTaggedObject(true, 0, new DerSequence(v2))); + v3.Add(new DerTaggedObject(isExplicit: true, tagNo: 0, new DerSequence(v2))); vo1.Add(new DerSequence(v3)); - v.Add(new DerSet(new DerSequence(new DerTaggedObject(true, 1, new DerSequence(vo1))))); + v.Add(new DerSet(new DerSequence(new DerTaggedObject(isExplicit: true, tagNo: 1, new DerSequence(vo1))))); attribute.Add(new DerSequence(v)); } @@ -1541,17 +1539,17 @@ public class X509Name /// /// country code - StringType(SIZE(2)) /// - public static DerObjectIdentifier C = new("2.5.4.6"); + public static DerObjectIdentifier C = new(identifier: "2.5.4.6"); /// /// common name - StringType(SIZE(1..64)) /// - public static DerObjectIdentifier Cn = new("2.5.4.3"); + public static DerObjectIdentifier Cn = new(identifier: "2.5.4.3"); /// /// object identifier /// - public static DerObjectIdentifier Dc = new("0.9.2342.19200300.100.1.25"); + public static DerObjectIdentifier Dc = new(identifier: "0.9.2342.19200300.100.1.25"); /// /// A Hashtable with default symbols @@ -1562,73 +1560,73 @@ public class X509Name /// /// email address in Verisign certificates /// - public static DerObjectIdentifier E = new("1.2.840.113549.1.9.1"); + public static DerObjectIdentifier E = new(identifier: "1.2.840.113549.1.9.1"); /// /// Email address (RSA PKCS#9 extension) - IA5String. /// Note: if you're trying to be ultra orthodox, don't use this! It shouldn't be in here. /// - public static DerObjectIdentifier EmailAddress = new("1.2.840.113549.1.9.1"); + public static DerObjectIdentifier EmailAddress = new(identifier: "1.2.840.113549.1.9.1"); /// /// Naming attribute of type X520name /// - public static DerObjectIdentifier Generation = new("2.5.4.44"); + public static DerObjectIdentifier Generation = new(identifier: "2.5.4.44"); /// /// Naming attribute of type X520name /// - public static DerObjectIdentifier Givenname = new("2.5.4.42"); + public static DerObjectIdentifier Givenname = new(identifier: "2.5.4.42"); /// /// Naming attribute of type X520name /// - public static DerObjectIdentifier Initials = new("2.5.4.43"); + public static DerObjectIdentifier Initials = new(identifier: "2.5.4.43"); /// /// locality name - StringType(SIZE(1..64)) /// - public static DerObjectIdentifier L = new("2.5.4.7"); + public static DerObjectIdentifier L = new(identifier: "2.5.4.7"); /// /// organization - StringType(SIZE(1..64)) /// - public static DerObjectIdentifier O = new("2.5.4.10"); + public static DerObjectIdentifier O = new(identifier: "2.5.4.10"); /// /// organizational unit name - StringType(SIZE(1..64)) /// - public static DerObjectIdentifier Ou = new("2.5.4.11"); + public static DerObjectIdentifier Ou = new(identifier: "2.5.4.11"); /// /// device serial number name - StringType(SIZE(1..64)) /// - public static DerObjectIdentifier Sn = new("2.5.4.5"); + public static DerObjectIdentifier Sn = new(identifier: "2.5.4.5"); /// /// state, or province name - StringType(SIZE(1..64)) /// - public static DerObjectIdentifier St = new("2.5.4.8"); + public static DerObjectIdentifier St = new(identifier: "2.5.4.8"); /// /// Naming attribute of type X520name /// - public static DerObjectIdentifier Surname = new("2.5.4.4"); + public static DerObjectIdentifier Surname = new(identifier: "2.5.4.4"); /// /// Title /// - public static DerObjectIdentifier T = new("2.5.4.12"); + public static DerObjectIdentifier T = new(identifier: "2.5.4.12"); /// /// LDAP User id. /// - public static DerObjectIdentifier Uid = new("0.9.2342.19200300.100.1.1"); + public static DerObjectIdentifier Uid = new(identifier: "0.9.2342.19200300.100.1.1"); /// /// Naming attribute of type X520name /// - public static DerObjectIdentifier UniqueIdentifier = new("2.5.4.45"); + public static DerObjectIdentifier UniqueIdentifier = new(identifier: "2.5.4.45"); /// /// A Hashtable with values @@ -1674,7 +1672,7 @@ public X509Name(Asn1Sequence seq) for (var i = 0; i < sett.Count; i++) { var s = (Asn1Sequence)sett[i]; - var id = DefaultSymbols[s[0]]; + var id = DefaultSymbols[s[index: 0]]; if (id == null) { @@ -1689,7 +1687,7 @@ public X509Name(Asn1Sequence seq) Values[id] = vs; } - vs.Add(((DerStringBase)s[1]).GetString()); + vs.Add(((DerStringBase)s[index: 1]).GetString()); } } } @@ -1705,14 +1703,14 @@ public X509Name(string dirName) while (nTok.HasMoreTokens()) { var token = nTok.NextToken(); - var index = token.IndexOf("=", StringComparison.Ordinal); + var index = token.IndexOf(value: "=", StringComparison.Ordinal); if (index == -1) { - throw new ArgumentException("badly formated directory string"); + throw new ArgumentException(message: "badly formated directory string"); } - var id = token.Substring(0, index).ToUpper(CultureInfo.InvariantCulture); + var id = token.Substring(startIndex: 0, index).ToUpper(CultureInfo.InvariantCulture); var value = token.Substring(index + 1); var vs = Values[id]; @@ -1730,7 +1728,7 @@ public string GetField(string name) { var vs = Values[name]; - return vs == null ? null : vs[0]; + return vs == null ? null : vs[index: 0]; } /// diff --git a/src/iTextSharp.LGPLv2.Core/iTextSharp/text/pdf/PdfSmartCopy.cs b/src/iTextSharp.LGPLv2.Core/iTextSharp/text/pdf/PdfSmartCopy.cs index 4814e33..4236850 100644 --- a/src/iTextSharp.LGPLv2.Core/iTextSharp/text/pdf/PdfSmartCopy.cs +++ b/src/iTextSharp.LGPLv2.Core/iTextSharp/text/pdf/PdfSmartCopy.cs @@ -15,13 +15,13 @@ public class PdfSmartCopy : PdfCopy /// /// the cache with the streams and references. /// - private readonly INullValueDictionary _streamMap; + private readonly NullValueDictionary _streamMap; /// /// Creates a PdfSmartCopy instance. /// - public PdfSmartCopy(Document document, Stream os) : base(document, os) => - _streamMap = new NullValueDictionary(); + public PdfSmartCopy(Document document, Stream os) : base(document, os) + => _streamMap = new NullValueDictionary(); /// /// Translate a PRIndirectReference to a PdfIndirectReference @@ -42,6 +42,7 @@ protected override PdfIndirectReference CopyIndirect(PrIndirectReference inp) } var srcObj = PdfReader.GetPdfObjectRelease(inp); + if (srcObj == null) { return null; @@ -50,9 +51,11 @@ protected override PdfIndirectReference CopyIndirect(PrIndirectReference inp) PdfIndirectReference theRef; var key = new RefKey(inp); var iRef = Indirects[key]; + if (iRef != null) { theRef = iRef.Ref; + if (iRef.Copied) { return theRef; @@ -61,20 +64,22 @@ protected override PdfIndirectReference CopyIndirect(PrIndirectReference inp) else { ByteStore streamKey = null; + if (srcObj.IsStream() || srcObj.IsDictionary()) { streamKey = new ByteStore(srcObj); var streamRef = _streamMap[streamKey]; + if (streamRef != null) { return streamRef; } } - + theRef = Body.PdfIndirectReference; iRef = new IndirectReferences(theRef); Indirects[key] = iRef; - + if (streamKey != null) { _streamMap[streamKey] = theRef; @@ -84,6 +89,7 @@ protected override PdfIndirectReference CopyIndirect(PrIndirectReference inp) if (srcObj.IsDictionary()) { var type = PdfReader.GetPdfObjectRelease(((PdfDictionary)srcObj).Get(PdfName.TYPE)); + if (type != null && PdfName.Page.Equals(type)) { return theRef; @@ -94,13 +100,14 @@ protected override PdfIndirectReference CopyIndirect(PrIndirectReference inp) var obj = CopyObject(srcObj); AddToBody(obj, theRef); + return theRef; } internal class ByteStore { private readonly byte[] _b; - private List _references; + private readonly List _references; internal ByteStore(PdfObject str) { @@ -124,12 +131,14 @@ public override bool Equals(object obj) } var b2 = store._b; + if (b2.Length != _b.Length) { return false; } var len = _b.Length; + for (var k = 0; k < len; ++k) { if (_b[k] != b2[k]) @@ -145,6 +154,7 @@ public override int GetHashCode() { var hash = 0; var len = _b.Length; + for (var k = 0; k < len; ++k) { hash = hash * 31 + _b[k]; @@ -155,7 +165,8 @@ public override int GetHashCode() private void serArray(PdfArray array, int level, ByteBuffer bb) { - bb.Append("$A"); + bb.Append(str: "$A"); + if (level <= 0) { return; @@ -169,15 +180,17 @@ private void serArray(PdfArray array, int level, ByteBuffer bb) private void serDic(PdfDictionary dic, int level, ByteBuffer bb) { - bb.Append("$D"); + bb.Append(str: "$D"); + if (level <= 0) { return; } var keys = new PdfName[dic.Size]; - dic.Keys.CopyTo(keys, 0); + dic.Keys.CopyTo(keys, arrayIndex: 0); Array.Sort(keys); + for (var k = 0; k < keys.Length; ++k) { serObject(keys[k], level, bb); @@ -194,7 +207,8 @@ private void serObject(PdfObject obj, int level, ByteBuffer bb) if (obj == null) { - bb.Append("$Lnull"); + bb.Append(str: "$Lnull"); + return; } @@ -202,10 +216,12 @@ private void serObject(PdfObject obj, int level, ByteBuffer bb) { var refKey = new RefKey((PdfIndirectReference)obj); var refIdx = _references.IndexOf(refKey); + if (refIdx >= 0) { // Already seen, print relative reference label only bb.Append($"$R{refIdx}"); + return; } @@ -215,9 +231,10 @@ private void serObject(PdfObject obj, int level, ByteBuffer bb) } obj = PdfReader.GetPdfObject(obj); + if (obj.IsStream()) { - bb.Append("$B"); + bb.Append(str: "$B"); serDic((PdfDictionary)obj, level - 1, bb); using var md5 = MD5BouncyCastle.Create(); bb.Append(md5.ComputeHash(PdfReader.GetStreamBytesRaw((PrStream)obj))); @@ -232,15 +249,15 @@ private void serObject(PdfObject obj, int level, ByteBuffer bb) } else if (obj.IsString()) { - bb.Append("$S").Append(obj.ToString()); + bb.Append(str: "$S").Append(obj.ToString()); } else if (obj.IsName()) { - bb.Append("$N").Append(obj.ToString()); + bb.Append(str: "$N").Append(obj.ToString()); } else { - bb.Append("$L").Append(obj.ToString()); + bb.Append(str: "$L").Append(obj.ToString()); } } } diff --git a/src/iTextSharp.LGPLv2.Core/iTextSharp/text/pdf/SimpleBookmark.cs b/src/iTextSharp.LGPLv2.Core/iTextSharp/text/pdf/SimpleBookmark.cs index 46dd85f..7c4bd16 100644 --- a/src/iTextSharp.LGPLv2.Core/iTextSharp/text/pdf/SimpleBookmark.cs +++ b/src/iTextSharp.LGPLv2.Core/iTextSharp/text/pdf/SimpleBookmark.cs @@ -55,36 +55,36 @@ public void EndElement(string tag) throw new ArgumentNullException(nameof(tag)); } - if (tag.Equals("Bookmark", StringComparison.Ordinal)) + if (tag.Equals(value: "Bookmark", StringComparison.Ordinal)) { if (_attr.Count == 0) { return; } - throw new InvalidOperationException("Bookmark end tag out of place."); + throw new InvalidOperationException(message: "Bookmark end tag out of place."); } - if (!tag.Equals("Title", StringComparison.Ordinal)) + if (!tag.Equals(value: "Title", StringComparison.Ordinal)) { throw new InvalidOperationException("Invalid end tag - " + tag); } var attributes = _attr.Pop(); - var title = (string)attributes["Title"]; - attributes["Title"] = title.Trim(); - var named = (string)attributes["Named"]; + var title = (string)attributes[key: "Title"]; + attributes[key: "Title"] = title.Trim(); + var named = (string)attributes[key: "Named"]; if (named != null) { - attributes["Named"] = UnEscapeBinaryString(named); + attributes[key: "Named"] = UnEscapeBinaryString(named); } - named = (string)attributes["NamedN"]; + named = (string)attributes[key: "NamedN"]; if (named != null) { - attributes["NamedN"] = UnEscapeBinaryString(named); + attributes[key: "NamedN"] = UnEscapeBinaryString(named); } if (_attr.Count == 0) @@ -94,12 +94,12 @@ public void EndElement(string tag) else { var parent = _attr.Peek(); - var kids = (IList>)parent["Kids"]; + var kids = (IList>)parent[key: "Kids"]; if (kids == null) { kids = new List>(); - parent["Kids"] = kids; + parent[key: "Kids"] = kids; } kids.Add(attributes); @@ -118,9 +118,9 @@ public void Text(string str) } var attributes = _attr.Peek(); - var title = (string)attributes["Title"]; + var title = (string)attributes[key: "Title"]; title += str; - attributes["Title"] = title; + attributes[key: "Title"] = title; } public void StartElement(string tag, INullValueDictionary h) @@ -137,7 +137,7 @@ public void StartElement(string tag, INullValueDictionary h) if (_topList == null) { - if (tag.Equals("Bookmark", StringComparison.Ordinal)) + if (tag.Equals(value: "Bookmark", StringComparison.Ordinal)) { _topList = new List>(); @@ -147,7 +147,7 @@ public void StartElement(string tag, INullValueDictionary h) throw new InvalidOperationException("Root element is not Bookmark: " + tag); } - if (!tag.Equals("Title", StringComparison.Ordinal)) + if (!tag.Equals(value: "Title", StringComparison.Ordinal)) { throw new InvalidOperationException("Tag " + tag + " not allowed."); } @@ -159,8 +159,8 @@ public void StartElement(string tag, INullValueDictionary h) attributes[kv.Key] = kv.Value; } - attributes["Title"] = ""; - attributes.Remove("Kids"); + attributes[key: "Title"] = ""; + attributes.Remove(key: "Kids"); _attr.Push(attributes); } @@ -188,14 +188,14 @@ public static void EliminatePages(IList> li var map = it.Next(); var hit = false; - if ("GoTo".Equals(map["Action"])) + if ("GoTo".Equals(map[key: "Action"])) { - var page = (string)map["Page"]; + var page = (string)map[key: "Page"]; if (page != null) { page = page.Trim(); - var idx = page.IndexOf(" ", StringComparison.Ordinal); + var idx = page.IndexOf(value: " ", StringComparison.Ordinal); int pageNum; if (idx < 0) @@ -204,7 +204,7 @@ public static void EliminatePages(IList> li } else { - pageNum = int.Parse(page.Substring(0, idx), CultureInfo.InvariantCulture); + pageNum = int.Parse(page.Substring(startIndex: 0, idx), CultureInfo.InvariantCulture); } var len = pageRange.Length & 0x7ffffffe; @@ -221,7 +221,7 @@ public static void EliminatePages(IList> li } } - var kids = (IList>)map["Kids"]; + var kids = (IList>)map[key: "Kids"]; if (kids != null) { @@ -229,7 +229,7 @@ public static void EliminatePages(IList> li if (kids.Count == 0) { - map.Remove("Kids"); + map.Remove(key: "Kids"); kids = null; } } @@ -242,9 +242,9 @@ public static void EliminatePages(IList> li } else { - map.Remove("Action"); - map.Remove("Page"); - map.Remove("Named"); + map.Remove(key: "Action"); + map.Remove(key: "Page"); + map.Remove(key: "Named"); } } } @@ -267,7 +267,7 @@ public static string EscapeBinaryString(string s) if (c < ' ') { - buf.Append('\\'); + buf.Append(value: '\\'); int v = c; var octal = ""; @@ -279,11 +279,11 @@ public static string EscapeBinaryString(string s) } while (v > 0); - buf.Append(octal.PadLeft(3, '0')); + buf.Append(octal.PadLeft(totalWidth: 3, paddingChar: '0')); } else if (c == '\\') { - buf.Append("\\\\"); + buf.Append(value: "\\\\"); } else { @@ -346,11 +346,11 @@ public static void ExportToXml(IList> list, throw new ArgumentNullException(nameof(wrt)); } - wrt.Write("\n\n"); - ExportToXmlNode(list, wrt, 1, onlyAscii); - wrt.Write("\n"); + wrt.Write(value: "\"?>\n\n"); + ExportToXmlNode(list, wrt, indent: 1, onlyAscii); + wrt.Write(value: "\n"); wrt.Flush(); } @@ -390,21 +390,21 @@ public static void ExportToXmlNode(IList> l { string title = null; outp.Write(dep); - outp.Write("> kids = null; foreach (var entry in map) { var key = entry.Key; - if (key.Equals("Title", StringComparison.Ordinal)) + if (key.Equals(value: "Title", StringComparison.Ordinal)) { title = (string)entry.Value; continue; } - if (key.Equals("Kids", StringComparison.Ordinal)) + if (key.Equals(value: "Kids", StringComparison.Ordinal)) { kids = (IList<INullValueDictionary<string, object>>)entry.Value; @@ -412,19 +412,20 @@ public static void ExportToXmlNode(IList<INullValueDictionary<string, object>> l } outp.Write(key); - outp.Write("=\""); + outp.Write(value: "=\""); var value = (string)entry.Value; - if (key.Equals("Named", StringComparison.Ordinal) || key.Equals("NamedN", StringComparison.Ordinal)) + if (key.Equals(value: "Named", StringComparison.Ordinal) || + key.Equals(value: "NamedN", StringComparison.Ordinal)) { value = EscapeBinaryString(value); } outp.Write(SimpleXmlParser.EscapeXml(value, onlyAscii)); - outp.Write("\" "); + outp.Write(value: "\" "); } - outp.Write(">"); + outp.Write(value: ">"); if (title == null) { @@ -435,12 +436,12 @@ public static void ExportToXmlNode(IList<INullValueDictionary<string, object>> l if (kids != null) { - outp.Write("\n"); + outp.Write(value: "\n"); ExportToXmlNode(kids, outp, indent + 1, onlyAscii); outp.Write(dep); } - outp.Write("\n"); + outp.Write(value: "\n"); } } @@ -535,7 +536,7 @@ public static object[] IterateOutlines(PdfWriter writer, foreach (var map in kids) { object[] lower = null; - var subKid = (IList>)map["Kids"]; + var subKid = (IList>)map[key: "Kids"]; if (subKid != null && subKid.Count > 0) { @@ -551,7 +552,7 @@ public static object[] IterateOutlines(PdfWriter writer, outline.Put(PdfName.Last, (PdfIndirectReference)lower[1]); var n = (int)lower[2]; - if ("false".Equals(map["Open"])) + if ("false".Equals(map[key: "Open"])) { outline.Put(PdfName.Count, new PdfNumber(-n)); } @@ -574,8 +575,8 @@ public static object[] IterateOutlines(PdfWriter writer, outline.Put(PdfName.Next, refs[ptr + 1]); } - outline.Put(PdfName.Title, new PdfString((string)map["Title"], PdfObject.TEXT_UNICODE)); - var color = (string)map["Color"]; + outline.Put(PdfName.Title, new PdfString((string)map[key: "Title"], PdfObject.TEXT_UNICODE)); + var color = (string)map[key: "Color"]; if (color != null) { @@ -608,18 +609,18 @@ public static object[] IterateOutlines(PdfWriter writer, } //in case it's malformed } - var style = (string)map["Style"]; + var style = (string)map[key: "Style"]; if (style != null) { var bits = 0; - if (style.IndexOf("italic", StringComparison.OrdinalIgnoreCase) >= 0) + if (style.IndexOf(value: "italic", StringComparison.OrdinalIgnoreCase) >= 0) { bits |= 1; } - if (style.IndexOf("bold", StringComparison.OrdinalIgnoreCase) >= 0) + if (style.IndexOf(value: "bold", StringComparison.OrdinalIgnoreCase) >= 0) { bits |= 2; } @@ -662,14 +663,14 @@ public static void ShiftPageNumbers(IList> foreach (var map in list) { - if ("GoTo".Equals(map["Action"])) + if ("GoTo".Equals(map[key: "Action"])) { - var page = (string)map["Page"]; + var page = (string)map[key: "Page"]; if (page != null) { page = page.Trim(); - var idx = page.IndexOf(" ", StringComparison.Ordinal); + var idx = page.IndexOf(value: " ", StringComparison.Ordinal); int pageNum; if (idx < 0) @@ -678,7 +679,7 @@ public static void ShiftPageNumbers(IList> } else { - pageNum = int.Parse(page.Substring(0, idx), CultureInfo.InvariantCulture); + pageNum = int.Parse(page.Substring(startIndex: 0, idx), CultureInfo.InvariantCulture); } var hit = false; @@ -714,11 +715,11 @@ public static void ShiftPageNumbers(IList> } } - map["Page"] = page; + map[key: "Page"] = page; } } - var kids = (IList>)map["Kids"]; + var kids = (IList>)map[key: "Kids"]; if (kids != null) { @@ -746,7 +747,7 @@ public static string UnEscapeBinaryString(string s) { if (++k >= len) { - buf.Append('\\'); + buf.Append(value: '\\'); break; } @@ -797,13 +798,13 @@ internal static void CreateOutlineAction(PdfDictionary outline, { try { - var action = (string)map["Action"]; + var action = (string)map[key: "Action"]; if ("GoTo".Equals(action, StringComparison.Ordinal)) { string p; - if ((p = (string)map["Named"]) != null) + if ((p = (string)map[key: "Named"]) != null) { if (namedAsNames) { @@ -811,10 +812,10 @@ internal static void CreateOutlineAction(PdfDictionary outline, } else { - outline.Put(PdfName.Dest, new PdfString(p, null)); + outline.Put(PdfName.Dest, new PdfString(p, encoding: null)); } } - else if ((p = (string)map["Page"]) != null) + else if ((p = (string)map[key: "Page"]) != null) { var ar = new PdfArray(); var tk = new StringTokenizer(p); @@ -834,9 +835,9 @@ internal static void CreateOutlineAction(PdfDictionary outline, { var fn = tk.NextToken(); - if (fn.StartsWith("/", StringComparison.Ordinal)) + if (fn.StartsWith(value: "/", StringComparison.Ordinal)) { - fn = fn.Substring(1); + fn = fn.Substring(startIndex: 1); } ar.Add(new PdfName(fn)); @@ -845,7 +846,7 @@ internal static void CreateOutlineAction(PdfDictionary outline, { fn = tk.NextToken(); - if (fn.Equals("null", StringComparison.Ordinal)) + if (fn.Equals(value: "null", StringComparison.Ordinal)) { ar.Add(PdfNull.Pdfnull); } @@ -864,15 +865,15 @@ internal static void CreateOutlineAction(PdfDictionary outline, string p; var dic = new PdfDictionary(); - if ((p = (string)map["Named"]) != null) + if ((p = (string)map[key: "Named"]) != null) { - dic.Put(PdfName.D, new PdfString(p, null)); + dic.Put(PdfName.D, new PdfString(p, encoding: null)); } - else if ((p = (string)map["NamedN"]) != null) + else if ((p = (string)map[key: "NamedN"]) != null) { dic.Put(PdfName.D, new PdfName(p)); } - else if ((p = (string)map["Page"]) != null) + else if ((p = (string)map[key: "Page"]) != null) { var ar = new PdfArray(); var tk = new StringTokenizer(p); @@ -891,9 +892,9 @@ internal static void CreateOutlineAction(PdfDictionary outline, { var fn = tk.NextToken(); - if (fn.StartsWith("/", StringComparison.Ordinal)) + if (fn.StartsWith(value: "/", StringComparison.Ordinal)) { - fn = fn.Substring(1); + fn = fn.Substring(startIndex: 1); } ar.Add(new PdfName(fn)); @@ -902,7 +903,7 @@ internal static void CreateOutlineAction(PdfDictionary outline, { fn = tk.NextToken(); - if (fn.Equals("null", StringComparison.Ordinal)) + if (fn.Equals(value: "null", StringComparison.Ordinal)) { ar.Add(PdfNull.Pdfnull); } @@ -916,21 +917,21 @@ internal static void CreateOutlineAction(PdfDictionary outline, dic.Put(PdfName.D, ar); } - var file = (string)map["File"]; + var file = (string)map[key: "File"]; if (dic.Size > 0 && file != null) { dic.Put(PdfName.S, PdfName.Gotor); dic.Put(PdfName.F, new PdfString(file)); - var nw = (string)map["NewWindow"]; + var nw = (string)map[key: "NewWindow"]; if (nw != null) { - if (nw.Equals("true", StringComparison.Ordinal)) + if (nw.Equals(value: "true", StringComparison.Ordinal)) { dic.Put(PdfName.Newwindow, PdfBoolean.Pdftrue); } - else if (nw.Equals("false", StringComparison.Ordinal)) + else if (nw.Equals(value: "false", StringComparison.Ordinal)) { dic.Put(PdfName.Newwindow, PdfBoolean.Pdffalse); } @@ -941,7 +942,7 @@ internal static void CreateOutlineAction(PdfDictionary outline, } else if ("URI".Equals(action, StringComparison.Ordinal)) { - var uri = (string)map["URI"]; + var uri = (string)map[key: "URI"]; if (uri != null) { @@ -953,7 +954,7 @@ internal static void CreateOutlineAction(PdfDictionary outline, } else if ("Launch".Equals(action, StringComparison.Ordinal)) { - var file = (string)map["File"]; + var file = (string)map[key: "File"]; if (file != null) { @@ -980,16 +981,16 @@ private static List> bookmarkDepth(PdfReade { var map = new NullValueDictionary(); var title = (PdfString)PdfReader.GetPdfObjectRelease(outline.Get(PdfName.Title)); - map["Title"] = title.ToUnicodeString(); + map[key: "Title"] = title.ToUnicodeString(); var color = (PdfArray)PdfReader.GetPdfObjectRelease(outline.Get(PdfName.C)); if (color != null && color.Size == 3) { var outp = new ByteBuffer(); - outp.Append(color.GetAsNumber(0).FloatValue).Append(' '); - outp.Append(color.GetAsNumber(1).FloatValue).Append(' '); - outp.Append(color.GetAsNumber(2).FloatValue); - map["Color"] = PdfEncodings.ConvertToString(outp.ToByteArray(), null); + outp.Append(color.GetAsNumber(idx: 0).FloatValue).Append(c: ' '); + outp.Append(color.GetAsNumber(idx: 1).FloatValue).Append(c: ' '); + outp.Append(color.GetAsNumber(idx: 2).FloatValue); + map[key: "Color"] = PdfEncodings.ConvertToString(outp.ToByteArray(), encoding: null); } var style = (PdfNumber)PdfReader.GetPdfObjectRelease(outline.Get(PdfName.F)); @@ -1013,7 +1014,7 @@ private static List> bookmarkDepth(PdfReade if (s.Length != 0) { - map["Style"] = s; + map[key: "Style"] = s; } } @@ -1021,7 +1022,7 @@ private static List> bookmarkDepth(PdfReade if (count != null && count.IntValue < 0) { - map["Open"] = "false"; + map[key: "Open"] = "false"; } try @@ -1049,9 +1050,9 @@ private static List> bookmarkDepth(PdfReade } else if (PdfName.Uri.Equals(PdfReader.GetPdfObjectRelease(action.Get(PdfName.S)))) { - map["Action"] = "URI"; + map[key: "Action"] = "URI"; - map["URI"] = ((PdfString)PdfReader.GetPdfObjectRelease(action.Get(PdfName.Uri))) + map[key: "URI"] = ((PdfString)PdfReader.GetPdfObjectRelease(action.Get(PdfName.Uri))) .ToUnicodeString(); } else if (PdfName.Gotor.Equals(PdfReader.GetPdfObjectRelease(action.Get(PdfName.S)))) @@ -1062,36 +1063,36 @@ private static List> bookmarkDepth(PdfReade { if (dest.IsString()) { - map["Named"] = dest.ToString(); + map[key: "Named"] = dest.ToString(); } else if (dest.IsName()) { - map["NamedN"] = PdfName.DecodeName(dest.ToString()); + map[key: "NamedN"] = PdfName.DecodeName(dest.ToString()); } else if (dest.IsArray()) { var arr = (PdfArray)dest; var s = new StringBuilder(); - s.Append(arr[0]); - s.Append(' ').Append(arr[1]); + s.Append(arr[idx: 0]); + s.Append(value: ' ').Append(arr[idx: 1]); for (var k = 2; k < arr.Size; ++k) { - s.Append(' ').Append(arr[k]); + s.Append(value: ' ').Append(arr[k]); } - map["Page"] = s.ToString(); + map[key: "Page"] = s.ToString(); } } - map["Action"] = "GoToR"; + map[key: "Action"] = "GoToR"; var file = PdfReader.GetPdfObjectRelease(action.Get(PdfName.F)); if (file != null) { if (file.IsString()) { - map["File"] = ((PdfString)file).ToUnicodeString(); + map[key: "File"] = ((PdfString)file).ToUnicodeString(); } else if (file.IsDictionary()) { @@ -1099,7 +1100,7 @@ private static List> bookmarkDepth(PdfReade if (file.IsString()) { - map["File"] = ((PdfString)file).ToUnicodeString(); + map[key: "File"] = ((PdfString)file).ToUnicodeString(); } } } @@ -1108,12 +1109,12 @@ private static List> bookmarkDepth(PdfReade if (newWindow != null) { - map["NewWindow"] = newWindow.ToString(); + map[key: "NewWindow"] = newWindow.ToString(); } } else if (PdfName.Launch.Equals(PdfReader.GetPdfObjectRelease(action.Get(PdfName.S)))) { - map["Action"] = "Launch"; + map[key: "Action"] = "Launch"; var file = PdfReader.GetPdfObjectRelease(action.Get(PdfName.F)); if (file == null) @@ -1125,7 +1126,7 @@ private static List> bookmarkDepth(PdfReade { if (file.IsString()) { - map["File"] = ((PdfString)file).ToUnicodeString(); + map[key: "File"] = ((PdfString)file).ToUnicodeString(); } else if (file.IsDictionary()) { @@ -1133,7 +1134,7 @@ private static List> bookmarkDepth(PdfReade if (file.IsString()) { - map["File"] = ((PdfString)file).ToUnicodeString(); + map[key: "File"] = ((PdfString)file).ToUnicodeString(); } } } @@ -1150,7 +1151,7 @@ private static List> bookmarkDepth(PdfReade if (first != null) { - map["Kids"] = bookmarkDepth(reader, first, pages); + map[key: "Kids"] = bookmarkDepth(reader, first, pages); } list.Add(map); @@ -1174,7 +1175,7 @@ private static int getNumber(PdfIndirectReference indirect) pdfObj.Contains(PdfName.Kids)) { var kids = (PdfArray)pdfObj.Get(PdfName.Kids); - indirect = (PdfIndirectReference)kids[0]; + indirect = (PdfIndirectReference)kids[idx: 0]; } return indirect.Number; @@ -1183,7 +1184,7 @@ private static int getNumber(PdfIndirectReference indirect) private static string makeBookmarkParam(PdfArray dest, NullValueDictionary pages) { var s = new StringBuilder(); - var obj = dest[0]; + var obj = dest[idx: 0]; if (obj.IsNumber()) { @@ -1194,33 +1195,33 @@ private static string makeBookmarkParam(PdfArray dest, NullValueDictionary map, + private static void mapGotoBookmark(NullValueDictionary map, PdfObject dest, NullValueDictionary pages) { if (dest.IsString()) { - map["Named"] = dest.ToString(); + map[key: "Named"] = dest.ToString(); } else if (dest.IsName()) { - map["Named"] = PdfName.DecodeName(dest.ToString()); + map[key: "Named"] = PdfName.DecodeName(dest.ToString()); } else if (dest.IsArray()) { - map["Page"] = makeBookmarkParam((PdfArray)dest, pages); //changed by ujihara 2004-06-13 + map[key: "Page"] = makeBookmarkParam((PdfArray)dest, pages); //changed by ujihara 2004-06-13 } - map["Action"] = "GoTo"; + map[key: "Action"] = "GoTo"; } } \ No newline at end of file diff --git a/src/iTextSharp.LGPLv2.Core/iTextSharp/text/pdf/SimpleNamedDestination.cs b/src/iTextSharp.LGPLv2.Core/iTextSharp/text/pdf/SimpleNamedDestination.cs index 52d62ef..87fe072 100644 --- a/src/iTextSharp.LGPLv2.Core/iTextSharp/text/pdf/SimpleNamedDestination.cs +++ b/src/iTextSharp.LGPLv2.Core/iTextSharp/text/pdf/SimpleNamedDestination.cs @@ -10,7 +10,7 @@ namespace iTextSharp.text.pdf; public sealed class SimpleNamedDestination : ISimpleXmlDocHandler { private NullValueDictionary _xmlLast; - private INullValueDictionary _xmlNames; + private NullValueDictionary _xmlNames; private SimpleNamedDestination() { @@ -27,32 +27,32 @@ public void EndElement(string tag) throw new ArgumentNullException(nameof(tag)); } - if (tag.Equals("Destination", StringComparison.Ordinal)) + if (tag.Equals(value: "Destination", StringComparison.Ordinal)) { if (_xmlLast == null && _xmlNames != null) { return; } - throw new ArgumentException("Destination end tag out of place."); + throw new ArgumentException(message: "Destination end tag out of place."); } - if (!tag.Equals("Name", StringComparison.Ordinal)) + if (!tag.Equals(value: "Name", StringComparison.Ordinal)) { throw new ArgumentException("Invalid end tag - " + tag); } if (_xmlLast == null || _xmlNames == null) { - throw new ArgumentException("Name end tag out of place."); + throw new ArgumentException(message: "Name end tag out of place."); } - if (!_xmlLast.TryGetValue("Page", out var pageValue)) + if (!_xmlLast.TryGetValue(key: "Page", out var pageValue)) { - throw new ArgumentException("Page attribute missing."); + throw new ArgumentException(message: "Page attribute missing."); } - _xmlNames[UnEscapeBinaryString(_xmlLast["Name"])] = pageValue; + _xmlNames[UnEscapeBinaryString(_xmlLast[key: "Name"])] = pageValue; _xmlLast = null; } @@ -67,9 +67,9 @@ public void Text(string str) return; } - var name = _xmlLast["Name"]; + var name = _xmlLast[key: "Name"]; name += str; - _xmlLast["Name"] = name; + _xmlLast[key: "Name"] = name; } public void StartElement(string tag, INullValueDictionary h) @@ -81,28 +81,28 @@ public void StartElement(string tag, INullValueDictionary h) if (_xmlNames == null) { - if (tag.Equals("Destination", StringComparison.Ordinal)) + if (tag.Equals(value: "Destination", StringComparison.Ordinal)) { _xmlNames = new NullValueDictionary(); return; } - throw new ArgumentException("Root element is not Destination."); + throw new ArgumentException(message: "Root element is not Destination."); } - if (!tag.Equals("Name", StringComparison.Ordinal)) + if (!tag.Equals(value: "Name", StringComparison.Ordinal)) { throw new ArgumentException("Tag " + tag + " not allowed."); } if (_xmlLast != null) { - throw new ArgumentException("Nested tags are not allowed."); + throw new ArgumentException(message: "Nested tags are not allowed."); } _xmlLast = new NullValueDictionary(h); - _xmlLast["Name"] = ""; + _xmlLast[key: "Name"] = ""; } public static string EscapeBinaryString(string s) @@ -122,14 +122,14 @@ public static string EscapeBinaryString(string s) if (c < ' ') { - buf.Append('\\'); - ((int)c).ToString("", CultureInfo.InvariantCulture); - var octal = "00" + Convert.ToString(c, 8); + buf.Append(value: '\\'); + ((int)c).ToString(format: "", CultureInfo.InvariantCulture); + var octal = "00" + Convert.ToString(c, toBase: 8); buf.Append(octal.Substring(octal.Length - 3)); } else if (c == '\\') { - buf.Append("\\\\"); + buf.Append(value: "\\\\"); } else { @@ -188,21 +188,21 @@ public static void ExportToXml(INullValueDictionary names, throw new ArgumentNullException(nameof(wrt)); } - wrt.Write("\n\n"); + wrt.Write(value: "\"?>\n\n"); foreach (var key in names.Keys) { var value = names[key]; - wrt.Write(" "); + wrt.Write(value: "\">"); wrt.Write(SimpleXmlParser.EscapeXml(EscapeBinaryString(key), onlyAscii)); - wrt.Write("\n"); + wrt.Write(value: "\n"); } - wrt.Write("\n"); + wrt.Write(value: "\n"); wrt.Flush(); } @@ -224,7 +224,7 @@ public static INullValueDictionary GetNamedDestination(PdfReader var names = fromNames ? reader.GetNamedDestinationFromNames() : reader.GetNamedDestinationFromStrings(); var n2 = new NullValueDictionary(names.Count); var keys = new string[names.Count]; - names.Keys.CopyTo(keys, 0); + names.Keys.CopyTo(keys, arrayIndex: 0); foreach (var name in keys) { @@ -233,12 +233,12 @@ public static INullValueDictionary GetNamedDestination(PdfReader try { - s.Append(pages[arr.GetAsIndirectObject(0).Number]); - s.Append(' ').Append(arr[1].ToString().Substring(1)); + s.Append(pages[arr.GetAsIndirectObject(idx: 0).Number]); + s.Append(value: ' ').Append(arr[idx: 1].ToString().Substring(startIndex: 1)); for (var k = 2; k < arr.Size; ++k) { - s.Append(' ').Append(arr[k]); + s.Append(value: ' ').Append(arr[k]); } n2[name] = s.ToString(); @@ -363,7 +363,7 @@ public static string UnEscapeBinaryString(string s) { if (++k >= len) { - buf.Append('\\'); + buf.Append(value: '\\'); break; } @@ -427,9 +427,9 @@ internal static PdfArray CreateDestinationArray(string value, PdfWriter writer) { var fn = tk.NextToken(); - if (fn.StartsWith("/", StringComparison.Ordinal)) + if (fn.StartsWith(value: "/", StringComparison.Ordinal)) { - fn = fn.Substring(1); + fn = fn.Substring(startIndex: 1); } ar.Add(new PdfName(fn)); @@ -438,7 +438,7 @@ internal static PdfArray CreateDestinationArray(string value, PdfWriter writer) { fn = tk.NextToken(); - if (fn.Equals("null", StringComparison.Ordinal)) + if (fn.Equals(value: "null", StringComparison.Ordinal)) { ar.Add(PdfNull.Pdfnull); } diff --git a/src/iTextSharp.LGPLv2.Core/iTextSharp/text/pdf/Type1Font.cs b/src/iTextSharp.LGPLv2.Core/iTextSharp/text/pdf/Type1Font.cs index db1a055..157a9dd 100644 --- a/src/iTextSharp.LGPLv2.Core/iTextSharp/text/pdf/Type1Font.cs +++ b/src/iTextSharp.LGPLv2.Core/iTextSharp/text/pdf/Type1Font.cs @@ -42,7 +42,7 @@ internal class Type1Font : BaseFont /// the second character and position 1 is the kerning distance. This is /// repeated for all the pairs. /// - private readonly INullValueDictionary _kernPairs = new NullValueDictionary(); + private readonly NullValueDictionary _kernPairs = new(); /// /// The PFB file if the input was made with a byte array. @@ -171,7 +171,7 @@ internal Type1Font(string afmFile, string enc, bool emb, byte[] ttfAfm, byte[] p { if (emb && ttfAfm != null && pfb == null) { - throw new DocumentException("Two byte arrays are needed if the Type1 font is embedded."); + throw new DocumentException(message: "Two byte arrays are needed if the Type1 font is embedded."); } if (emb && ttfAfm != null) @@ -207,14 +207,14 @@ internal Type1Font(string afmFile, string enc, bool emb, byte[] ttfAfm, byte[] p while (true) { - var size = istr.Read(buf, 0, buf.Length); + var size = istr.Read(buf, offset: 0, buf.Length); if (size == 0) { break; } - ostr.Write(buf, 0, size); + ostr.Write(buf, offset: 0, size); } buf = ostr.ToArray(); @@ -254,7 +254,7 @@ internal Type1Font(string afmFile, string enc, bool emb, byte[] ttfAfm, byte[] p } } } - else if (afmFile.EndsWith(".afm", StringComparison.OrdinalIgnoreCase)) + else if (afmFile.EndsWith(value: ".afm", StringComparison.OrdinalIgnoreCase)) { try { @@ -284,7 +284,7 @@ internal Type1Font(string afmFile, string enc, bool emb, byte[] ttfAfm, byte[] p } } } - else if (afmFile.EndsWith(".pfm", StringComparison.OrdinalIgnoreCase)) + else if (afmFile.EndsWith(value: ".pfm", StringComparison.OrdinalIgnoreCase)) { try { @@ -326,15 +326,15 @@ internal Type1Font(string afmFile, string enc, bool emb, byte[] ttfAfm, byte[] p _encodingScheme = _encodingScheme.Trim(); - if (_encodingScheme.Equals("AdobeStandardEncoding", StringComparison.Ordinal) || - _encodingScheme.Equals("StandardEncoding", StringComparison.Ordinal)) + if (_encodingScheme.Equals(value: "AdobeStandardEncoding", StringComparison.Ordinal) || + _encodingScheme.Equals(value: "StandardEncoding", StringComparison.Ordinal)) { FontSpecific = false; } - if (!encoding.StartsWith("#", StringComparison.Ordinal)) + if (!encoding.StartsWith(value: "#", StringComparison.Ordinal)) { - PdfEncodings.ConvertToBytes(" ", enc); // check if the encoding exists + PdfEncodings.ConvertToBytes(text: " ", enc); // check if the encoding exists } CreateEncoding(); @@ -442,13 +442,13 @@ public PdfDictionary GetFontDescriptor(PdfIndirectReference fontStream) flags |= 64; } - if (_fontName.IndexOf("Caps", StringComparison.Ordinal) >= 0 || - _fontName.EndsWith("SC", StringComparison.Ordinal)) + if (_fontName.IndexOf(value: "Caps", StringComparison.Ordinal) >= 0 || + _fontName.EndsWith(value: "SC", StringComparison.Ordinal)) { flags |= 131072; } - if (_weight.Equals("Bold", StringComparison.Ordinal)) + if (_weight.Equals(value: "Bold", StringComparison.Ordinal)) { flags |= 262144; } @@ -520,11 +520,11 @@ public override PdfStream GetFullFontStream() try { - var filePfb = _fileName.Substring(0, _fileName.Length - 3) + "pfb"; + var filePfb = _fileName.Substring(startIndex: 0, _fileName.Length - 3) + "pfb"; if (Pfb == null) { - rf = new RandomAccessFileOrArray(filePfb, true); + rf = new RandomAccessFileOrArray(filePfb, forceRead: true); } else { @@ -632,8 +632,7 @@ public override int GetKerning(int char1, int char2) /// Checks if the font has any kerning pairs. /// /// true if the font has any kerning pairs - public override bool HasKernPairs() - => _kernPairs.Count > 0; + public override bool HasKernPairs() => _kernPairs.Count > 0; /// /// Reads the font metrics @@ -648,7 +647,7 @@ public void Process(RandomAccessFileOrArray rf) while ((line = rf.ReadLine()) != null) { - var tok = new StringTokenizer(line, " ,\n\r\t\f"); + var tok = new StringTokenizer(line, delim: " ,\n\r\t\f"); if (!tok.HasMoreTokens()) { @@ -657,78 +656,78 @@ public void Process(RandomAccessFileOrArray rf) var ident = tok.NextToken(); - if (ident.Equals("FontName", StringComparison.Ordinal)) + if (ident.Equals(value: "FontName", StringComparison.Ordinal)) { - _fontName = tok.NextToken("\u00ff").Substring(1); + _fontName = tok.NextToken(delim: "\u00ff").Substring(startIndex: 1); } - else if (ident.Equals("FullName", StringComparison.Ordinal)) + else if (ident.Equals(value: "FullName", StringComparison.Ordinal)) { - _fullName = tok.NextToken("\u00ff").Substring(1); + _fullName = tok.NextToken(delim: "\u00ff").Substring(startIndex: 1); } - else if (ident.Equals("FamilyName", StringComparison.Ordinal)) + else if (ident.Equals(value: "FamilyName", StringComparison.Ordinal)) { - _familyName = tok.NextToken("\u00ff").Substring(1); + _familyName = tok.NextToken(delim: "\u00ff").Substring(startIndex: 1); } - else if (ident.Equals("Weight", StringComparison.Ordinal)) + else if (ident.Equals(value: "Weight", StringComparison.Ordinal)) { - _weight = tok.NextToken("\u00ff").Substring(1); + _weight = tok.NextToken(delim: "\u00ff").Substring(startIndex: 1); } - else if (ident.Equals("ItalicAngle", StringComparison.Ordinal)) + else if (ident.Equals(value: "ItalicAngle", StringComparison.Ordinal)) { _italicAngle = float.Parse(tok.NextToken(), NumberFormatInfo.InvariantInfo); } - else if (ident.Equals("IsFixedPitch", StringComparison.Ordinal)) + else if (ident.Equals(value: "IsFixedPitch", StringComparison.Ordinal)) { - _isFixedPitch = tok.NextToken().Equals("true", StringComparison.Ordinal); + _isFixedPitch = tok.NextToken().Equals(value: "true", StringComparison.Ordinal); } - else if (ident.Equals("CharacterSet", StringComparison.Ordinal)) + else if (ident.Equals(value: "CharacterSet", StringComparison.Ordinal)) { - _characterSet = tok.NextToken("\u00ff").Substring(1); + _characterSet = tok.NextToken(delim: "\u00ff").Substring(startIndex: 1); } - else if (ident.Equals("FontBBox", StringComparison.Ordinal)) + else if (ident.Equals(value: "FontBBox", StringComparison.Ordinal)) { _llx = (int)float.Parse(tok.NextToken(), NumberFormatInfo.InvariantInfo); _lly = (int)float.Parse(tok.NextToken(), NumberFormatInfo.InvariantInfo); _urx = (int)float.Parse(tok.NextToken(), NumberFormatInfo.InvariantInfo); _ury = (int)float.Parse(tok.NextToken(), NumberFormatInfo.InvariantInfo); } - else if (ident.Equals("UnderlinePosition", StringComparison.Ordinal)) + else if (ident.Equals(value: "UnderlinePosition", StringComparison.Ordinal)) { _underlinePosition = (int)float.Parse(tok.NextToken(), NumberFormatInfo.InvariantInfo); } - else if (ident.Equals("UnderlineThickness", StringComparison.Ordinal)) + else if (ident.Equals(value: "UnderlineThickness", StringComparison.Ordinal)) { _underlineThickness = (int)float.Parse(tok.NextToken(), NumberFormatInfo.InvariantInfo); } - else if (ident.Equals("EncodingScheme", StringComparison.Ordinal)) + else if (ident.Equals(value: "EncodingScheme", StringComparison.Ordinal)) { - _encodingScheme = tok.NextToken("\u00ff").Substring(1); + _encodingScheme = tok.NextToken(delim: "\u00ff").Substring(startIndex: 1); } - else if (ident.Equals("CapHeight", StringComparison.Ordinal)) + else if (ident.Equals(value: "CapHeight", StringComparison.Ordinal)) { _capHeight = (int)float.Parse(tok.NextToken(), NumberFormatInfo.InvariantInfo); } - else if (ident.Equals("XHeight", StringComparison.Ordinal)) + else if (ident.Equals(value: "XHeight", StringComparison.Ordinal)) { _xHeight = (int)float.Parse(tok.NextToken(), NumberFormatInfo.InvariantInfo); } - else if (ident.Equals("Ascender", StringComparison.Ordinal)) + else if (ident.Equals(value: "Ascender", StringComparison.Ordinal)) { _ascender = (int)float.Parse(tok.NextToken(), NumberFormatInfo.InvariantInfo); } - else if (ident.Equals("Descender", StringComparison.Ordinal)) + else if (ident.Equals(value: "Descender", StringComparison.Ordinal)) { _descender = (int)float.Parse(tok.NextToken(), NumberFormatInfo.InvariantInfo); } - else if (ident.Equals("StdHW", StringComparison.Ordinal)) + else if (ident.Equals(value: "StdHW", StringComparison.Ordinal)) { _stdHw = (int)float.Parse(tok.NextToken(), NumberFormatInfo.InvariantInfo); } - else if (ident.Equals("StdVW", StringComparison.Ordinal)) + else if (ident.Equals(value: "StdVW", StringComparison.Ordinal)) { _stdVw = (int)float.Parse(tok.NextToken(), NumberFormatInfo.InvariantInfo); } - else if (ident.Equals("StartCharMetrics", StringComparison.Ordinal)) + else if (ident.Equals(value: "StartCharMetrics", StringComparison.Ordinal)) { isMetrics = true; @@ -752,7 +751,7 @@ public void Process(RandomAccessFileOrArray rf) var ident = tok.NextToken(); - if (ident.Equals("EndCharMetrics", StringComparison.Ordinal)) + if (ident.Equals(value: "EndCharMetrics", StringComparison.Ordinal)) { isMetrics = false; @@ -764,7 +763,7 @@ public void Process(RandomAccessFileOrArray rf) var n = ""; int[] b = null; - tok = new StringTokenizer(line, ";"); + tok = new StringTokenizer(line, delim: ";"); while (tok.HasMoreTokens()) { @@ -777,19 +776,19 @@ public void Process(RandomAccessFileOrArray rf) ident = tokc.NextToken(); - if (ident.Equals("C", StringComparison.Ordinal)) + if (ident.Equals(value: "C", StringComparison.Ordinal)) { c = int.Parse(tokc.NextToken(), CultureInfo.InvariantCulture); } - else if (ident.Equals("WX", StringComparison.Ordinal)) + else if (ident.Equals(value: "WX", StringComparison.Ordinal)) { wx = (int)float.Parse(tokc.NextToken(), NumberFormatInfo.InvariantInfo); } - else if (ident.Equals("N", StringComparison.Ordinal)) + else if (ident.Equals(value: "N", StringComparison.Ordinal)) { n = tokc.NextToken(); } - else if (ident.Equals("B", StringComparison.Ordinal)) + else if (ident.Equals(value: "B", StringComparison.Ordinal)) { b = new[] { @@ -819,13 +818,13 @@ public void Process(RandomAccessFileOrArray rf) throw new DocumentException("Missing EndCharMetrics in " + _fileName); } - if (!_charMetrics.ContainsKey("nonbreakingspace")) + if (!_charMetrics.ContainsKey(key: "nonbreakingspace")) { - var space = _charMetrics["space"]; + var space = _charMetrics[key: "space"]; if (space != null) { - _charMetrics["nonbreakingspace"] = space; + _charMetrics[key: "nonbreakingspace"] = space; } } @@ -840,12 +839,12 @@ public void Process(RandomAccessFileOrArray rf) var ident = tok.NextToken(); - if (ident.Equals("EndFontMetrics", StringComparison.Ordinal)) + if (ident.Equals(value: "EndFontMetrics", StringComparison.Ordinal)) { return; } - if (ident.Equals("StartKernPairs", StringComparison.Ordinal)) + if (ident.Equals(value: "StartKernPairs", StringComparison.Ordinal)) { isMetrics = true; @@ -869,7 +868,7 @@ public void Process(RandomAccessFileOrArray rf) var ident = tok.NextToken(); - if (ident.Equals("KPX", StringComparison.Ordinal)) + if (ident.Equals(value: "KPX", StringComparison.Ordinal)) { var first = tok.NextToken(); var second = tok.NextToken(); @@ -887,13 +886,13 @@ public void Process(RandomAccessFileOrArray rf) { var n = relates.Length; var relates2 = new object[n + 2]; - Array.Copy(relates, 0, relates2, 0, n); + Array.Copy(relates, sourceIndex: 0, relates2, destinationIndex: 0, n); relates2[n] = second; relates2[n + 1] = width; _kernPairs[first] = relates2; } } - else if (ident.Equals("EndKernPairs", StringComparison.Ordinal)) + else if (ident.Equals(value: "EndKernPairs", StringComparison.Ordinal)) { isMetrics = false; @@ -958,7 +957,7 @@ public override bool SetKerning(int char1, int char2, int kern) var size = obj.Length; var obj2 = new object[size + 2]; - Array.Copy(obj, 0, obj2, 0, size); + Array.Copy(obj, sourceIndex: 0, obj2, destinationIndex: 0, size); obj2[size] = second; obj2[size + 1] = kern; _kernPairs[first] = obj2; @@ -985,7 +984,7 @@ internal override int GetRawWidth(int c, string name) } else { - if (name.Equals(".notdef", StringComparison.Ordinal)) + if (name.Equals(value: ".notdef", StringComparison.Ordinal)) { return 0; } @@ -1061,7 +1060,7 @@ protected override int[] GetRawCharBBox(int c, string name) } else { - if (name.Equals(".notdef", StringComparison.Ordinal)) + if (name.Equals(value: ".notdef", StringComparison.Ordinal)) { return null; } @@ -1155,7 +1154,7 @@ private PdfDictionary getFontBaseType(PdfIndirectReference fontDescriptor, { if (shortTag[k] == 0) { - wd.Add(new PdfNumber(0)); + wd.Add(new PdfNumber(value: 0)); } else { diff --git a/src/iTextSharp.LGPLv2.Core/iTextSharp/text/pdf/Type3Font.cs b/src/iTextSharp.LGPLv2.Core/iTextSharp/text/pdf/Type3Font.cs index 811cadd..45d3166 100644 --- a/src/iTextSharp.LGPLv2.Core/iTextSharp/text/pdf/Type3Font.cs +++ b/src/iTextSharp.LGPLv2.Core/iTextSharp/text/pdf/Type3Font.cs @@ -7,7 +7,7 @@ namespace iTextSharp.text.pdf; /// public class Type3Font : BaseFont { - private readonly INullValueDictionary _char2Glyph = new NullValueDictionary(); + private readonly NullValueDictionary _char2Glyph = new(); private readonly bool _colorized; private readonly PageResources _pageResources = new(); private readonly bool[] _usedSlot; @@ -57,17 +57,23 @@ public Type3Font(PdfWriter writer, bool colorized) _usedSlot = new bool[256]; } - public override string[][] AllNameEntries + public override string[][] AllNameEntries => new[] { - get { return new[] { new[] { "4", "", "", "", "" } }; } - } + new[] + { + "4", "", "", "", "" + } + }; public override string[][] FamilyFontName => FullFontName; - public override string[][] FullFontName + public override string[][] FullFontName => new[] { - get { return new[] { new[] { "", "", "", "" } }; } - } + new[] + { + "", "", "", "" + } + }; public override string PostscriptFontName { @@ -108,12 +114,14 @@ public PdfContentByte DefineGlyph(char c, float wx, float llx, float lly, float _usedSlot[c] = true; var glyph = _char2Glyph[c]; + if (glyph != null) { return glyph; } _widths3[c] = (int)wx; + if (!_colorized) { if (float.IsNaN(_llx)) @@ -134,6 +142,7 @@ public PdfContentByte DefineGlyph(char c, float wx, float llx, float lly, float glyph = new Type3Glyph(_writer, _pageResources, wx, llx, lly, urx, ury, _colorized); _char2Glyph[c] = glyph; + return glyph; } @@ -169,6 +178,7 @@ public override int GetWidth(string text) var c = text.ToCharArray(); var total = 0; + for (var k = 0; k < c.Length; ++k) { total += GetWidth(c[k]); @@ -188,9 +198,11 @@ internal override byte[] ConvertToBytes(string text) var cc = text.ToCharArray(); var b = new byte[cc.Length]; var p = 0; + for (var k = 0; k < cc.Length; ++k) { var c = cc[k]; + if (CharExists(c)) { b[p++] = (byte)c; @@ -203,7 +215,8 @@ internal override byte[] ConvertToBytes(string text) } var b2 = new byte[p]; - Array.Copy(b, 0, b2, 0, p); + Array.Copy(b, sourceIndex: 0, b2, destinationIndex: 0, p); + return b2; } @@ -211,7 +224,10 @@ internal override byte[] ConvertToBytes(int char1) { if (CharExists(char1)) { - return new[] { (byte)char1 }; + return new[] + { + (byte)char1 + }; } return Array.Empty(); @@ -223,11 +239,12 @@ internal override void WriteFont(PdfWriter writer, PdfIndirectReference piRef, o { if (_writer != writer) { - throw new ArgumentException("Type3 font used with the wrong PdfWriter"); + throw new ArgumentException(message: "Type3 font used with the wrong PdfWriter"); } // Get first & lastchar ... var firstChar = 0; + while (firstChar < _usedSlot.Length && !_usedSlot[firstChar]) { firstChar++; @@ -235,10 +252,11 @@ internal override void WriteFont(PdfWriter writer, PdfIndirectReference piRef, o if (firstChar == _usedSlot.Length) { - throw new DocumentException("No glyphs defined for Type3 font"); + throw new DocumentException(message: "No glyphs defined for Type3 font"); } var lastChar = _usedSlot.Length - 1; + while (lastChar >= firstChar && !_usedSlot[lastChar]) { lastChar--; @@ -248,6 +266,7 @@ internal override void WriteFont(PdfWriter writer, PdfIndirectReference piRef, o var invOrd = new int[lastChar - firstChar + 1]; int invOrdIndx = 0, w = 0; + for (var u = firstChar; u <= lastChar; u++, w++) { if (_usedSlot[u]) @@ -260,9 +279,11 @@ internal override void WriteFont(PdfWriter writer, PdfIndirectReference piRef, o var diffs = new PdfArray(); var charprocs = new PdfDictionary(); var last = -1; + for (var k = 0; k < invOrdIndx; ++k) { var c = invOrd[k]; + if (c > last) { last = c; @@ -272,6 +293,7 @@ internal override void WriteFont(PdfWriter writer, PdfIndirectReference piRef, o ++last; var c2 = invOrd[k]; var s = GlyphList.UnicodeToName(c2); + if (s == null) { s = "a" + c2; @@ -280,7 +302,7 @@ internal override void WriteFont(PdfWriter writer, PdfIndirectReference piRef, o var n = new PdfName(s); diffs.Add(n); var glyph = _char2Glyph[(char)c2]; - var stream = new PdfStream(glyph.ToPdf(null)); + var stream = new PdfStream(glyph.ToPdf(writer: null)); stream.FlateCompress(compressionLevel); var refp = writer.AddToBody(stream).IndirectReference; charprocs.Put(n, refp); @@ -288,16 +310,21 @@ internal override void WriteFont(PdfWriter writer, PdfIndirectReference piRef, o var font = new PdfDictionary(PdfName.Font); font.Put(PdfName.Subtype, PdfName.Type3); + if (_colorized) { - font.Put(PdfName.Fontbbox, new PdfRectangle(0, 0, 0, 0)); + font.Put(PdfName.Fontbbox, new PdfRectangle(llx: 0, lly: 0, urx: 0, ury: 0)); } else { font.Put(PdfName.Fontbbox, new PdfRectangle(_llx, _lly, _urx, _ury)); } - font.Put(PdfName.Fontmatrix, new PdfArray(new[] { 0.001f, 0, 0, 0.001f, 0, 0 })); + font.Put(PdfName.Fontmatrix, new PdfArray(new[] + { + 0.001f, 0, 0, 0.001f, 0, 0 + })); + font.Put(PdfName.Charprocs, writer.AddToBody(charprocs).IndirectReference); var localEncoding = new PdfDictionary(); localEncoding.Put(PdfName.Differences, diffs); @@ -305,6 +332,7 @@ internal override void WriteFont(PdfWriter writer, PdfIndirectReference piRef, o font.Put(PdfName.Firstchar, new PdfNumber(firstChar)); font.Put(PdfName.Lastchar, new PdfNumber(lastChar)); font.Put(PdfName.Widths, writer.AddToBody(new PdfArray(localWidths)).IndirectReference); + if (_pageResources.HasResources()) { font.Put(PdfName.Resources, writer.AddToBody(_pageResources.Resources).IndirectReference); diff --git a/src/iTextSharp.LGPLv2.Core/iTextSharp/text/pdf/events/IndexEvents.cs b/src/iTextSharp.LGPLv2.Core/iTextSharp/text/pdf/events/IndexEvents.cs index 41234c1..ddbc3a6 100644 --- a/src/iTextSharp.LGPLv2.Core/iTextSharp/text/pdf/events/IndexEvents.cs +++ b/src/iTextSharp.LGPLv2.Core/iTextSharp/text/pdf/events/IndexEvents.cs @@ -17,7 +17,7 @@ public class IndexEvents : PdfPageEventHelper /// /// keeps the indextag with the pagenumber /// - private readonly INullValueDictionary _indextag = new NullValueDictionary(); + private readonly NullValueDictionary _indextag = new(); /// /// Comparator for sorting the index @@ -40,8 +40,7 @@ public class IndexEvents : PdfPageEventHelper /// The second level. /// The third level. /// Returns the Chunk. - public Chunk Create(string text, string in1, string in2, - string in3) + public Chunk Create(string text, string in1, string in2, string in3) { var chunk = new Chunk(text); var tag = $"idx_{_indexcounter++}"; @@ -49,6 +48,7 @@ public Chunk Create(string text, string in1, string in2, chunk.SetLocalDestination(tag); var entry = new Entry(in1, in2, in3, tag, this); _indexentry.Add(entry); + return chunk; } @@ -58,7 +58,7 @@ public Chunk Create(string text, string in1, string in2, /// The text for the Chunk. /// The first level. /// Returns the Chunk. - public Chunk Create(string text, string in1) => Create(text, in1, "", ""); + public Chunk Create(string text, string in1) => Create(text, in1, in2: "", in3: ""); /// /// Create an index entry. @@ -67,7 +67,7 @@ public Chunk Create(string text, string in1, string in2, /// The first level. /// The second level. /// Returns the Chunk. - public Chunk Create(string text, string in1, string in2) => Create(text, in1, in2, ""); + public Chunk Create(string text, string in1, string in2) => Create(text, in1, in2, in3: ""); /// /// Create an index entry. @@ -76,8 +76,7 @@ public Chunk Create(string text, string in1, string in2, /// The first level. /// The second level. /// The third level. - public void Create(Chunk text, string in1, string in2, - string in3) + public void Create(Chunk text, string in1, string in2, string in3) { if (text == null) { @@ -96,10 +95,7 @@ public void Create(Chunk text, string in1, string in2, /// /// The text. /// The first level. - public void Create(Chunk text, string in1) - { - Create(text, in1, "", ""); - } + public void Create(Chunk text, string in1) => Create(text, in1, in2: "", in3: ""); /// /// Create an index entry. @@ -107,10 +103,7 @@ public void Create(Chunk text, string in1) /// The text. /// The first level. /// The second level. - public void Create(Chunk text, string in1, string in2) - { - Create(text, in1, in2, ""); - } + public void Create(Chunk text, string in1, string in2) => Create(text, in1, in2, in3: ""); /// /// Returns the sorted list with the entries and the collected page numbers. @@ -126,6 +119,7 @@ public IList GetSortedEntries() var key = e.GetKey(); var master = grouped[key]; + if (master != null) { master.AddPageNumberAndTag(e.GetPageNumber(), e.GetTag()); @@ -139,7 +133,8 @@ public IList GetSortedEntries() // copy to a list and sort it var sorted = new List(grouped.Values); - sorted.Sort(0, sorted.Count, _comparator); + sorted.Sort(index: 0, sorted.Count, _comparator); + return sorted; } @@ -149,8 +144,7 @@ public IList GetSortedEntries() /// com.lowagie.text.pdf.PdfWriter, com.lowagie.text.Document, /// com.lowagie.text.Rectangle, java.lang.String) /// - public override void OnGenericTag(PdfWriter writer, Document document, - Rectangle rect, string text) + public override void OnGenericTag(PdfWriter writer, Document document, Rectangle rect, string text) { if (writer == null) { @@ -164,10 +158,7 @@ public override void OnGenericTag(PdfWriter writer, Document document, /// Set the comparator. /// /// The comparator to set. - public void SetComparator(IComparer aComparator) - { - _comparator = aComparator; - } + public void SetComparator(IComparer aComparator) => _comparator = aComparator; /// /// -------------------------------------------------------------------- @@ -219,8 +210,7 @@ public class Entry /// The third level. /// The tag. /// - public Entry(string aIn1, string aIn2, string aIn3, - string aTag, IndexEvents parent) + public Entry(string aIn1, string aIn2, string aIn3, string aTag, IndexEvents parent) { _in1 = aIn1; _in2 = aIn2; @@ -273,6 +263,7 @@ public int GetPageNumber() var rt = -1; object i = _parent._indextag[_tag]; rt = (int)i; + return rt; } @@ -301,12 +292,13 @@ public int GetPageNumber() public override string ToString() { var buf = new StringBuilder(); - buf.Append(_in1).Append(' '); - buf.Append(_in2).Append(' '); - buf.Append(_in3).Append(' '); + buf.Append(_in1).Append(value: ' '); + buf.Append(_in2).Append(value: ' '); + buf.Append(_in3).Append(value: ' '); + for (var i = 0; i < _pagenumbers.Count; i++) { - buf.Append(_pagenumbers[i]).Append(' '); + buf.Append(_pagenumbers[i]).Append(value: ' '); } return buf.ToString(); @@ -321,6 +313,7 @@ public int Compare(Entry arg0, Entry arg1) var en2 = arg1; var rt = 0; + if (en1.GetIn1() != null && en2.GetIn1() != null) { if ((rt = Util.CompareToIgnoreCase(en1.GetIn1(), en2.GetIn1())) == 0) diff --git a/src/iTextSharp.LGPLv2.Core/iTextSharp/text/rtf/parser/RtfImportMappings.cs b/src/iTextSharp.LGPLv2.Core/iTextSharp/text/rtf/parser/RtfImportMappings.cs index 123fa4b..5aec4ad 100644 --- a/src/iTextSharp.LGPLv2.Core/iTextSharp/text/rtf/parser/RtfImportMappings.cs +++ b/src/iTextSharp.LGPLv2.Core/iTextSharp/text/rtf/parser/RtfImportMappings.cs @@ -18,22 +18,22 @@ public class RtfImportMappings /// /// The colorNr to Color mappings. /// - private readonly INullValueDictionary _colorMappings; + private readonly NullValueDictionary _colorMappings; /// /// The fontNr to fontName mappings. /// - private readonly INullValueDictionary _fontMappings; + private readonly NullValueDictionary _fontMappings; /// /// The listNr to List mappings. /// - private readonly INullValueDictionary _listMappings; + private readonly NullValueDictionary _listMappings; /// /// The sytlesheetListNr to Stylesheet mappings. /// - private readonly INullValueDictionary _stylesheetListMappings; + private readonly NullValueDictionary _stylesheetListMappings; /// /// Constructs a new RtfImportMappings initialising the mappings. @@ -51,30 +51,21 @@ public RtfImportMappings() /// /// The color number. /// The Color. - public void AddColor(string colorNr, BaseColor color) - { - _colorMappings[colorNr] = color; - } + public void AddColor(string colorNr, BaseColor color) => _colorMappings[colorNr] = color; /// /// Add a font to the list of mappings. /// /// The font number. /// The font name. - public void AddFont(string fontNr, string fontName) - { - _fontMappings[fontNr] = fontName; - } + public void AddFont(string fontNr, string fontName) => _fontMappings[fontNr] = fontName; /// /// Add a List to the list of mappings. /// /// The List number. /// The List. - public void AddList(string listNr, string list) - { - _listMappings[listNr] = list; - } + public void AddList(string listNr, string list) => _listMappings[listNr] = list; /// /// Add a Stylesheet List to the list of mappings. @@ -82,9 +73,7 @@ public void AddList(string listNr, string list) /// The Stylesheet List number. /// The StylesheetList. public void AddStylesheetList(string stylesheetListNr, string list) - { - _stylesheetListMappings[stylesheetListNr] = list; - } + => _stylesheetListMappings[stylesheetListNr] = list; /// /// Gets the list of color mappings. String to Color. diff --git a/src/iTextSharp.LGPLv2.Core/iTextSharp/text/rtf/parser/destinations/RtfDestinationColorTable.cs b/src/iTextSharp.LGPLv2.Core/iTextSharp/text/rtf/parser/destinations/RtfDestinationColorTable.cs index 8bd8102..9ddb652 100644 --- a/src/iTextSharp.LGPLv2.Core/iTextSharp/text/rtf/parser/destinations/RtfDestinationColorTable.cs +++ b/src/iTextSharp.LGPLv2.Core/iTextSharp/text/rtf/parser/destinations/RtfDestinationColorTable.cs @@ -19,7 +19,7 @@ public class RtfDestinationColorTable : RtfDestination /// /// Color map object for conversions /// - private INullValueDictionary _colorMap; + private NullValueDictionary _colorMap; /// /// The number of the current color being parsed. @@ -79,7 +79,7 @@ public class RtfDestinationColorTable : RtfDestination /// /// Constructor. /// - public RtfDestinationColorTable() : base(null) + public RtfDestinationColorTable() : base(parser: null) { _colorMap = new NullValueDictionary(); _colorNr = 0; @@ -127,6 +127,7 @@ public override bool HandleCharacter(int ch) public override bool HandleCloseGroup() { processColor(); + return true; } @@ -137,27 +138,27 @@ public override bool HandleControlWord(RtfCtrlWordData ctrlWordData) throw new ArgumentNullException(nameof(ctrlWordData)); } - if (ctrlWordData.CtrlWord.Equals("blue", StringComparison.Ordinal)) + if (ctrlWordData.CtrlWord.Equals(value: "blue", StringComparison.Ordinal)) { setBlue(ctrlWordData.IntValue()); } - if (ctrlWordData.CtrlWord.Equals("red", StringComparison.Ordinal)) + if (ctrlWordData.CtrlWord.Equals(value: "red", StringComparison.Ordinal)) { setRed(ctrlWordData.IntValue()); } - if (ctrlWordData.CtrlWord.Equals("green", StringComparison.Ordinal)) + if (ctrlWordData.CtrlWord.Equals(value: "green", StringComparison.Ordinal)) { setGreen(ctrlWordData.IntValue()); } - if (ctrlWordData.CtrlWord.Equals("cshade", StringComparison.Ordinal)) + if (ctrlWordData.CtrlWord.Equals(value: "cshade", StringComparison.Ordinal)) { setShade(ctrlWordData.IntValue()); } - if (ctrlWordData.CtrlWord.Equals("ctint", StringComparison.Ordinal)) + if (ctrlWordData.CtrlWord.Equals(value: "ctint", StringComparison.Ordinal)) { setTint(ctrlWordData.IntValue()); } @@ -209,6 +210,7 @@ public override void SetToDefaults() _ctint = 255; _cshade = 255; _themeColor = RtfColorThemes.THEME_UNDEFINED; + // do not reset colorNr } @@ -224,7 +226,7 @@ private void processColor() if (RtfParser.IsImport()) { _importHeader.ImportColor(_colorNr.ToString(CultureInfo.InvariantCulture), - new BaseColor(_red, _green, _blue)); + new BaseColor(_red, _green, _blue)); } if (RtfParser.IsConvert()) @@ -283,6 +285,7 @@ private void setShade(int value) if (value >= 0 && value <= 255) { _cshade = value; + if (value >= 0 && value < 255) { _ctint = 255; @@ -317,6 +320,7 @@ private void setTint(int value) if (value >= 0 && value <= 255) { _ctint = value; + if (value >= 0 && value < 255) { _cshade = 255; diff --git a/src/iTextSharp.LGPLv2.Core/iTextSharp/text/rtf/parser/destinations/RtfDestinationFontTable.cs b/src/iTextSharp.LGPLv2.Core/iTextSharp/text/rtf/parser/destinations/RtfDestinationFontTable.cs index 9fa0c4c..ca9c002 100644 --- a/src/iTextSharp.LGPLv2.Core/iTextSharp/text/rtf/parser/destinations/RtfDestinationFontTable.cs +++ b/src/iTextSharp.LGPLv2.Core/iTextSharp/text/rtf/parser/destinations/RtfDestinationFontTable.cs @@ -97,7 +97,7 @@ public sealed class RtfDestinationFontTable : RtfDestination /// /// Convert font mapping to FontFactory font objects. /// - private INullValueDictionary _fontMap; + private NullValueDictionary _fontMap; /// /// The \*\fname @@ -148,7 +148,7 @@ public sealed class RtfDestinationFontTable : RtfDestination /// /// Constructor /// - public RtfDestinationFontTable() : base(null) + public RtfDestinationFontTable() : base(parser: null) { } @@ -156,10 +156,7 @@ public RtfDestinationFontTable() : base(null) /// Constructs a new RtfFontTableParser. /// @since 2.0.8 /// - public RtfDestinationFontTable(RtfParser parser) : base(parser) - { - init(true); - } + public RtfDestinationFontTable(RtfParser parser) : base(parser) => init(importFonts: true); /// /// (non-Javadoc) @@ -187,12 +184,15 @@ public override bool HandleCharacter(int ch) { case SettingNormal: _fontName += (char)ch; + break; case SettingAlternate: _falt += (char)ch; + break; case SettingPanose: _panose += (char)ch; + break; case SettingFontEmbed: break; @@ -218,6 +218,7 @@ public override bool HandleCloseGroup() } _state = SettingNormal; + return true; } @@ -230,134 +231,135 @@ public override bool HandleCloseGroup() public override bool HandleControlWord(RtfCtrlWordData ctrlWordData) { var result = true; + // just let fonttbl fall through and set last ctrl word object. - if (ctrlWordData.CtrlWord.Equals("f", StringComparison.Ordinal)) + if (ctrlWordData.CtrlWord.Equals(value: "f", StringComparison.Ordinal)) { SetFontNumber(ctrlWordData.Param); result = true; } - if (ctrlWordData.CtrlWord.Equals("fcharset", StringComparison.Ordinal)) + if (ctrlWordData.CtrlWord.Equals(value: "fcharset", StringComparison.Ordinal)) { SetCharset(ctrlWordData.Param); result = true; } // font families - if (ctrlWordData.CtrlWord.Equals("fnil", StringComparison.Ordinal)) + if (ctrlWordData.CtrlWord.Equals(value: "fnil", StringComparison.Ordinal)) { - SetFontFamily("roman"); + SetFontFamily(fontFamily: "roman"); result = true; } - if (ctrlWordData.CtrlWord.Equals("froman", StringComparison.Ordinal)) + if (ctrlWordData.CtrlWord.Equals(value: "froman", StringComparison.Ordinal)) { - SetFontFamily("roman"); + SetFontFamily(fontFamily: "roman"); result = true; } - if (ctrlWordData.CtrlWord.Equals("fswiss", StringComparison.Ordinal)) + if (ctrlWordData.CtrlWord.Equals(value: "fswiss", StringComparison.Ordinal)) { - SetFontFamily("swiss"); + SetFontFamily(fontFamily: "swiss"); result = true; } - if (ctrlWordData.CtrlWord.Equals("fmodern", StringComparison.Ordinal)) + if (ctrlWordData.CtrlWord.Equals(value: "fmodern", StringComparison.Ordinal)) { - SetFontFamily("modern"); + SetFontFamily(fontFamily: "modern"); result = true; } - if (ctrlWordData.CtrlWord.Equals("fscript", StringComparison.Ordinal)) + if (ctrlWordData.CtrlWord.Equals(value: "fscript", StringComparison.Ordinal)) { - SetFontFamily("script"); + SetFontFamily(fontFamily: "script"); result = true; } - if (ctrlWordData.CtrlWord.Equals("fdecor", StringComparison.Ordinal)) + if (ctrlWordData.CtrlWord.Equals(value: "fdecor", StringComparison.Ordinal)) { - SetFontFamily("decor"); + SetFontFamily(fontFamily: "decor"); result = true; } - if (ctrlWordData.CtrlWord.Equals("ftech", StringComparison.Ordinal)) + if (ctrlWordData.CtrlWord.Equals(value: "ftech", StringComparison.Ordinal)) { - SetFontFamily("tech"); + SetFontFamily(fontFamily: "tech"); result = true; } - if (ctrlWordData.CtrlWord.Equals("fbidi", StringComparison.Ordinal)) + if (ctrlWordData.CtrlWord.Equals(value: "fbidi", StringComparison.Ordinal)) { - SetFontFamily("bidi"); + SetFontFamily(fontFamily: "bidi"); result = true; } // pitch - if (ctrlWordData.CtrlWord.Equals("fprq", StringComparison.Ordinal)) + if (ctrlWordData.CtrlWord.Equals(value: "fprq", StringComparison.Ordinal)) { SetPitch(ctrlWordData.Param); result = true; } // bias - if (ctrlWordData.CtrlWord.Equals("fbias", StringComparison.Ordinal)) + if (ctrlWordData.CtrlWord.Equals(value: "fbias", StringComparison.Ordinal)) { SetBias(ctrlWordData.Param); result = true; } // theme font information - if (ctrlWordData.CtrlWord.Equals("flomajor", StringComparison.Ordinal)) + if (ctrlWordData.CtrlWord.Equals(value: "flomajor", StringComparison.Ordinal)) { - SetThemeFont("flomajor"); + SetThemeFont(themeFont: "flomajor"); result = true; } - if (ctrlWordData.CtrlWord.Equals("fhimajor", StringComparison.Ordinal)) + if (ctrlWordData.CtrlWord.Equals(value: "fhimajor", StringComparison.Ordinal)) { - SetThemeFont("fhimajor"); + SetThemeFont(themeFont: "fhimajor"); result = true; } - if (ctrlWordData.CtrlWord.Equals("fdbmajor", StringComparison.Ordinal)) + if (ctrlWordData.CtrlWord.Equals(value: "fdbmajor", StringComparison.Ordinal)) { - SetThemeFont("fdbmajor"); + SetThemeFont(themeFont: "fdbmajor"); result = true; } - if (ctrlWordData.CtrlWord.Equals("fbimajor", StringComparison.Ordinal)) + if (ctrlWordData.CtrlWord.Equals(value: "fbimajor", StringComparison.Ordinal)) { - SetThemeFont("fbimajor"); + SetThemeFont(themeFont: "fbimajor"); result = true; } - if (ctrlWordData.CtrlWord.Equals("flominor", StringComparison.Ordinal)) + if (ctrlWordData.CtrlWord.Equals(value: "flominor", StringComparison.Ordinal)) { - SetThemeFont("flominor"); + SetThemeFont(themeFont: "flominor"); result = true; } - if (ctrlWordData.CtrlWord.Equals("fhiminor", StringComparison.Ordinal)) + if (ctrlWordData.CtrlWord.Equals(value: "fhiminor", StringComparison.Ordinal)) { - SetThemeFont("fhiminor"); + SetThemeFont(themeFont: "fhiminor"); result = true; } - if (ctrlWordData.CtrlWord.Equals("fdbminor", StringComparison.Ordinal)) + if (ctrlWordData.CtrlWord.Equals(value: "fdbminor", StringComparison.Ordinal)) { - SetThemeFont("fdbminor"); + SetThemeFont(themeFont: "fdbminor"); result = true; } - if (ctrlWordData.CtrlWord.Equals("fbiminor", StringComparison.Ordinal)) + if (ctrlWordData.CtrlWord.Equals(value: "fbiminor", StringComparison.Ordinal)) { - SetThemeFont("fbiminor"); + SetThemeFont(themeFont: "fbiminor"); result = true; } // panose - if (ctrlWordData.CtrlWord.Equals("panose", StringComparison.Ordinal)) + if (ctrlWordData.CtrlWord.Equals(value: "panose", StringComparison.Ordinal)) { _state = SettingPanose; result = true; @@ -365,54 +367,55 @@ public override bool HandleControlWord(RtfCtrlWordData ctrlWordData) // \*\fname // #PCDATA - if (ctrlWordData.CtrlWord.Equals("fname", StringComparison.Ordinal)) + if (ctrlWordData.CtrlWord.Equals(value: "fname", StringComparison.Ordinal)) { _state = SettingFontname; result = true; } // \*\falt - if (ctrlWordData.CtrlWord.Equals("falt", StringComparison.Ordinal)) + if (ctrlWordData.CtrlWord.Equals(value: "falt", StringComparison.Ordinal)) { _state = SettingAlternate; result = true; } // \*\fontemb - if (ctrlWordData.CtrlWord.Equals("fontemb", StringComparison.Ordinal)) + if (ctrlWordData.CtrlWord.Equals(value: "fontemb", StringComparison.Ordinal)) { _state = SettingFontEmbed; result = true; } // font type - if (ctrlWordData.CtrlWord.Equals("ftnil", StringComparison.Ordinal)) + if (ctrlWordData.CtrlWord.Equals(value: "ftnil", StringComparison.Ordinal)) { - SetTrueType("ftnil"); + SetTrueType(value: "ftnil"); result = true; } - if (ctrlWordData.CtrlWord.Equals("fttruetype", StringComparison.Ordinal)) + if (ctrlWordData.CtrlWord.Equals(value: "fttruetype", StringComparison.Ordinal)) { - SetTrueType("fttruetype"); + SetTrueType(value: "fttruetype"); result = true; } // \*\fontfile - if (ctrlWordData.CtrlWord.Equals("fontemb", StringComparison.Ordinal)) + if (ctrlWordData.CtrlWord.Equals(value: "fontemb", StringComparison.Ordinal)) { _state = SettingFontFile; result = true; } // codepage - if (ctrlWordData.CtrlWord.Equals("cpg", StringComparison.Ordinal)) + if (ctrlWordData.CtrlWord.Equals(value: "cpg", StringComparison.Ordinal)) { SetCodePage(ctrlWordData.Param); result = true; } LastCtrlWord = ctrlWordData; + return result; } @@ -435,10 +438,7 @@ public override bool HandleControlWord(RtfCtrlWordData ctrlWordData) /// @since 2.0.8 /// /// Bias value - public void SetBias(string value) - { - _fbias = int.Parse(value, CultureInfo.InvariantCulture); - } + public void SetBias(string value) => _fbias = int.Parse(value, CultureInfo.InvariantCulture); /// /// Set the character-set to the parsed value. @@ -465,40 +465,28 @@ public void SetCharset(string charset) /// @since 2.0.8 /// /// The code page value - public void SetCodePage(string value) - { - _cpg = value; - } + public void SetCodePage(string value) => _cpg = value; /// /// Set the alternate font name. /// @since 2.0.8 /// /// The falt font value - public void SetFontAlternate(string fontAlternate) - { - _falt = fontAlternate; - } + public void SetFontAlternate(string fontAlternate) => _falt = fontAlternate; /// /// Set the font family to the parsed value. /// @since 2.0.8 /// /// The font family. - public void SetFontFamily(string fontFamily) - { - _fontFamily = fontFamily; - } + public void SetFontFamily(string fontFamily) => _fontFamily = fontFamily; /// /// Set the font name to the parsed value. /// @since 2.0.8 /// /// The font name. - public void SetFontName(string fontName) - { - _fontName = fontName; - } + public void SetFontName(string fontName) => _fontName = fontName; /// /// Set the font number to the parsed value. @@ -506,10 +494,7 @@ public void SetFontName(string fontName) /// @since 2.0.8 /// /// The font number. - public void SetFontNumber(string fontNr) - { - _fontNr = fontNr; - } + public void SetFontNumber(string fontNr) => _fontNr = fontNr; /// /// (non-Javadoc) @@ -524,7 +509,7 @@ public override void SetParser(RtfParser parser) } RtfParser = parser; - init(true); + init(importFonts: true); } /// @@ -532,20 +517,14 @@ public override void SetParser(RtfParser parser) /// @since 2.0.8 /// /// Pitch value - public void SetPitch(string value) - { - _fprq = int.Parse(value, CultureInfo.InvariantCulture); - } + public void SetPitch(string value) => _fprq = int.Parse(value, CultureInfo.InvariantCulture); /// /// Set the font theme /// @since 2.0.8 /// /// Theme value - public void SetThemeFont(string themeFont) - { - _themeFont = themeFont; - } + public void SetThemeFont(string themeFont) => _themeFont = themeFont; /// /// (non-Javadoc) @@ -562,8 +541,10 @@ public override void SetToDefaults() _charset = ""; _fprq = 0; _panose = ""; + //this.nontaggedname = ""; _falt = ""; + //this.fontemb = ""; //this.fontType = ""; //this.fontFile = ""; @@ -579,10 +560,7 @@ public override void SetToDefaults() /// @since 2.0.8 /// /// The type - public void SetTrueType(string value) - { - _trueType = value; - } + public void SetTrueType(string value) => _trueType = value; /// /// Create a font via the FontFactory @@ -594,6 +572,7 @@ private static Font createfont(string fontName) { Font f1 = null; var pos = -1; + do { f1 = FontFactory.GetFont(fontName); @@ -603,12 +582,14 @@ private static Font createfont(string fontName) break; // found a font, exit the do/while } - pos = fontName.LastIndexOf(" ", StringComparison.Ordinal); // find the last space + pos = fontName.LastIndexOf(value: " ", StringComparison.Ordinal); // find the last space + if (pos > 0) { - fontName = fontName.Substring(0, pos); // truncate it to the last space + fontName = fontName.Substring(startIndex: 0, pos); // truncate it to the last space } - } while (pos > 0); + } + while (pos > 0); return f1; } @@ -617,10 +598,7 @@ private static Font createfont(string fontName) /// Load system fonts into the static FontFactory object /// @since 2.0.8 /// - private static void importSystemFonts() - { - FontFactory.RegisterDirectories(); - } + private static void importSystemFonts() => FontFactory.RegisterDirectories(); /// /// Initialize the object. @@ -630,12 +608,14 @@ private static void importSystemFonts() private void init(bool importFonts) { _fontMap = new NullValueDictionary(); + if (RtfParser != null) { _importHeader = RtfParser.GetImportManager(); } SetToDefaults(); + if (importFonts) { importSystemFonts(); @@ -649,6 +629,7 @@ private void init(bool importFonts) private void processFont() { _fontName = _fontName.Trim(); + if (_fontName.Length == 0) { return; @@ -659,9 +640,9 @@ private void processFont() return; } - if (_fontName.Length > 0 && _fontName.IndexOf(";", StringComparison.Ordinal) >= 0) + if (_fontName.Length > 0 && _fontName.IndexOf(value: ";", StringComparison.Ordinal) >= 0) { - _fontName = _fontName.Substring(0, _fontName.IndexOf(";", StringComparison.Ordinal)); + _fontName = _fontName.Substring(startIndex: 0, _fontName.IndexOf(value: ";", StringComparison.Ordinal)); } if (RtfParser.IsImport()) @@ -678,16 +659,17 @@ private void processFont() // } // } else { if (!_importHeader.ImportFont(_fontNr, _fontName, - int.Parse(string.IsNullOrEmpty(_charset) ? CharsetDefault : _charset, - CultureInfo.InvariantCulture))) + int.Parse(string.IsNullOrEmpty(_charset) ? CharsetDefault : _charset, + CultureInfo.InvariantCulture))) { if (_falt.Length > 0) { _importHeader.ImportFont(_fontNr, _falt, - int.Parse(string.IsNullOrEmpty(_charset) ? CharsetDefault : _charset, - CultureInfo.InvariantCulture)); + int.Parse(string.IsNullOrEmpty(_charset) ? CharsetDefault : _charset, + CultureInfo.InvariantCulture)); } } + // } } @@ -697,6 +679,7 @@ private void processFont() var fName = _fontName; // work variable for trimming name if needed. var f1 = createfont(fName); + if (f1.BaseFont == null && _falt.Length > 0) { f1 = createfont(_falt); @@ -734,6 +717,7 @@ private void processFont() } _fontMap[_fontNr] = f1; + //System.out.Println(f1.GetFamilyname()); }