/** * Constructs a PDF Collection Sort Dictionary. * @param keys the keys of the fields that will be used to sort entries */ public PdfCollectionSort(String[] keys) : base(PdfName.COLLECTIONSORT) { PdfArray array = new PdfArray(); for (int i = 0; i < keys.Length; i++) { array.Add(new PdfName(keys[i])); } Put(PdfName.S, array); }
/** * Defines the sort order of the field (ascending or descending). * @param ascending an array with every element corresponding with a name of a field. */ public void SetSortOrder(bool[] ascending) { PdfObject o = (PdfObject)Get(PdfName.S); if (o is PdfArray) { if (((PdfArray)o).Size != ascending.Length) { throw new InvalidOperationException("The number of booleans in this array doesn't correspond with the number of fields."); } PdfArray array = new PdfArray(); for (int i = 0; i < ascending.Length; i++) { array.Add(new PdfBoolean(ascending[i])); } Put(PdfName.A, array); } else { throw new InvalidOperationException("You need a single bool for this collection sort dictionary."); } }
internal ColorDetails AddSimplePatternColorspace(Color color) { int type = ExtendedColor.GetType(color); if (type == ExtendedColor.TYPE_PATTERN || type == ExtendedColor.TYPE_SHADING) throw new Exception("An uncolored tile pattern can not have another pattern or shading as color."); switch (type) { case ExtendedColor.TYPE_RGB: if (patternColorspaceRGB == null) { patternColorspaceRGB = new ColorDetails(GetColorspaceName(), body.PdfIndirectReference, null); PdfArray array = new PdfArray(PdfName.PATTERN); array.Add(PdfName.DEVICERGB); AddToBody(array, patternColorspaceRGB.IndirectReference); } return patternColorspaceRGB; case ExtendedColor.TYPE_CMYK: if (patternColorspaceCMYK == null) { patternColorspaceCMYK = new ColorDetails(GetColorspaceName(), body.PdfIndirectReference, null); PdfArray array = new PdfArray(PdfName.PATTERN); array.Add(PdfName.DEVICECMYK); AddToBody(array, patternColorspaceCMYK.IndirectReference); } return patternColorspaceCMYK; case ExtendedColor.TYPE_GRAY: if (patternColorspaceGRAY == null) { patternColorspaceGRAY = new ColorDetails(GetColorspaceName(), body.PdfIndirectReference, null); PdfArray array = new PdfArray(PdfName.PATTERN); array.Add(PdfName.DEVICEGRAY); AddToBody(array, patternColorspaceGRAY.IndirectReference); } return patternColorspaceGRAY; case ExtendedColor.TYPE_SEPARATION: { ColorDetails details = AddSimple(((SpotColor)color).PdfSpotColor); ColorDetails patternDetails = (ColorDetails)documentSpotPatterns[details]; if (patternDetails == null) { patternDetails = new ColorDetails(GetColorspaceName(), body.PdfIndirectReference, null); PdfArray array = new PdfArray(PdfName.PATTERN); array.Add(details.IndirectReference); AddToBody(array, patternDetails.IndirectReference); documentSpotPatterns[details] = patternDetails; } return patternDetails; } default: throw new Exception("Invalid color type in PdfWriter.AddSimplePatternColorspace()."); } }
/** * Signals that the <CODE>Document</CODE> was closed and that no other * <CODE>Elements</CODE> will be added. * <P> * The pages-tree is built and written to the outputstream. * A Catalog is constructed, as well as an Info-object, * the referencetable is composed and everything is written * to the outputstream embedded in a Trailer. */ public override void Close() { if (open) { if ((currentPageNumber - 1) != pageReferences.Count) throw new Exception("The page " + pageReferences.Count + " was requested but the document has only " + (currentPageNumber - 1) + " pages."); pdf.Close(); AddSharedObjectsToBody(); // add the root to the body PdfIndirectReference rootRef = root.WritePageTree(); // make the catalog-object and add it to the body PdfDictionary catalog = GetCatalog(rootRef); // [C9] if there is XMP data to add: add it if (xmpMetadata != null) { PdfStream xmp = new PdfStream(xmpMetadata); xmp.Put(PdfName.TYPE, PdfName.METADATA); xmp.Put(PdfName.SUBTYPE, PdfName.XML); if (crypto != null && !crypto.IsMetadataEncrypted()) { PdfArray ar = new PdfArray(); ar.Add(PdfName.CRYPT); xmp.Put(PdfName.FILTER, ar); } catalog.Put(PdfName.METADATA, body.Add(xmp).IndirectReference); } // [C10] make pdfx conformant if (IsPdfX()) { pdfxConformance.CompleteInfoDictionary(Info); pdfxConformance.CompleteExtraCatalog(ExtraCatalog); } // [C11] Output Intents if (extraCatalog != null) { catalog.MergeDifferent(extraCatalog); } WriteOutlines(catalog, false); // add the Catalog to the body PdfIndirectObject indirectCatalog = AddToBody(catalog, false); // add the info-object to the body PdfIndirectObject infoObj = AddToBody(Info, false); // [F1] encryption PdfIndirectReference encryption = null; PdfObject fileID = null; body.FlushObjStm(); if (crypto != null) { PdfIndirectObject encryptionObject = AddToBody(crypto.GetEncryptionDictionary(), false); encryption = encryptionObject.IndirectReference; fileID = crypto.FileID; } else fileID = PdfEncryption.CreateInfoId(PdfEncryption.CreateDocumentId()); // write the cross-reference table of the body body.WriteCrossReferenceTable(os, indirectCatalog.IndirectReference, infoObj.IndirectReference, encryption, fileID, prevxref); // make the trailer // [F2] full compression if (fullCompression) { byte[] tmp = GetISOBytes("startxref\n"); os.Write(tmp, 0, tmp.Length); tmp = GetISOBytes(body.Offset.ToString()); os.Write(tmp, 0, tmp.Length); tmp = GetISOBytes("\n%%EOF\n"); os.Write(tmp, 0, tmp.Length); } else { PdfTrailer trailer = new PdfTrailer(body.Size, body.Offset, indirectCatalog.IndirectReference, infoObj.IndirectReference, encryption, fileID, prevxref); trailer.ToPdf(this, os); } base.Close(); } }
/** * Adds an image to the document but not to the page resources. It is used with * templates and <CODE>Document.Add(Image)</CODE>. * @param image the <CODE>Image</CODE> to add * @param fixedRef the reference to used. It may be <CODE>null</CODE>, * a <CODE>PdfIndirectReference</CODE> or a <CODE>PRIndirectReference</CODE>. * @return the name of the image added * @throws PdfException on error * @throws DocumentException on error */ public PdfName AddDirectImageSimple(Image image, PdfIndirectReference fixedRef) { PdfName name; // if the images is already added, just retrieve the name if (images.ContainsKey(image.MySerialId)) { name = (PdfName) images[image.MySerialId]; } // if it's a new image, add it to the document else { if (image.IsImgTemplate()) { name = new PdfName("img" + images.Count); if (image is ImgWMF){ ImgWMF wmf = (ImgWMF)image; wmf.ReadWMF(PdfTemplate.CreateTemplate(this, 0, 0)); } } else { PdfIndirectReference dref = image.DirectReference; if (dref != null) { PdfName rname = new PdfName("img" + images.Count); images[image.MySerialId] = rname; imageDictionary.Put(rname, dref); return rname; } Image maskImage = image.ImageMask; PdfIndirectReference maskRef = null; if (maskImage != null) { PdfName mname = (PdfName)images[maskImage.MySerialId]; maskRef = GetImageReference(mname); } PdfImage i = new PdfImage(image, "img" + images.Count, maskRef); if (image is ImgJBIG2) { byte[] globals = ((ImgJBIG2) image).GlobalBytes; if (globals != null) { PdfDictionary decodeparms = new PdfDictionary(); decodeparms.Put(PdfName.JBIG2GLOBALS, GetReferenceJBIG2Globals(globals)); i.Put(PdfName.DECODEPARMS, decodeparms); } } if (image.HasICCProfile()) { PdfICCBased icc = new PdfICCBased(image.TagICC, image.CompressionLevel); PdfIndirectReference iccRef = Add(icc); PdfArray iccArray = new PdfArray(); iccArray.Add(PdfName.ICCBASED); iccArray.Add(iccRef); PdfArray colorspace = i.GetAsArray(PdfName.COLORSPACE); if (colorspace != null) { if (colorspace.Size > 1 && PdfName.INDEXED.Equals(colorspace[0])) colorspace[1] = iccArray; else i.Put(PdfName.COLORSPACE, iccArray); } else i.Put(PdfName.COLORSPACE, iccArray); } Add(i, fixedRef); name = i.Name; } images[image.MySerialId] = name; } return name; }
public static PdfFunction Type3(PdfWriter writer, float[] domain, float[] range, PdfFunction[] functions, float[] bounds, float[] encode) { PdfFunction func = new PdfFunction(writer); func.dictionary = new PdfDictionary(); func.dictionary.Put(PdfName.FUNCTIONTYPE, new PdfNumber(3)); func.dictionary.Put(PdfName.DOMAIN, new PdfArray(domain)); if (range != null) func.dictionary.Put(PdfName.RANGE, new PdfArray(range)); PdfArray array = new PdfArray(); for (int k = 0; k < functions.Length; ++k) array.Add(functions[k].Reference); func.dictionary.Put(PdfName.FUNCTIONS, array); func.dictionary.Put(PdfName.BOUNDS, new PdfArray(bounds)); func.dictionary.Put(PdfName.ENCODE, new PdfArray(encode)); return func; }
/** * Adds an object to the calculationOrder. */ public void AddCalculationOrder(PdfFormField formField) { calculationOrder.Add(formField.IndirectReference); }
/** * Sets different values in a list selection. * No appearance is generated yet; nor does the code check if multiple select is allowed. * * @param name the name of the field * @param value an array with values that need to be selected * @return true only if the field value was changed * @since 2.1.4 */ public bool SetListSelection(String name, String[] value) { Item item = GetFieldItem(name); if (item == null) return false; PdfName type = item.GetMerged(0).GetAsName(PdfName.FT); if (!PdfName.CH.Equals(type)) { return false; } String[] options = GetListOptionExport(name); PdfArray array = new PdfArray(); for (int i = 0; i < value.Length; i++) { for (int j = 0; j < options.Length; j++) { if (options[j].Equals(value[i])) { array.Add(new PdfNumber(j)); } } } 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.MarkUsed( this, Item.WRITE_VALUE | Item.WRITE_WIDGET ); return true; }
private void AdjustTabOrder(PdfArray annots, PdfIndirectReference ind, PdfNumber nn) { int v = nn.IntValue; ArrayList t = (ArrayList)tabOrder[annots] ; if (t == null) { t = new ArrayList(); int size = annots.Size - 1; for (int k = 0; k < size; ++k) { t.Add(zero); } t.Add(v); tabOrder[annots] = t; annots.Add(ind); } else { int size = t.Count - 1; for (int k = size; k >= 0; --k) { if ((int)t[k] <= v) { t.Insert(k + 1, v); annots.Add(k + 1, ind); size = -2; break; } } if (size != -2) { t.Insert(0, v); annots.Add(0, ind); } } }
public static Object[] IterateOutlines(PdfWriter writer, PdfIndirectReference parent, ArrayList kids, bool namedAsNames) { PdfIndirectReference[] refs = new PdfIndirectReference[kids.Count]; for (int k = 0; k < refs.Length; ++k) { refs[k] = writer.PdfIndirectReference; } int ptr = 0; int count = 0; foreach (Hashtable map in kids) { Object[] lower = null; ArrayList subKid = (ArrayList)map["Kids"]; if (subKid != null && subKid.Count > 0) { lower = IterateOutlines(writer, refs[ptr], subKid, namedAsNames); } PdfDictionary outline = new PdfDictionary(); ++count; if (lower != null) { outline.Put(PdfName.FIRST, (PdfIndirectReference)lower[0]); outline.Put(PdfName.LAST, (PdfIndirectReference)lower[1]); int n = (int)lower[2]; if ("false".Equals(map["Open"])) { outline.Put(PdfName.COUNT, new PdfNumber(-n)); } else { outline.Put(PdfName.COUNT, new PdfNumber(n)); count += n; } } outline.Put(PdfName.PARENT, parent); if (ptr > 0) { outline.Put(PdfName.PREV, refs[ptr - 1]); } if (ptr < refs.Length - 1) { outline.Put(PdfName.NEXT, refs[ptr + 1]); } outline.Put(PdfName.TITLE, new PdfString((String)map["Title"], PdfObject.TEXT_UNICODE)); String color = (String)map["Color"]; if (color != null) { try { PdfArray arr = new PdfArray(); StringTokenizer tk = new StringTokenizer(color); for (int k = 0; k < 3; ++k) { float f = float.Parse(tk.NextToken(), NumberFormatInfo.InvariantInfo); if (f < 0) { f = 0; } if (f > 1) { f = 1; } arr.Add(new PdfNumber(f)); } outline.Put(PdfName.C, arr); } catch {} //in case it's malformed } String style = (String)map["Style"]; if (style != null) { style = style.ToLower(CultureInfo.InvariantCulture); int bits = 0; if (style.IndexOf("italic") >= 0) { bits |= 1; } if (style.IndexOf("bold") >= 0) { bits |= 2; } if (bits != 0) { outline.Put(PdfName.F, new PdfNumber(bits)); } } CreateOutlineAction(outline, map, writer, namedAsNames); writer.AddToBody(outline, refs[ptr]); ++ptr; } return(new Object[] { refs[0], refs[refs.Length - 1], count }); }
internal static void CreateOutlineAction(PdfDictionary outline, Hashtable map, PdfWriter writer, bool namedAsNames) { try { String action = (String)map["Action"]; if ("GoTo".Equals(action)) { String p; if ((p = (String)map["Named"]) != null) { if (namedAsNames) { outline.Put(PdfName.DEST, new PdfName(p)); } else { outline.Put(PdfName.DEST, new PdfString(p, null)); } } else if ((p = (String)map["Page"]) != null) { PdfArray ar = new PdfArray(); StringTokenizer tk = new StringTokenizer(p); int n = int.Parse(tk.NextToken()); ar.Add(writer.GetPageReference(n)); if (!tk.HasMoreTokens()) { ar.Add(PdfName.XYZ); ar.Add(new float[] { 0, 10000, 0 }); } else { String fn = tk.NextToken(); if (fn.StartsWith("/")) { fn = fn.Substring(1); } ar.Add(new PdfName(fn)); for (int k = 0; k < 4 && tk.HasMoreTokens(); ++k) { fn = tk.NextToken(); if (fn.Equals("null")) { ar.Add(PdfNull.PDFNULL); } else { ar.Add(new PdfNumber(fn)); } } } outline.Put(PdfName.DEST, ar); } } else if ("GoToR".Equals(action)) { String p; PdfDictionary dic = new PdfDictionary(); if ((p = (String)map["Named"]) != null) { dic.Put(PdfName.D, new PdfString(p, null)); } else if ((p = (String)map["NamedN"]) != null) { dic.Put(PdfName.D, new PdfName(p)); } else if ((p = (String)map["Page"]) != null) { PdfArray ar = new PdfArray(); StringTokenizer tk = new StringTokenizer(p); ar.Add(new PdfNumber(tk.NextToken())); if (!tk.HasMoreTokens()) { ar.Add(PdfName.XYZ); ar.Add(new float[] { 0, 10000, 0 }); } else { String fn = tk.NextToken(); if (fn.StartsWith("/")) { fn = fn.Substring(1); } ar.Add(new PdfName(fn)); for (int k = 0; k < 4 && tk.HasMoreTokens(); ++k) { fn = tk.NextToken(); if (fn.Equals("null")) { ar.Add(PdfNull.PDFNULL); } else { ar.Add(new PdfNumber(fn)); } } } dic.Put(PdfName.D, ar); } String file = (String)map["File"]; if (dic.Size > 0 && file != null) { dic.Put(PdfName.S, PdfName.GOTOR); dic.Put(PdfName.F, new PdfString(file)); String nw = (String)map["NewWindow"]; if (nw != null) { if (nw.Equals("true")) { dic.Put(PdfName.NEWWINDOW, PdfBoolean.PDFTRUE); } else if (nw.Equals("false")) { dic.Put(PdfName.NEWWINDOW, PdfBoolean.PDFFALSE); } } outline.Put(PdfName.A, dic); } } else if ("URI".Equals(action)) { String uri = (String)map["URI"]; if (uri != null) { PdfDictionary dic = new PdfDictionary(); dic.Put(PdfName.S, PdfName.URI); dic.Put(PdfName.URI, new PdfString(uri)); outline.Put(PdfName.A, dic); } } else if ("Launch".Equals(action)) { String file = (String)map["File"]; if (file != null) { PdfDictionary dic = new PdfDictionary(); dic.Put(PdfName.S, PdfName.LAUNCH); dic.Put(PdfName.F, new PdfString(file)); outline.Put(PdfName.A, dic); } } } catch { // empty on purpose } }
/** Generates the font dictionary for this font. * @return the PdfDictionary containing the font dictionary * @param firstChar the first valid character * @param lastChar the last valid character * @param shortTag a 256 bytes long <CODE>byte</CODE> array where each unused byte is represented by 0 * @param fontDescriptor the indirect reference to a PdfDictionary containing the font descriptor or <CODE>null</CODE> */ private PdfDictionary GetFontBaseType(PdfIndirectReference fontDescriptor, int firstChar, int lastChar, byte[] shortTag) { PdfDictionary dic = new PdfDictionary(PdfName.FONT); dic.Put(PdfName.SUBTYPE, PdfName.TYPE1); dic.Put(PdfName.BASEFONT, new PdfName(FontName)); bool stdEncoding = encoding.Equals(CP1252) || encoding.Equals(MACROMAN); if (!fontSpecific || specialMap != null) { for (int k = firstChar; k <= lastChar; ++k) { if (!differences[k].Equals(notdef)) { firstChar = k; break; } } if (stdEncoding) { dic.Put(PdfName.ENCODING, encoding.Equals(CP1252) ? PdfName.WIN_ANSI_ENCODING : PdfName.MAC_ROMAN_ENCODING); } else { PdfDictionary enc = new PdfDictionary(PdfName.ENCODING); PdfArray dif = new PdfArray(); bool gap = true; for (int k = firstChar; k <= lastChar; ++k) { if (shortTag[k] != 0) { if (gap) { dif.Add(new PdfNumber(k)); gap = false; } dif.Add(new PdfName(differences[k])); } else { gap = true; } } enc.Put(PdfName.DIFFERENCES, dif); dic.Put(PdfName.ENCODING, enc); } } if (specialMap != null || forceWidthsOutput || !(builtinFont && (fontSpecific || stdEncoding))) { dic.Put(PdfName.FIRSTCHAR, new PdfNumber(firstChar)); dic.Put(PdfName.LASTCHAR, new PdfNumber(lastChar)); PdfArray wd = new PdfArray(); for (int k = firstChar; k <= lastChar; ++k) { if (shortTag[k] == 0) { wd.Add(new PdfNumber(0)); } else { wd.Add(new PdfNumber(widths[k])); } } dic.Put(PdfName.WIDTHS, wd); } if (!builtinFont && fontDescriptor != null) { dic.Put(PdfName.FONTDESCRIPTOR, fontDescriptor); } return(dic); }
public void AlterContents() { if (over == null && under == null) { return; } PdfArray ar = null; PdfObject content = PdfReader.GetPdfObject(pageN.Get(PdfName.CONTENTS), pageN); if (content == null) { ar = new PdfArray(); pageN.Put(PdfName.CONTENTS, ar); } else if (content.IsArray()) { ar = (PdfArray)content; } else if (content.IsStream()) { ar = new PdfArray(); ar.Add(pageN.Get(PdfName.CONTENTS)); pageN.Put(PdfName.CONTENTS, ar); } else { ar = new PdfArray(); pageN.Put(PdfName.CONTENTS, ar); } ByteBuffer out_p = new ByteBuffer(); if (under != null) { out_p.Append(PdfContents.SAVESTATE); ApplyRotation(pageN, out_p); out_p.Append(under.InternalBuffer); out_p.Append(PdfContents.RESTORESTATE); } if (over != null) { out_p.Append(PdfContents.SAVESTATE); } PdfStream stream = new PdfStream(out_p.ToByteArray()); stream.FlateCompress(cstp.CompressionLevel); PdfIndirectReference ref1 = cstp.AddToBody(stream).IndirectReference; ar.AddFirst(ref1); out_p.Reset(); if (over != null) { out_p.Append(' '); out_p.Append(PdfContents.RESTORESTATE); out_p.Append(PdfContents.SAVESTATE); ApplyRotation(pageN, out_p); out_p.Append(over.InternalBuffer); out_p.Append(PdfContents.RESTORESTATE); stream = new PdfStream(out_p.ToByteArray()); stream.FlateCompress(cstp.CompressionLevel); ar.Add(cstp.AddToBody(stream).IndirectReference); } pageN.Put(PdfName.RESOURCES, pageResources.Resources); }
/** * @see com.lowagie.text.pdf.PdfDictionary#toPdf(com.lowagie.text.pdf.PdfWriter, java.io.OutputStream) */ public override void ToPdf(PdfWriter writer, Stream os) { if (inputStream != null && compressed) { Put(PdfName.FILTER, PdfName.FLATEDECODE); } PdfEncryption crypto = null; if (writer != null) { crypto = writer.Encryption; } if (crypto != null) { PdfObject filter = Get(PdfName.FILTER); if (filter != null) { if (PdfName.CRYPT.Equals(filter)) { crypto = null; } else if (filter.IsArray()) { PdfArray a = (PdfArray)filter; if (!a.IsEmpty() && PdfName.CRYPT.Equals(a[0])) { crypto = null; } } } } if (crypto != null && crypto.IsEmbeddedFilesOnly()) { PdfArray filter = new PdfArray(); PdfArray decodeparms = new PdfArray(); PdfDictionary crypt = new PdfDictionary(); crypt.Put(PdfName.NAME, PdfName.STDCF); filter.Add(PdfName.CRYPT); decodeparms.Add(crypt); if (compressed) { filter.Add(PdfName.FLATEDECODE); decodeparms.Add(new PdfNull()); } Put(PdfName.FILTER, filter); Put(PdfName.DECODEPARMS, decodeparms); } PdfObject nn = Get(PdfName.LENGTH); if (crypto != null && nn != null && nn.IsNumber()) { int sz = ((PdfNumber)nn).IntValue; Put(PdfName.LENGTH, new PdfNumber(crypto.CalculateStreamSize(sz))); SuperToPdf(writer, os); Put(PdfName.LENGTH, nn); } else { SuperToPdf(writer, os); } os.Write(STARTSTREAM, 0, STARTSTREAM.Length); if (inputStream != null) { rawLength = 0; ZOutputStream def = null; OutputStreamCounter osc = new OutputStreamCounter(os); OutputStreamEncryption ose = null; Stream fout = osc; if (crypto != null) { fout = ose = crypto.GetEncryptionStream(fout); } if (compressed) { fout = def = new ZOutputStream(fout, compressionLevel); } byte[] buf = new byte[4192]; while (true) { int n = inputStream.Read(buf, 0, buf.Length); if (n <= 0) { break; } fout.Write(buf, 0, n); rawLength += n; } if (def != null) { def.Finish(); } if (ose != null) { ose.Finish(); } inputStreamLength = osc.Counter; } else { if (crypto == null) { if (streamBytes != null) { streamBytes.WriteTo(os); } else { os.Write(bytes, 0, bytes.Length); } } else { byte[] b; if (streamBytes != null) { b = crypto.EncryptByteArray(streamBytes.ToArray()); } else { b = crypto.EncryptByteArray(bytes); } os.Write(b, 0, b.Length); } } os.Write(ENDSTREAM, 0, ENDSTREAM.Length); }
private static void GetOCGOrder(PdfArray order, PdfLayer layer) { if (!layer.OnPanel) return; if (layer.Title == null) order.Add(layer.Ref); ArrayList children = layer.Children; if (children == null) return; PdfArray kids = new PdfArray(); if (layer.Title != null) kids.Add(new PdfString(layer.Title, PdfObject.TEXT_UNICODE)); for (int k = 0; k < children.Count; ++k) { GetOCGOrder(kids, (PdfLayer)children[k]); } if (kids.Size > 0) order.Add(kids); }
/** * Translate a PRArray to a PdfArray. Also translate all of the objects contained * in it */ protected PdfArray CopyArray(PdfArray inp) { PdfArray outp = new PdfArray(); foreach (PdfObject value in inp.ArrayList) { outp.Add(CopyObject(value)); } return outp; }
/** * Returns the CrossReferenceTable of the <CODE>Body</CODE>. * @param os * @param root * @param info * @param encryption * @param fileID * @param prevxref * @throws IOException */ internal void WriteCrossReferenceTable(Stream os, PdfIndirectReference root, PdfIndirectReference info, PdfIndirectReference encryption, PdfObject fileID, int prevxref) { int refNumber = 0; if (writer.FullCompression) { FlushObjStm(); refNumber = IndirectReferenceNumber; xrefs[new PdfCrossReference(refNumber, position)] = null; } int first = ((PdfCrossReference)xrefs.GetMinKey()).Refnum; int len = 0; ArrayList sections = new ArrayList(); foreach (PdfCrossReference entry in xrefs.Keys) { if (first + len == entry.Refnum) ++len; else { sections.Add(first); sections.Add(len); first = entry.Refnum; len = 1; } } sections.Add(first); sections.Add(len); if (writer.FullCompression) { int mid = 4; uint mask = 0xff000000; for (; mid > 1; --mid) { if ((mask & position) != 0) break; mask >>= 8; } ByteBuffer buf = new ByteBuffer(); foreach (PdfCrossReference entry in xrefs.Keys) { entry.ToPdf(mid, buf); } PdfStream xr = new PdfStream(buf.ToByteArray()); buf = null; xr.FlateCompress(writer.CompressionLevel); xr.Put(PdfName.SIZE, new PdfNumber(Size)); xr.Put(PdfName.ROOT, root); if (info != null) { xr.Put(PdfName.INFO, info); } if (encryption != null) xr.Put(PdfName.ENCRYPT, encryption); if (fileID != null) xr.Put(PdfName.ID, fileID); xr.Put(PdfName.W, new PdfArray(new int[]{1, mid, 2})); xr.Put(PdfName.TYPE, PdfName.XREF); PdfArray idx = new PdfArray(); for (int k = 0; k < sections.Count; ++k) idx.Add(new PdfNumber((int)sections[k])); xr.Put(PdfName.INDEX, idx); if (prevxref > 0) xr.Put(PdfName.PREV, new PdfNumber(prevxref)); PdfEncryption enc = writer.crypto; writer.crypto = null; PdfIndirectObject indirect = new PdfIndirectObject(refNumber, xr, writer); indirect.WriteTo(writer.Os); writer.crypto = enc; } else { byte[] tmp = GetISOBytes("xref\n"); os.Write(tmp, 0, tmp.Length); IEnumerator i = xrefs.Keys; i.MoveNext(); for (int k = 0; k < sections.Count; k += 2) { first = (int)sections[k]; len = (int)sections[k + 1]; tmp = GetISOBytes(first.ToString()); os.Write(tmp, 0, tmp.Length); os.WriteByte((byte)' '); tmp = GetISOBytes(len.ToString()); os.Write(tmp, 0, tmp.Length); os.WriteByte((byte)'\n'); while (len-- > 0) { ((PdfCrossReference)i.Current).ToPdf(os); i.MoveNext(); } } } }
public void AlterContents() { if (over == null && under == null) return; PdfArray ar = null; PdfObject content = PdfReader.GetPdfObject(pageN.Get(PdfName.CONTENTS), pageN); if (content == null) { ar = new PdfArray(); pageN.Put(PdfName.CONTENTS, ar); } else if (content.IsArray()) { ar = (PdfArray)content; } else if (content.IsStream()) { ar = new PdfArray(); ar.Add(pageN.Get(PdfName.CONTENTS)); pageN.Put(PdfName.CONTENTS, ar); } else { ar = new PdfArray(); pageN.Put(PdfName.CONTENTS, ar); } ByteBuffer out_p = new ByteBuffer(); if (under != null) { out_p.Append(PdfContents.SAVESTATE); ApplyRotation(pageN, out_p); out_p.Append(under.InternalBuffer); out_p.Append(PdfContents.RESTORESTATE); } if (over != null) out_p.Append(PdfContents.SAVESTATE); PdfStream stream = new PdfStream(out_p.ToByteArray()); stream.FlateCompress(cstp.CompressionLevel); PdfIndirectReference ref1 = cstp.AddToBody(stream).IndirectReference; ar.AddFirst(ref1); out_p.Reset(); if (over != null) { out_p.Append(' '); out_p.Append(PdfContents.RESTORESTATE); out_p.Append(PdfContents.SAVESTATE); ApplyRotation(pageN, out_p); out_p.Append(over.InternalBuffer); out_p.Append(PdfContents.RESTORESTATE); stream = new PdfStream(out_p.ToByteArray()); stream.FlateCompress(cstp.CompressionLevel); ar.Add(cstp.AddToBody(stream).IndirectReference); } pageN.Put(PdfName.RESOURCES, pageResources.Resources); }
/** * Creates a name tree. * @param items the item of the name tree. The key is a <CODE>String</CODE> * and the value is a <CODE>PdfObject</CODE>. Note that although the * keys are strings only the lower byte is used and no check is made for chars * with the same lower byte and different upper byte. This will generate a wrong * tree name. * @param writer the writer * @throws IOException on error * @return the dictionary with the name tree. This dictionary is the one * generally pointed to by the key /Dests, for example */ public static PdfDictionary WriteTree(Hashtable items, PdfWriter writer) { if (items.Count == 0) return null; String[] names = new String[items.Count]; items.Keys.CopyTo(names, 0); Array.Sort(names); if (names.Length <= leafSize) { PdfDictionary dic = new PdfDictionary(); PdfArray ar = new PdfArray(); for (int k = 0; k < names.Length; ++k) { ar.Add(new PdfString(names[k], null)); ar.Add((PdfObject)items[names[k]]); } dic.Put(PdfName.NAMES, ar); return dic; } int skip = leafSize; PdfIndirectReference[] kids = new PdfIndirectReference[(names.Length + leafSize - 1) / leafSize]; for (int k = 0; k < kids.Length; ++k) { int offset = k * leafSize; int end = Math.Min(offset + leafSize, names.Length); PdfDictionary dic = new PdfDictionary(); PdfArray arr = new PdfArray(); arr.Add(new PdfString(names[offset], null)); arr.Add(new PdfString(names[end - 1], null)); dic.Put(PdfName.LIMITS, arr); arr = new PdfArray(); for (; offset < end; ++offset) { arr.Add(new PdfString(names[offset], null)); arr.Add((PdfObject)items[names[offset]]); } dic.Put(PdfName.NAMES, arr); kids[k] = writer.AddToBody(dic).IndirectReference; } int top = kids.Length; while (true) { if (top <= leafSize) { PdfArray arr = new PdfArray(); for (int k = 0; k < top; ++k) arr.Add(kids[k]); PdfDictionary dic = new PdfDictionary(); dic.Put(PdfName.KIDS, arr); return dic; } skip *= leafSize; int tt = (names.Length + skip - 1 )/ skip; for (int k = 0; k < tt; ++k) { int offset = k * leafSize; int end = Math.Min(offset + leafSize, top); PdfDictionary dic = new PdfDictionary(); PdfArray arr = new PdfArray(); arr.Add(new PdfString(names[k * skip], null)); arr.Add(new PdfString(names[Math.Min((k + 1) * skip, names.Length) - 1], null)); dic.Put(PdfName.LIMITS, arr); arr = new PdfArray(); for (; offset < end; ++offset) { arr.Add(kids[offset]); } dic.Put(PdfName.KIDS, arr); kids[k] = writer.AddToBody(dic).IndirectReference; } top = tt; } }
public PdfArray GetEncodedRecipients() { PdfArray EncodedRecipients = new PdfArray(); byte[] cms = null; for (int i=0; i<recipients.Count; i++) { try { cms = GetEncodedRecipient(i); EncodedRecipients.Add(new PdfLiteral(PdfContentByte.EscapeString(cms))); } catch { EncodedRecipients = null; } } return EncodedRecipients; }
/** * Adds documentFields. */ public void AddDocumentField(PdfIndirectReference piref) { documentFields.Add(piref); }
/** * Reads next frame image */ protected void ReadImage() { ix = ReadShort(); // (sub)image position & size iy = ReadShort(); iw = ReadShort(); ih = ReadShort(); int packed = inp.ReadByte(); lctFlag = (packed & 0x80) != 0; // 1 - local color table flag interlace = (packed & 0x40) != 0; // 2 - interlace flag // 3 - sort flag // 4-5 - reserved lctSize = 2 << (packed & 7); // 6-8 - local color table size m_bpc = NewBpc(m_gbpc); if (lctFlag) { m_curr_table = ReadColorTable((packed & 7) + 1); // read table m_bpc = NewBpc((packed & 7) + 1); } else { m_curr_table = m_global_table; } if (transparency && transIndex >= m_curr_table.Length / 3) transparency = false; if (transparency && m_bpc == 1) { // Acrobat 5.05 doesn't like this combination byte[] tp = new byte[12]; Array.Copy(m_curr_table, 0, tp, 0, 6); m_curr_table = tp; m_bpc = 2; } bool skipZero = DecodeImageData(); // decode pixel data if (!skipZero) Skip(); Image img = null; img = new ImgRaw(iw, ih, 1, m_bpc, m_out); PdfArray colorspace = new PdfArray(); colorspace.Add(PdfName.INDEXED); colorspace.Add(PdfName.DEVICERGB); int len = m_curr_table.Length; colorspace.Add(new PdfNumber(len / 3 - 1)); colorspace.Add(new PdfString(m_curr_table)); PdfDictionary ad = new PdfDictionary(); ad.Put(PdfName.COLORSPACE, colorspace); img.Additional = ad; if (transparency) { img.Transparency = new int[]{transIndex, transIndex}; } img.OriginalType = Image.ORIGINAL_GIF; img.OriginalData = fromData; img.Url = fromUrl; GifFrame gf = new GifFrame(); gf.image = img; gf.ix = ix; gf.iy = iy; frames.Add(gf); // add image to frame list //ResetFrame(); }
/** * Compresses the stream. * @param compressionLevel the compression level (0 = best speed, 9 = best compression, -1 is default) * @since 2.1.3 */ public void FlateCompress(int compressionLevel) { if (!Document.Compress) { return; } // check if the flateCompress-method has allready been if (compressed) { return; } this.compressionLevel = compressionLevel; if (inputStream != null) { compressed = true; return; } // check if a filter allready exists PdfObject filter = PdfReader.GetPdfObject(Get(PdfName.FILTER)); if (filter != null) { if (filter.IsName()) { if (PdfName.FLATEDECODE.Equals(filter)) { return; } } else if (filter.IsArray()) { if (((PdfArray)filter).Contains(PdfName.FLATEDECODE)) { return; } } else { throw new PdfException("Stream could not be compressed: filter is not a name or array."); } } // compress MemoryStream stream = new MemoryStream(); var zip = new ZOutputStream(stream, compressionLevel); if (streamBytes != null) { streamBytes.WriteTo(zip); } else { zip.Write(bytes, 0, bytes.Length); } //zip.Close(); zip.Finish(); // update the object streamBytes = stream; bytes = null; Put(PdfName.LENGTH, new PdfNumber(streamBytes.Length)); if (filter == null) { Put(PdfName.FILTER, PdfName.FLATEDECODE); } else { PdfArray filters = new PdfArray(filter); filters.Add(PdfName.FLATEDECODE); Put(PdfName.FILTER, filters); } compressed = true; }
public static PdfAnnotation CreateInk(PdfWriter writer, Rectangle rect, string contents, float[][] inkList) { PdfAnnotation annot = new PdfAnnotation(writer, rect); annot.Put(PdfName.SUBTYPE, PdfName.INK); annot.Put(PdfName.CONTENTS, new PdfString(contents, PdfObject.TEXT_UNICODE)); PdfArray outer = new PdfArray(); for (int k = 0; k < inkList.Length; ++k) { PdfArray inner = new PdfArray(); float[] deep = inkList[k]; for (int j = 0; j < deep.Length; ++j) inner.Add(new PdfNumber(deep[j])); outer.Add(inner); } annot.Put(PdfName.INKLIST, outer); return annot; }
internal static PdfArray CreateDestinationArray(String value, PdfWriter writer) { PdfArray ar = new PdfArray(); StringTokenizer tk = new StringTokenizer(value); int n = int.Parse(tk.NextToken()); ar.Add(writer.GetPageReference(n)); if (!tk.HasMoreTokens()) { ar.Add(PdfName.XYZ); ar.Add(new float[]{0, 10000, 0}); } else { String fn = tk.NextToken(); if (fn.StartsWith("/")) fn = fn.Substring(1); ar.Add(new PdfName(fn)); for (int k = 0; k < 4 && tk.HasMoreTokens(); ++k) { fn = tk.NextToken(); if (fn.Equals("null")) ar.Add(PdfNull.PDFNULL); else ar.Add(new PdfNumber(fn)); } } return ar; }
public static PdfAnnotation CreateLine(PdfWriter writer, Rectangle rect, string contents, float x1, float y1, float x2, float y2) { PdfAnnotation annot = new PdfAnnotation(writer, rect); annot.Put(PdfName.SUBTYPE, PdfName.LINE); annot.Put(PdfName.CONTENTS, new PdfString(contents, PdfObject.TEXT_UNICODE)); PdfArray array = new PdfArray(new PdfNumber(x1)); array.Add(new PdfNumber(y1)); array.Add(new PdfNumber(x2)); array.Add(new PdfNumber(y2)); annot.Put(PdfName.L, array); return annot; }
/** * Sets a collection of optional content groups whose states are intended to follow * a "radio button" paradigm. That is, the state of at most one optional * content group in the array should be ON at a time: if one group is turned * ON, all others must be turned OFF. * @param group the radio group */ public void AddOCGRadioGroup(ArrayList group) { PdfArray ar = new PdfArray(); for (int k = 0; k < group.Count; ++k) { PdfLayer layer = (PdfLayer)group[k]; if (layer.Title == null) ar.Add(layer.Ref); } if (ar.Size == 0) return; OCGRadioGroup.Add(ar); }
public static PdfAnnotation CreateMarkup(PdfWriter writer, Rectangle rect, string contents, int type, float[] quadPoints) { PdfAnnotation annot = new PdfAnnotation(writer, rect); PdfName name = PdfName.HIGHLIGHT; switch (type) { case MARKUP_UNDERLINE: name = PdfName.UNDERLINE; break; case MARKUP_STRIKEOUT: name = PdfName.STRIKEOUT; break; case MARKUP_SQUIGGLY: name = PdfName.SQUIGGLY; break; } annot.Put(PdfName.SUBTYPE, name); annot.Put(PdfName.CONTENTS, new PdfString(contents, PdfObject.TEXT_UNICODE)); PdfArray array = new PdfArray(); for (int k = 0; k < quadPoints.Length; ++k) array.Add(new PdfNumber(quadPoints[k])); annot.Put(PdfName.QUADPOINTS, array); return annot; }
/** * Signals that the <CODE>Document</CODE> has been opened and that * <CODE>Elements</CODE> can be added. * <P> * When this method is called, the PDF-document header is * written to the outputstream. */ public override void Open() { base.Open(); pdf_version.WriteHeader(os); body = new PdfBody(this); if (pdfxConformance.IsPdfX32002()) { PdfDictionary sec = new PdfDictionary(); sec.Put(PdfName.GAMMA, new PdfArray(new float[]{2.2f,2.2f,2.2f})); sec.Put(PdfName.MATRIX, new PdfArray(new float[]{0.4124f,0.2126f,0.0193f,0.3576f,0.7152f,0.1192f,0.1805f,0.0722f,0.9505f})); sec.Put(PdfName.WHITEPOINT, new PdfArray(new float[]{0.9505f,1f,1.089f})); PdfArray arr = new PdfArray(PdfName.CALRGB); arr.Add(sec); SetDefaultColorspace(PdfName.DEFAULTRGB, AddToBody(arr).IndirectReference); } }
public static PdfArray GetMKColor(Color color) { PdfArray array = new PdfArray(); int type = ExtendedColor.GetType(color); switch (type) { case ExtendedColor.TYPE_GRAY: { array.Add(new PdfNumber(((GrayColor)color).Gray)); break; } case ExtendedColor.TYPE_CMYK: { CMYKColor cmyk = (CMYKColor)color; array.Add(new PdfNumber(cmyk.Cyan)); array.Add(new PdfNumber(cmyk.Magenta)); array.Add(new PdfNumber(cmyk.Yellow)); array.Add(new PdfNumber(cmyk.Black)); break; } case ExtendedColor.TYPE_SEPARATION: case ExtendedColor.TYPE_PATTERN: case ExtendedColor.TYPE_SHADING: throw new Exception("Separations, patterns and shadings are not allowed in MK dictionary."); default: array.Add(new PdfNumber(color.R / 255f)); array.Add(new PdfNumber(color.G / 255f)); array.Add(new PdfNumber(color.B / 255f)); break; } return array; }
protected void FillOCProperties(bool erase) { if (vOCProperties == null) vOCProperties = new PdfOCProperties(); if (erase) { vOCProperties.Remove(PdfName.OCGS); vOCProperties.Remove(PdfName.D); } if (vOCProperties.Get(PdfName.OCGS) == null) { PdfArray gr = new PdfArray(); foreach (PdfLayer layer in documentOCG.Keys) { gr.Add(layer.Ref); } vOCProperties.Put(PdfName.OCGS, gr); } if (vOCProperties.Get(PdfName.D) != null) return; ArrayList docOrder = new ArrayList(documentOCGorder); for (ListIterator it = new ListIterator(docOrder); it.HasNext();) { PdfLayer layer = (PdfLayer)it.Next(); if (layer.Parent != null) it.Remove(); } PdfArray order = new PdfArray(); foreach (PdfLayer layer in docOrder) { GetOCGOrder(order, layer); } PdfDictionary d = new PdfDictionary(); vOCProperties.Put(PdfName.D, d); d.Put(PdfName.ORDER, order); PdfArray grx = new PdfArray(); foreach (PdfLayer layer in documentOCG.Keys) { if (!layer.On) grx.Add(layer.Ref); } if (grx.Size > 0) d.Put(PdfName.OFF, grx); if (OCGRadioGroup.Size > 0) d.Put(PdfName.RBGROUPS, OCGRadioGroup); if (OCGLocked.Size > 0) d.Put(PdfName.LOCKED, OCGLocked); AddASEvent(PdfName.VIEW, PdfName.ZOOM); AddASEvent(PdfName.VIEW, PdfName.VIEW); AddASEvent(PdfName.PRINT, PdfName.PRINT); AddASEvent(PdfName.EXPORT, PdfName.EXPORT); d.Put(PdfName.LISTMODE, PdfName.VISIBLEPAGES); }
public void SetMKIconFit(PdfName scale, PdfName scalingType, float leftoverLeft, float leftoverBottom, bool fitInBounds) { PdfDictionary dic = new PdfDictionary(); if (!scale.Equals(PdfName.A)) dic.Put(PdfName.SW, scale); if (!scalingType.Equals(PdfName.P)) dic.Put(PdfName.S, scalingType); if (leftoverLeft != 0.5f || leftoverBottom != 0.5f) { PdfArray array = new PdfArray(new PdfNumber(leftoverLeft)); array.Add(new PdfNumber(leftoverBottom)); dic.Put(PdfName.A, array); } if (fitInBounds) dic.Put(PdfName.FB, PdfBoolean.PDFTRUE); MK.Put(PdfName.IF, dic); }
private void AddASEvent(PdfName eventa, PdfName category) { PdfArray arr = new PdfArray(); foreach (PdfLayer layer in documentOCG.Keys) { PdfDictionary usage = (PdfDictionary)layer.Get(PdfName.USAGE); if (usage != null && usage.Get(category) != null) arr.Add(layer.Ref); } if (arr.Size == 0) return; PdfDictionary d = (PdfDictionary)vOCProperties.Get(PdfName.D); PdfArray arras = (PdfArray)d.Get(PdfName.AS); if (arras == null) { arras = new PdfArray(); d.Put(PdfName.AS, arras); } PdfDictionary asa = new PdfDictionary(); asa.Put(PdfName.EVENT, eventa); asa.Put(PdfName.CATEGORY, new PdfArray(category)); asa.Put(PdfName.OCGS, arr); arras.Add(asa); }
/** Generates the font dictionary for this font. * @return the PdfDictionary containing the font dictionary * @param subsetPrefix the subset prefx * @param firstChar the first valid character * @param lastChar the last valid character * @param shortTag a 256 bytes long <CODE>byte</CODE> array where each unused byte is represented by 0 * @param fontDescriptor the indirect reference to a PdfDictionary containing the font descriptor or <CODE>null</CODE> * @throws DocumentException if there is an error */ protected PdfDictionary GetFontBaseType(PdfIndirectReference fontDescriptor, string subsetPrefix, int firstChar, int lastChar, byte[] shortTag) { PdfDictionary dic = new PdfDictionary(PdfName.FONT); if (cff) { dic.Put(PdfName.SUBTYPE, PdfName.TYPE1); dic.Put(PdfName.BASEFONT, new PdfName(fontName + style)); } else { dic.Put(PdfName.SUBTYPE, PdfName.TRUETYPE); dic.Put(PdfName.BASEFONT, new PdfName(subsetPrefix + fontName + style)); } dic.Put(PdfName.BASEFONT, new PdfName(subsetPrefix + fontName + style)); if (!fontSpecific) { for (int k = firstChar; k <= lastChar; ++k) { if (!differences[k].Equals(notdef)) { firstChar = k; break; } } if (encoding.Equals(CP1252) || encoding.Equals(MACROMAN)) dic.Put(PdfName.ENCODING, encoding.Equals(CP1252) ? PdfName.WIN_ANSI_ENCODING : PdfName.MAC_ROMAN_ENCODING); else { PdfDictionary enc = new PdfDictionary(PdfName.ENCODING); PdfArray dif = new PdfArray(); bool gap = true; for (int k = firstChar; k <= lastChar; ++k) { if (shortTag[k] != 0) { if (gap) { dif.Add(new PdfNumber(k)); gap = false; } dif.Add(new PdfName(differences[k])); } else gap = true; } enc.Put(PdfName.DIFFERENCES, dif); dic.Put(PdfName.ENCODING, enc); } } dic.Put(PdfName.FIRSTCHAR, new PdfNumber(firstChar)); dic.Put(PdfName.LASTCHAR, new PdfNumber(lastChar)); PdfArray wd = new PdfArray(); for (int k = firstChar; k <= lastChar; ++k) { if (shortTag[k] == 0) wd.Add(new PdfNumber(0)); else wd.Add(new PdfNumber(widths[k])); } dic.Put(PdfName.WIDTHS, wd); if (fontDescriptor != null) dic.Put(PdfName.FONTDESCRIPTOR, fontDescriptor); return dic; }
/** * Sets the option list for fields of type list or combo. One of <CODE>exportValues</CODE> * or <CODE>displayValues</CODE> may be <CODE>null</CODE> but not both. This method will only * set the list but will not set the value or appearance. For that, calling <CODE>setField()</CODE> * is required. * <p> * An example: * <p> * <PRE> * PdfReader pdf = new PdfReader("input.pdf"); * PdfStamper stp = new PdfStamper(pdf, new FileOutputStream("output.pdf")); * AcroFields af = stp.GetAcroFields(); * af.SetListOption("ComboBox", new String[]{"a", "b", "c"}, new String[]{"first", "second", "third"}); * af.SetField("ComboBox", "b"); * stp.Close(); * </PRE> * @param fieldName the field name * @param exportValues the export values * @param displayValues the display values * @return <CODE>true</CODE> if the operation succeeded, <CODE>false</CODE> otherwise */ public bool SetListOption(String fieldName, String[] exportValues, String[] displayValues) { if (exportValues == null && displayValues == null) return false; if (exportValues != null && displayValues != null && exportValues.Length != displayValues.Length) throw new ArgumentException("The export and the display array must have the same size."); int ftype = GetFieldType(fieldName); if (ftype != FIELD_TYPE_COMBO && ftype != FIELD_TYPE_LIST) return false; Item fd = (Item)fields[fieldName]; String[] sing = null; if (exportValues == null && displayValues != null) sing = displayValues; else if (exportValues != null && displayValues == null) sing = exportValues; PdfArray opt = new PdfArray(); if (sing != null) { for (int k = 0; k < sing.Length; ++k) opt.Add(new PdfString(sing[k], PdfObject.TEXT_UNICODE)); } else { for (int k = 0; k < exportValues.Length; ++k) { PdfArray a = new PdfArray(); a.Add(new PdfString(exportValues[k], PdfObject.TEXT_UNICODE)); a.Add(new PdfString(displayValues[k], PdfObject.TEXT_UNICODE)); opt.Add(a); } } fd.WriteToAll( PdfName.OPT, opt, Item.WRITE_VALUE | Item.WRITE_MERGED ); return true; }
protected PdfArray BranchForm(Hashtable level, PdfIndirectReference parent, String fname) { PdfArray arr = new PdfArray(); foreach (DictionaryEntry entry in level) { String name = (String)entry.Key; Object obj = entry.Value; PdfIndirectReference ind = PdfIndirectReference; PdfDictionary dic = new PdfDictionary(); if (parent != null) { dic.Put(PdfName.PARENT, parent); } dic.Put(PdfName.T, new PdfString(name, PdfObject.TEXT_UNICODE)); String fname2 = fname + "." + name; int coidx = calculationOrder.IndexOf(fname2); if (coidx >= 0) { calculationOrderRefs[coidx] = ind; } if (obj is Hashtable) { dic.Put(PdfName.KIDS, BranchForm((Hashtable)obj, ind, fname2)); arr.Add(ind); AddToBody(dic, ind); } else { ArrayList list = (ArrayList)obj; dic.MergeDifferent((PdfDictionary)list[0]); if (list.Count == 3) { dic.MergeDifferent((PdfDictionary)list[2]); int page = (int)list[1]; PdfDictionary pageDic = (PdfDictionary)pageDics[page - 1]; PdfArray annots = pageDic.GetAsArray(PdfName.ANNOTS); if (annots == null) { annots = new PdfArray(); pageDic.Put(PdfName.ANNOTS, annots); } PdfNumber nn = (PdfNumber)dic.Get(iTextTag); dic.Remove(iTextTag); AdjustTabOrder(annots, ind, nn); } else { PdfArray kids = new PdfArray(); for (int k = 1; k < list.Count; k += 2) { int page = (int)list[k]; PdfDictionary pageDic = (PdfDictionary)pageDics[page - 1]; PdfArray annots = pageDic.GetAsArray(PdfName.ANNOTS); if (annots == null) { annots = new PdfArray(); pageDic.Put(PdfName.ANNOTS, annots); } PdfDictionary widget = new PdfDictionary(); widget.Merge((PdfDictionary)list[k + 1]); widget.Put(PdfName.PARENT, ind); PdfNumber nn = (PdfNumber)widget.Get(iTextTag); widget.Remove(iTextTag); PdfIndirectReference wref = AddToBody(widget).IndirectReference; AdjustTabOrder(annots, wref, nn); kids.Add(wref); Propagate(widget, null, false); } dic.Put(PdfName.KIDS, kids); } arr.Add(ind); AddToBody(dic, ind); Propagate(dic, null, false); } } return(arr); }
public PdfArray RotateAnnotations(PdfWriter writer, Rectangle pageSize) { PdfArray array = new PdfArray(); int rotation = pageSize.Rotation % 360; int currentPage = writer.CurrentPageNumber; for (int k = 0; k < annotations.Count; ++k) { PdfAnnotation dic = (PdfAnnotation)annotations[k]; int page = dic.PlaceInPage; if (page > currentPage) { delayedAnnotations.Add(dic); continue; } if (dic.IsForm()) { if (!dic.IsUsed()) { Hashtable templates = dic.Templates; if (templates != null) acroForm.AddFieldTemplates(templates); } PdfFormField field = (PdfFormField)dic; if (field.Parent == null) acroForm.AddDocumentField(field.IndirectReference); } if (dic.IsAnnotation()) { array.Add(dic.IndirectReference); if (!dic.IsUsed()) { PdfRectangle rect = (PdfRectangle)dic.Get(PdfName.RECT); if (rect != null) { switch (rotation) { case 90: dic.Put(PdfName.RECT, new PdfRectangle( pageSize.Top - rect.Bottom, rect.Left, pageSize.Top - rect.Top, rect.Right)); break; case 180: dic.Put(PdfName.RECT, new PdfRectangle( pageSize.Right - rect.Left, pageSize.Top - rect.Bottom, pageSize.Right - rect.Right, pageSize.Top - rect.Top)); break; case 270: dic.Put(PdfName.RECT, new PdfRectangle( rect.Bottom, pageSize.Right - rect.Left, rect.Top, pageSize.Right - rect.Right)); break; } } } } if (!dic.IsUsed()) { dic.SetUsed(); writer.AddToBody(dic, dic.IndirectReference); } } return array; }
/** Generates the font dictionary for this font. * @return the PdfDictionary containing the font dictionary * @param firstChar the first valid character * @param lastChar the last valid character * @param shortTag a 256 bytes long <CODE>byte</CODE> array where each unused byte is represented by 0 * @param fontDescriptor the indirect reference to a PdfDictionary containing the font descriptor or <CODE>null</CODE> */ private PdfDictionary GetFontBaseType(PdfIndirectReference fontDescriptor, int firstChar, int lastChar, byte[] shortTag) { PdfDictionary dic = new PdfDictionary(PdfName.FONT); dic.Put(PdfName.SUBTYPE, PdfName.TYPE1); dic.Put(PdfName.BASEFONT, new PdfName(FontName)); bool stdEncoding = encoding.Equals(CP1252) || encoding.Equals(MACROMAN); if (!fontSpecific || specialMap != null) { for (int k = firstChar; k <= lastChar; ++k) { if (!differences[k].Equals(notdef)) { firstChar = k; break; } } if (stdEncoding) dic.Put(PdfName.ENCODING, encoding.Equals(CP1252) ? PdfName.WIN_ANSI_ENCODING : PdfName.MAC_ROMAN_ENCODING); else { PdfDictionary enc = new PdfDictionary(PdfName.ENCODING); PdfArray dif = new PdfArray(); bool gap = true; for (int k = firstChar; k <= lastChar; ++k) { if (shortTag[k] != 0) { if (gap) { dif.Add(new PdfNumber(k)); gap = false; } dif.Add(new PdfName(differences[k])); } else gap = true; } enc.Put(PdfName.DIFFERENCES, dif); dic.Put(PdfName.ENCODING, enc); } } if (specialMap != null || forceWidthsOutput || !(builtinFont && (fontSpecific || stdEncoding))) { dic.Put(PdfName.FIRSTCHAR, new PdfNumber(firstChar)); dic.Put(PdfName.LASTCHAR, new PdfNumber(lastChar)); PdfArray wd = new PdfArray(); for (int k = firstChar; k <= lastChar; ++k) { if (shortTag[k] == 0) wd.Add(new PdfNumber(0)); else wd.Add(new PdfNumber(widths[k])); } dic.Put(PdfName.WIDTHS, wd); } if (!builtinFont && fontDescriptor != null) dic.Put(PdfName.FONTDESCRIPTOR, fontDescriptor); return dic; }
/** * Compresses the stream. * @param compressionLevel the compression level (0 = best speed, 9 = best compression, -1 is default) * @since 2.1.3 */ public void FlateCompress(int compressionLevel) { if (!Document.Compress) return; // check if the flateCompress-method has allready been if (compressed) { return; } this.compressionLevel = compressionLevel; if (inputStream != null) { compressed = true; return; } // check if a filter allready exists PdfObject filter = PdfReader.GetPdfObject(Get(PdfName.FILTER)); if (filter != null) { if (filter.IsName()) { if (PdfName.FLATEDECODE.Equals(filter)) return; } else if (filter.IsArray()) { if (((PdfArray) filter).Contains(PdfName.FLATEDECODE)) return; } else { throw new PdfException("Stream could not be compressed: filter is not a name or array."); } } // compress MemoryStream stream = new MemoryStream(); var zip = new ZOutputStream(stream, compressionLevel); if (streamBytes != null) streamBytes.WriteTo(zip); else zip.Write(bytes, 0, bytes.Length); //zip.Close(); zip.Finish(); // update the object streamBytes = stream; bytes = null; Put(PdfName.LENGTH, new PdfNumber(streamBytes.Length)); if (filter == null) { Put(PdfName.FILTER, PdfName.FLATEDECODE); } else { PdfArray filters = new PdfArray(filter); filters.Add(PdfName.FLATEDECODE); Put(PdfName.FILTER, filters); } compressed = true; }
/** * Creates a number tree. * @param items the item of the number tree. The key is an <CODE>Integer</CODE> * and the value is a <CODE>PdfObject</CODE>. * @param writer the writer * @throws IOException on error * @return the dictionary with the number tree. */ public static PdfDictionary WriteTree(Hashtable items, PdfWriter writer) { if (items.Count == 0) { return(null); } int[] numbers = new int[items.Count]; items.Keys.CopyTo(numbers, 0); Array.Sort(numbers); if (numbers.Length <= leafSize) { PdfDictionary dic = new PdfDictionary(); PdfArray ar = new PdfArray(); for (int k = 0; k < numbers.Length; ++k) { ar.Add(new PdfNumber(numbers[k])); ar.Add((PdfObject)items[numbers[k]]); } dic.Put(PdfName.NUMS, ar); return(dic); } int skip = leafSize; PdfIndirectReference[] kids = new PdfIndirectReference[(numbers.Length + leafSize - 1) / leafSize]; for (int k = 0; k < kids.Length; ++k) { int offset = k * leafSize; int end = Math.Min(offset + leafSize, numbers.Length); PdfDictionary dic = new PdfDictionary(); PdfArray arr = new PdfArray(); arr.Add(new PdfNumber(numbers[offset])); arr.Add(new PdfNumber(numbers[end - 1])); dic.Put(PdfName.LIMITS, arr); arr = new PdfArray(); for (; offset < end; ++offset) { arr.Add(new PdfNumber(numbers[offset])); arr.Add((PdfObject)items[numbers[offset]]); } dic.Put(PdfName.NUMS, arr); kids[k] = writer.AddToBody(dic).IndirectReference; } int top = kids.Length; while (true) { if (top <= leafSize) { PdfArray arr = new PdfArray(); for (int k = 0; k < top; ++k) { arr.Add(kids[k]); } PdfDictionary dic = new PdfDictionary(); dic.Put(PdfName.KIDS, arr); return(dic); } skip *= leafSize; int tt = (numbers.Length + skip - 1) / skip; for (int k = 0; k < tt; ++k) { int offset = k * leafSize; int end = Math.Min(offset + leafSize, top); PdfDictionary dic = new PdfDictionary(); PdfArray arr = new PdfArray(); arr.Add(new PdfNumber(numbers[k * skip])); arr.Add(new PdfNumber(numbers[Math.Min((k + 1) * skip, numbers.Length) - 1])); dic.Put(PdfName.LIMITS, arr); arr = new PdfArray(); for (; offset < end; ++offset) { arr.Add(kids[offset]); } dic.Put(PdfName.KIDS, arr); kids[k] = writer.AddToBody(dic).IndirectReference; } top = tt; } }