/**
  * Creates a RichMediaExecute action dictionary.
  * @param   ref a reference to rich media annotation dictionary for
  * an annotation for which to execute the script command.
  * @param   command the command name and arguments to be
  * executed when the rich-media-execute action is invoked.
  */
 public RichMediaExecuteAction(PdfIndirectReference refi, RichMediaCommand command)
     : base()
 {
     Put(PdfName.S, PdfName.RICHMEDIAEXECUTE);
     Put(PdfName.TA, refi);
     Put(PdfName.CMD, command);
 }
 private ImageRenderInfo(Matrix ctm, PdfIndirectReference refi, PdfDictionary colorSpaceDictionary)
 {
     this.ctm = ctm;
     this.refi = refi;
     this.inlineImageInfo = null;
     this.colorSpaceDictionary = colorSpaceDictionary;
 }
Exemplo n.º 3
0
 virtual protected internal void SetReader(PdfReader reader){
     this.reader = reader;
     PdfObject obj = reader.Catalog.Get(PdfName.STRUCTTREEROOT);
     obj = GetDirectObject(obj);
     if ((obj == null) || (!obj.IsDictionary()))
         throw new BadPdfFormatException(MessageLocalization.GetComposedMessage("no.structtreeroot.found"));
     structTreeRoot = (PdfDictionary)obj;
     obj = GetDirectObject(structTreeRoot.Get(PdfName.PARENTTREE));
     if (obj == null || !obj.IsDictionary())
         throw new BadPdfFormatException(MessageLocalization.GetComposedMessage("the.document.does.not.contain.parenttree"));
     parentTree = (PdfDictionary)obj;
     sourceRoleMap = null;
     sourceClassMap = null;
     nullReference = null;
 }
        /** Generates the font dictionary.
         * @param descendant the descendant dictionary
         * @param subsetPrefix the subset prefix
         * @param toUnicode the ToUnicode stream
         * @return the stream
         */
        virtual public PdfDictionary GetFontBaseType(PdfIndirectReference descendant, string subsetPrefix, PdfIndirectReference toUnicode)
        {
            PdfDictionary dic = new PdfDictionary(PdfName.FONT);

            dic.Put(PdfName.SUBTYPE, PdfName.TYPE0);
            // The PDF Reference manual advises to add -encoding to CID font names
            if (cff)
            {
                dic.Put(PdfName.BASEFONT, new PdfName(subsetPrefix + fontName + "-" + encoding));
            }
            else
            {
                dic.Put(PdfName.BASEFONT, new PdfName(subsetPrefix + fontName));
            }
            dic.Put(PdfName.ENCODING, new PdfName(encoding));
            dic.Put(PdfName.DESCENDANTFONTS, new PdfArray(descendant));
            if (toUnicode != null)
            {
                dic.Put(PdfName.TOUNICODE, toUnicode);
            }
            return(dic);
        }
        /** Outputs to the writer the font dictionaries and streams.
         * @param writer the writer for this document
         * @param ref the font indirect reference
         * @param parms several parameters that depend on the font type
         * @throws IOException on error
         * @throws DocumentException error in generating the object
         */
        internal override void WriteFont(PdfWriter writer, PdfIndirectReference piref, Object[] parms)
        {
            Hashtable longTag = (Hashtable)parms[0];

            AddRangeUni(longTag, true, subset);
            ArrayList tmp = new ArrayList();

            foreach (object o in longTag.Values)
            {
                tmp.Add(o);
            }
            Object[] metrics = tmp.ToArray();
            Array.Sort(metrics, this);
            PdfIndirectReference ind_font = null;
            PdfObject            pobj     = null;
            PdfIndirectObject    obj      = null;
            PdfIndirectReference cidset   = null;

            if (writer.PDFXConformance == PdfWriter.PDFA1A || writer.PDFXConformance == PdfWriter.PDFA1B)
            {
                PdfStream stream;
                if (metrics.Length == 0)
                {
                    stream = new PdfStream(new byte[] { (byte)0x80 });
                }
                else
                {
                    int    top = ((int[])metrics[metrics.Length - 1])[0];
                    byte[] bt  = new byte[top / 8 + 1];
                    for (int k = 0; k < metrics.Length; ++k)
                    {
                        int v = ((int[])metrics[k])[0];
                        bt[v / 8] |= rotbits[v % 8];
                    }
                    stream = new PdfStream(bt);
                    stream.FlateCompress(compressionLevel);
                }
                cidset = writer.AddToBody(stream).IndirectReference;
            }
            // sivan: cff
            if (cff)
            {
                byte[] b = ReadCffFont();
                if (subset || subsetRanges != null)
                {
                    CFFFontSubset cffs = new CFFFontSubset(new RandomAccessFileOrArray(b), longTag);
                    b = cffs.Process((cffs.GetNames())[0]);
                }

                pobj     = new StreamFont(b, "CIDFontType0C", compressionLevel);
                obj      = writer.AddToBody(pobj);
                ind_font = obj.IndirectReference;
            }
            else
            {
                byte[] b;
                if (subset || directoryOffset != 0)
                {
                    TrueTypeFontSubSet sb = new TrueTypeFontSubSet(fileName, new RandomAccessFileOrArray(rf), longTag, directoryOffset, false, false);
                    b = sb.Process();
                }
                else
                {
                    b = GetFullFont();
                }
                int[] lengths = new int[] { b.Length };
                pobj     = new StreamFont(b, lengths, compressionLevel);
                obj      = writer.AddToBody(pobj);
                ind_font = obj.IndirectReference;
            }
            String subsetPrefix = "";

            if (subset)
            {
                subsetPrefix = CreateSubsetPrefix();
            }
            PdfDictionary dic = GetFontDescriptor(ind_font, subsetPrefix, cidset);

            obj      = writer.AddToBody(dic);
            ind_font = obj.IndirectReference;

            pobj     = GetCIDFontType2(ind_font, subsetPrefix, metrics);
            obj      = writer.AddToBody(pobj);
            ind_font = obj.IndirectReference;

            pobj = GetToUnicode(metrics);
            PdfIndirectReference toUnicodeRef = null;

            if (pobj != null)
            {
                obj          = writer.AddToBody(pobj);
                toUnicodeRef = obj.IndirectReference;
            }

            pobj = GetFontBaseType(ind_font, subsetPrefix, toUnicodeRef);
            writer.AddToBody(pobj, piref);
        }
Exemplo n.º 6
0
 // constructors
 
 /**
 * Constructs a PDF-Trailer.
 *
 * @param        size        the number of entries in the <CODE>PdfCrossReferenceTable</CODE>
 * @param        offset      offset of the <CODE>PdfCrossReferenceTable</CODE>
 * @param        root        an indirect reference to the root of the PDF document
 * @param        info        an indirect reference to the info object of the PDF document
 * @param encryption
 * @param fileID
 * @param prevxref
 */
 
 public PdfTrailer(int size, long offset, PdfIndirectReference root, PdfIndirectReference info, PdfIndirectReference encryption, PdfObject fileID, long prevxref) {
     this.offset = offset;
     Put(PdfName.SIZE, new PdfNumber(size));
     Put(PdfName.ROOT, root);
     if (info != null) {
         Put(PdfName.INFO, info);
     }
     if (encryption != null)
         Put(PdfName.ENCRYPT, encryption);
     if (fileID != null)
         Put(PdfName.ID, fileID);
     if (prevxref > 0)
         Put(PdfName.PREV, new PdfNumber(prevxref));
 }
Exemplo n.º 7
0
 /**
 * Writes a <CODE>PdfImage</CODE> to the outputstream.
 *
 * @param pdfImage the image to be added
 * @return a <CODE>PdfIndirectReference</CODE> to the encapsulated image
 * @throws PdfException when a document isn't open yet, or has been closed
 */        
 internal virtual PdfIndirectReference Add(PdfImage pdfImage, PdfIndirectReference fixedRef) {
     if (! imageDictionary.Contains(pdfImage.Name)) {
         PdfWriter.CheckPdfIsoConformance(this, PdfIsoKeys.PDFISOKEY_IMAGE, pdfImage);
         if (fixedRef is PRIndirectReference) {
             PRIndirectReference r2 = (PRIndirectReference)fixedRef;
             fixedRef = new PdfIndirectReference(0, GetNewObjectNumber(r2.Reader, r2.Number, r2.Generation));
         }
         if (fixedRef == null)
             fixedRef = AddToBody(pdfImage).IndirectReference;
         else
             AddToBody(pdfImage, fixedRef);
         imageDictionary.Put(pdfImage.Name, fixedRef);
         return fixedRef;
     }
     return (PdfIndirectReference)imageDictionary.Get(pdfImage.Name);
 }
Exemplo n.º 8
0
 internal void AddDocumentField(PdfIndirectReference ref_p) {
     PdfDictionary catalog = reader.Catalog;
     PdfDictionary acroForm = (PdfDictionary)PdfReader.GetPdfObject(catalog.Get(PdfName.ACROFORM), catalog);
     if (acroForm == null) {
         acroForm = new PdfDictionary();
         catalog.Put(PdfName.ACROFORM, acroForm);
         MarkUsed(catalog);
     }
     PdfArray fields = (PdfArray)PdfReader.GetPdfObject(acroForm.Get(PdfName.FIELDS), acroForm);
     if (fields == null) {
         fields = new PdfArray();
         acroForm.Put(PdfName.FIELDS, fields);
         MarkUsed(acroForm);
     }
     if (!acroForm.Contains(PdfName.DA)) {
         acroForm.Put(PdfName.DA, new PdfString("/Helv 0 Tf 0 g "));
         MarkUsed(acroForm);
     }
     fields.Add(ref_p);
     MarkUsed(fields);
 }
Exemplo n.º 9
0
 /**
  * Set the page of the <CODE>PdfDestination</CODE>-object.
  *
  * @param pageReference indirect reference to the page
  * @return <CODE>true</CODE> if this page was set as the <CODE>PdfDestination</CODE>-page.
  */
 public bool SetDestinationPage(PdfIndirectReference pageReference)
 {
     if (destination == null) {
         return false;
     }
     return destination.AddPage(pageReference);
 }
Exemplo n.º 10
0
 /**
 * Creates a new, empty, membership layer.
 * @param writer the writer
 */    
 public PdfLayerMembership(PdfWriter writer) : base(PdfName.OCMD) {
     Put(PdfName.OCGS, members);
     refi = writer.PdfIndirectReference;
 }
Exemplo n.º 11
0
        internal void Propagate(PdfObject obj, PdfIndirectReference refo, bool restricted)
        {
            if (obj == null)
            {
                return;
            }
            //        if (refo != null)
            //            AddToBody(obj, refo);
            if (obj is PdfIndirectReference)
            {
                return;
            }
            switch (obj.Type)
            {
            case PdfObject.DICTIONARY:
            case PdfObject.STREAM: {
                PdfDictionary dic = (PdfDictionary)obj;
                foreach (PdfName key in dic.Keys)
                {
                    if (restricted && (key.Equals(PdfName.PARENT) || key.Equals(PdfName.KIDS)))
                    {
                        continue;
                    }
                    PdfObject ob = dic.Get(key);
                    if (ob != null && ob.IsIndirect())
                    {
                        PRIndirectReference ind = (PRIndirectReference)ob;
                        if (!SetVisited(ind) && !IsPage(ind))
                        {
                            PdfIndirectReference refi = GetNewReference(ind);
                            Propagate(PdfReader.GetPdfObjectRelease(ind), refi, restricted);
                        }
                    }
                    else
                    {
                        Propagate(ob, null, restricted);
                    }
                }
                break;
            }

            case PdfObject.ARRAY: {
                //PdfArray arr = new PdfArray();
                for (ListIterator <PdfObject> it = ((PdfArray)obj).GetListIterator(); it.HasNext();)
                {
                    PdfObject ob = it.Next();
                    if (ob != null && ob.IsIndirect())
                    {
                        PRIndirectReference ind = (PRIndirectReference)ob;
                        if (!IsVisited(ind) && !IsPage(ind))
                        {
                            PdfIndirectReference refi = GetNewReference(ind);
                            Propagate(PdfReader.GetPdfObjectRelease(ind), refi, restricted);
                        }
                    }
                    else
                    {
                        Propagate(ob, null, restricted);
                    }
                }
                break;
            }

            case PdfObject.INDIRECT: {
                throw new Exception(MessageLocalization.GetComposedMessage("reference.pointing.to.reference"));
            }
            }
        }
Exemplo n.º 12
0
        /**Creates a Rendition action
         * @param file
         * @param fs
         * @param mimeType
         * @param ref
         * @return a Media Clip action
         * @throws IOException
         */
        public static PdfAction Rendition(String file, PdfFileSpecification fs, String mimeType, PdfIndirectReference refi)
        {
            PdfAction js = new PdfAction();

            js.Put(PdfName.S, PdfName.RENDITION);
            js.Put(PdfName.R, new PdfRendition(file, fs, mimeType));
            js.Put(new PdfName("OP"), new PdfNumber(0));
            js.Put(new PdfName("AN"), refi);
            return(js);
        }
Exemplo n.º 13
0
        /**
         * Constructs a new <CODE>PdfAction</CODE> of Subtype GoTo.
         * @param destination the destination to go to
         */

        internal PdfAction(PdfIndirectReference destination)
        {
            Put(PdfName.S, PdfName.GOTO);
            Put(PdfName.D, destination);
        }
Exemplo n.º 14
0
 internal void AddPage(PdfIndirectReference page)
 {
     pages.Add(page);
 }
Exemplo n.º 15
0
        // returns the top parent to include in the catalog
        internal PdfIndirectReference WritePageTree()
        {
            if (pages.Count == 0)
            {
                throw new IOException(MessageLocalization.GetComposedMessage("the.document.has.no.pages"));
            }
            int leaf = 1;
            List <PdfIndirectReference> tParents    = parents;
            List <PdfIndirectReference> tPages      = pages;
            List <PdfIndirectReference> nextParents = new List <PdfIndirectReference>();

            while (true)
            {
                leaf *= leafSize;
                int stdCount   = leafSize;
                int rightCount = tPages.Count % leafSize;
                if (rightCount == 0)
                {
                    rightCount = leafSize;
                }
                for (int p = 0; p < tParents.Count; ++p)
                {
                    int count;
                    int thisLeaf = leaf;
                    if (p == tParents.Count - 1)
                    {
                        count    = rightCount;
                        thisLeaf = pages.Count % leaf;
                        if (thisLeaf == 0)
                        {
                            thisLeaf = leaf;
                        }
                    }
                    else
                    {
                        count = stdCount;
                    }
                    PdfDictionary top = new PdfDictionary(PdfName.PAGES);
                    top.Put(PdfName.COUNT, new PdfNumber(thisLeaf));
                    PdfArray         kids   = new PdfArray();
                    List <PdfObject> intern = kids.ArrayList;
                    foreach (PdfObject obb in tPages.GetRange(p * stdCount, count))
                    {
                        intern.Add(obb);
                    }
                    top.Put(PdfName.KIDS, kids);
                    if (tParents.Count > 1)
                    {
                        if ((p % leafSize) == 0)
                        {
                            nextParents.Add(writer.PdfIndirectReference);
                        }
                        top.Put(PdfName.PARENT, nextParents[p / leafSize]);
                    }
                    writer.AddToBody(top, tParents[p]);
                }
                if (tParents.Count == 1)
                {
                    topParent = tParents[0];
                    return(topParent);
                }
                tPages      = tParents;
                tParents    = nextParents;
                nextParents = new List <PdfIndirectReference>();
            }
        }
Exemplo n.º 16
0
 /** Each spot color used in a document has an instance of this class.
  * @param colorName the color name
  * @param indirectReference the indirect reference to the font
  * @param scolor the <CODE>PDfSpotColor</CODE>
  */
 internal ColorDetails(PdfName colorName, PdfIndirectReference indirectReference, PdfSpotColor scolor)
 {
     this.colorName         = colorName;
     this.indirectReference = indirectReference;
     this.spotcolor         = scolor;
 }
Exemplo n.º 17
0
 /** Outputs to the writer the font dictionaries and streams.
  * @param writer the writer for this document
  * @param ref the font indirect reference
  * @param parms several parameters that depend on the font type
  * @throws IOException on error
  * @throws DocumentException error in generating the object
  */
 internal override void WriteFont(PdfWriter writer, PdfIndirectReference piref, Object[] parms)
 {
     writer.GetTtfUnicodeWriter().WriteFont(this, piref, parms, rotbits);
 }
Exemplo n.º 18
0
 internal PdfName AddShading(PdfName name, PdfIndirectReference reference) {
     name = TranslateName(name);
     shadingDictionary.Put(name, reference);
     return name;
 }
Exemplo n.º 19
0
 internal PdfName AddExtGState(PdfName name, PdfIndirectReference reference) {
     name = TranslateName(name);
     extGStateDictionary.Put(name, reference);
     return name;
 }
Exemplo n.º 20
0
        protected PdfArray BranchForm(Dictionary <string, object> level, PdfIndirectReference parent, String fname)
        {
            PdfArray arr = new PdfArray();

            foreach (KeyValuePair <string, object> entry in level)
            {
                String name = 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 Dictionary <string, object> )
                {
                    dic.Put(PdfName.KIDS, BranchForm((Dictionary <string, object>)obj, ind, fname2));
                    arr.Add(ind);
                    AddToBody(dic, ind);
                }
                else
                {
                    List <object> list = (List <object>)obj;
                    dic.MergeDifferent((PdfDictionary)list[0]);
                    if (list.Count == 3)
                    {
                        dic.MergeDifferent((PdfDictionary)list[2]);
                        int           page    = (int)list[1];
                        PdfDictionary pageDic = 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 = 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);
        }
Exemplo n.º 21
0
 internal void Close(Hashtable moreInfo)
 {
     if (closed)
         return;
     if (useVp) {
         reader.SetViewerPreferences(viewerPreferences);
         MarkUsed(reader.Trailer.Get(PdfName.ROOT));
     }
     if (flat)
         FlatFields();
     if (flatFreeText)
         FlatFreeTextFields();
     AddFieldResources();
     PdfDictionary acroForm = (PdfDictionary)PdfReader.GetPdfObject(reader.Catalog.Get(PdfName.ACROFORM), reader.Catalog);
     if (acroFields != null && acroFields.Xfa.Changed) {
         MarkUsed(acroForm);
         if (!flat)
             acroFields.Xfa.SetXfa(this);
     }
     if (sigFlags != 0) {
         if (acroForm != null) {
             acroForm.Put(PdfName.SIGFLAGS, new PdfNumber(sigFlags));
             MarkUsed(acroForm);
         }
     }
     closed = true;
     AddSharedObjectsToBody();
     SetOutlines();
     SetJavaScript();
     AddFileAttachments();
     PdfDictionary catalog = reader.Catalog;
     if (openAction != null) {
         catalog.Put(PdfName.OPENACTION, openAction);
     }
     byte[] altMetadata = xmpMetadata;
     if (altMetadata == null) {
         PdfObject xmpo = PdfReader.GetPdfObject(catalog.Get(PdfName.METADATA));
         if (xmpo != null && xmpo.IsStream()) {
             altMetadata = PdfReader.GetStreamBytesRaw((PRStream)xmpo);
             PdfReader.KillIndirect(xmpo);
         }
     }
     // if there is XMP data to add: add it
     if (altMetadata != null) {
         PdfStream xmp = new PdfStream(altMetadata);
         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);
         MarkUsed(catalog);
     }
     PRIndirectReference iInfo = null;
     try {
         file.ReOpen();
         AlterContents();
         iInfo = (PRIndirectReference)reader.trailer.Get(PdfName.INFO);
         int skip = -1;
         if (iInfo != null)
             skip = iInfo.Number;
         int rootN = ((PRIndirectReference)reader.trailer.Get(PdfName.ROOT)).Number;
         if (append) {
             int[] keys = marked.GetKeys();
             for (int k = 0; k < keys.Length; ++k) {
                 int j = keys[k];
                 PdfObject obj = reader.GetPdfObjectRelease(j);
                 if (obj != null && skip != j && j < initialXrefSize) {
                     AddToBody(obj, j, j != rootN);
                 }
             }
             for (int k = initialXrefSize; k < reader.XrefSize; ++k) {
                 PdfObject obj = reader.GetPdfObject(k);
                 if (obj != null) {
                     AddToBody(obj, GetNewObjectNumber(reader, k, 0));
                 }
             }
         }
         else {
             for (int k = 1; k < reader.XrefSize; ++k) {
                 PdfObject obj = reader.GetPdfObjectRelease(k);
                 if (obj != null && skip != k) {
                     AddToBody(obj, GetNewObjectNumber(reader, k, 0), k != rootN);
                 }
             }
         }
     }
     finally {
         try {
             file.Close();
         }
         catch  {
             // empty on purpose
         }
     }
     PdfIndirectReference encryption = null;
     PdfObject fileID = null;
     if (crypto != null) {
         if (append) {
             encryption = reader.GetCryptoRef();
         }
         else {
             PdfIndirectObject encryptionObject = AddToBody(crypto.GetEncryptionDictionary(), false);
             encryption = encryptionObject.IndirectReference;
         }
         fileID = crypto.FileID;
     }
     PRIndirectReference iRoot = (PRIndirectReference)reader.trailer.Get(PdfName.ROOT);
     PdfIndirectReference root = new PdfIndirectReference(0, GetNewObjectNumber(reader, iRoot.Number, 0));
     PdfIndirectReference info = null;
     PdfDictionary oldInfo = (PdfDictionary)PdfReader.GetPdfObject(iInfo);
     PdfDictionary newInfo = new PdfDictionary();
     if (oldInfo != null) {
         foreach (PdfName key in oldInfo.Keys) {
             PdfObject value = PdfReader.GetPdfObject(oldInfo.Get(key));
             newInfo.Put(key, value);
         }
     }
     if (moreInfo != null) {
         foreach (DictionaryEntry entry in moreInfo) {
             PdfName keyName = new PdfName((String)entry.Key);
             String value = (String)entry.Value;
             if (value == null)
                 newInfo.Remove(keyName);
             else
                 newInfo.Put(keyName, new PdfString(value, PdfObject.TEXT_UNICODE));
         }
     }
     if (append) {
         if (iInfo == null)
             info = AddToBody(newInfo, false).IndirectReference;
         else
             info = AddToBody(newInfo, iInfo.Number, false).IndirectReference;
     }
     else {
         if (newInfo.Size != 0)
             info = AddToBody(newInfo, false).IndirectReference;
     }
     // write the cross-reference table of the body
     body.WriteCrossReferenceTable(os, root, info, encryption, fileID, prevxref);
     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,
         root,
         info,
         encryption,
         fileID, prevxref);
         trailer.ToPdf(this, os);
     }
     os.Flush();
     if (CloseStream)
         os.Close();
     reader.Close();
 }
Exemplo n.º 22
0
        /** 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);
        }
 // constructors
 
 /**
 * Constructs a <CODE>PdfCatalog</CODE>.
 *
 * @param        pages       an indirect reference to the root of the document's Pages tree.
 * @param writer the writer the catalog applies to
 */
 
 internal PdfCatalog(PdfIndirectReference pages, PdfWriter writer) : base(CATALOG) {
     this.writer = writer;
     Put(PdfName.PAGES, pages);
 }
Exemplo n.º 24
0
        // constructor

        /**
         * Constructs a <CODE>PdfImage</CODE>-object.
         *
         * @param image the <CODE>Image</CODE>-object
         * @param name the <CODE>PdfName</CODE> for this image
         * @throws BadPdfFormatException on error
         */

        public PdfImage(Image image, String name, PdfIndirectReference maskRef) : base()
        {
            this.image = image;
            if (name == null)
            {
                GenerateImgResName(image);
            }
            else
            {
                this.name = new PdfName(name);
            }
            Put(PdfName.TYPE, PdfName.XOBJECT);
            Put(PdfName.SUBTYPE, PdfName.IMAGE);
            Put(PdfName.WIDTH, new PdfNumber(image.Width));
            Put(PdfName.HEIGHT, new PdfNumber(image.Height));
            if (image.Layer != null)
            {
                Put(PdfName.OC, image.Layer.Ref);
            }
            if (image.IsMask() && (image.Bpc == 1 || image.Bpc > 0xff))
            {
                Put(PdfName.IMAGEMASK, PdfBoolean.PDFTRUE);
            }
            if (maskRef != null)
            {
                if (image.Smask)
                {
                    Put(PdfName.SMASK, maskRef);
                }
                else
                {
                    Put(PdfName.MASK, maskRef);
                }
            }
            if (image.IsMask() && image.Inverted)
            {
                Put(PdfName.DECODE, new PdfLiteral("[1 0]"));
            }
            if (image.Interpolation)
            {
                Put(PdfName.INTERPOLATE, PdfBoolean.PDFTRUE);
            }
            Stream isp = null;

            try {
                // deal with transparency
                int[] transparency = image.Transparency;
                if (transparency != null && !image.IsMask() && maskRef == null)
                {
                    StringBuilder s = new StringBuilder("[");
                    for (int k = 0; k < transparency.Length; ++k)
                    {
                        s.Append(transparency[k]).Append(' ');
                    }
                    s.Append(']');
                    Put(PdfName.MASK, new PdfLiteral(s.ToString()));
                }
                // Raw Image data
                if (image.IsImgRaw())
                {
                    // will also have the CCITT parameters
                    int colorspace = image.Colorspace;
                    bytes = image.RawData;
                    Put(PdfName.LENGTH, new PdfNumber(bytes.Length));
                    int bpc = image.Bpc;
                    if (bpc > 0xff)
                    {
                        if (!image.IsMask())
                        {
                            Put(PdfName.COLORSPACE, PdfName.DEVICEGRAY);
                        }
                        Put(PdfName.BITSPERCOMPONENT, new PdfNumber(1));
                        Put(PdfName.FILTER, PdfName.CCITTFAXDECODE);
                        int           k           = bpc - Image.CCITTG3_1D;
                        PdfDictionary decodeparms = new PdfDictionary();
                        if (k != 0)
                        {
                            decodeparms.Put(PdfName.K, new PdfNumber(k));
                        }
                        if ((colorspace & Image.CCITT_BLACKIS1) != 0)
                        {
                            decodeparms.Put(PdfName.BLACKIS1, PdfBoolean.PDFTRUE);
                        }
                        if ((colorspace & Image.CCITT_ENCODEDBYTEALIGN) != 0)
                        {
                            decodeparms.Put(PdfName.ENCODEDBYTEALIGN, PdfBoolean.PDFTRUE);
                        }
                        if ((colorspace & Image.CCITT_ENDOFLINE) != 0)
                        {
                            decodeparms.Put(PdfName.ENDOFLINE, PdfBoolean.PDFTRUE);
                        }
                        if ((colorspace & Image.CCITT_ENDOFBLOCK) != 0)
                        {
                            decodeparms.Put(PdfName.ENDOFBLOCK, PdfBoolean.PDFFALSE);
                        }
                        decodeparms.Put(PdfName.COLUMNS, new PdfNumber(image.Width));
                        decodeparms.Put(PdfName.ROWS, new PdfNumber(image.Height));
                        Put(PdfName.DECODEPARMS, decodeparms);
                    }
                    else
                    {
                        switch (colorspace)
                        {
                        case 1:
                            Put(PdfName.COLORSPACE, PdfName.DEVICEGRAY);
                            if (image.Inverted)
                            {
                                Put(PdfName.DECODE, new PdfLiteral("[1 0]"));
                            }
                            break;

                        case 3:
                            Put(PdfName.COLORSPACE, PdfName.DEVICERGB);
                            if (image.Inverted)
                            {
                                Put(PdfName.DECODE, new PdfLiteral("[1 0 1 0 1 0]"));
                            }
                            break;

                        case 4:
                        default:
                            Put(PdfName.COLORSPACE, PdfName.DEVICECMYK);
                            if (image.Inverted)
                            {
                                Put(PdfName.DECODE, new PdfLiteral("[1 0 1 0 1 0 1 0]"));
                            }
                            break;
                        }
                        PdfDictionary additional = image.Additional;
                        if (additional != null)
                        {
                            Merge(additional);
                        }
                        if (image.IsMask() && (image.Bpc == 1 || image.Bpc > 8))
                        {
                            Remove(PdfName.COLORSPACE);
                        }
                        Put(PdfName.BITSPERCOMPONENT, new PdfNumber(image.Bpc));
                        if (image.Deflated)
                        {
                            Put(PdfName.FILTER, PdfName.FLATEDECODE);
                        }
                        else
                        {
                            FlateCompress(image.CompressionLevel);
                        }
                    }
                    return;
                }

                // GIF, JPEG or PNG
                String errorID;
                if (image.RawData == null)
                {
                    WebRequest wr = WebRequest.Create(image.Url);
                    wr.Credentials = CredentialCache.DefaultCredentials;
                    isp            = wr.GetResponse().GetResponseStream();
                    errorID        = image.Url.ToString();
                }
                else
                {
                    isp     = new MemoryStream(image.RawData);
                    errorID = "Byte array";
                }
                switch (image.Type)
                {
                case Image.JPEG:
                    Put(PdfName.FILTER, PdfName.DCTDECODE);
                    if (image.ColorTransform == 0)
                    {
                        PdfDictionary decodeparms = new PdfDictionary();
                        decodeparms.Put(PdfName.COLORTRANSFORM, new PdfNumber(0));
                        Put(PdfName.DECODEPARMS, decodeparms);
                    }
                    switch (image.Colorspace)
                    {
                    case 1:
                        Put(PdfName.COLORSPACE, PdfName.DEVICEGRAY);
                        break;

                    case 3:
                        Put(PdfName.COLORSPACE, PdfName.DEVICERGB);
                        break;

                    default:
                        Put(PdfName.COLORSPACE, PdfName.DEVICECMYK);
                        if (image.Inverted)
                        {
                            Put(PdfName.DECODE, new PdfLiteral("[1 0 1 0 1 0 1 0]"));
                        }
                        break;
                    }
                    Put(PdfName.BITSPERCOMPONENT, new PdfNumber(8));
                    if (image.RawData != null)
                    {
                        bytes = image.RawData;
                        Put(PdfName.LENGTH, new PdfNumber(bytes.Length));
                        return;
                    }
                    streamBytes = new MemoryStream();
                    TransferBytes(isp, streamBytes, -1);
                    break;

                case Image.JPEG2000:
                    Put(PdfName.FILTER, PdfName.JPXDECODE);
                    if (image.Colorspace > 0)
                    {
                        switch (image.Colorspace)
                        {
                        case 1:
                            Put(PdfName.COLORSPACE, PdfName.DEVICEGRAY);
                            break;

                        case 3:
                            Put(PdfName.COLORSPACE, PdfName.DEVICERGB);
                            break;

                        default:
                            Put(PdfName.COLORSPACE, PdfName.DEVICECMYK);
                            break;
                        }
                        Put(PdfName.BITSPERCOMPONENT, new PdfNumber(image.Bpc));
                    }
                    if (image.RawData != null)
                    {
                        bytes = image.RawData;
                        Put(PdfName.LENGTH, new PdfNumber(bytes.Length));
                        return;
                    }
                    streamBytes = new MemoryStream();
                    TransferBytes(isp, streamBytes, -1);
                    break;

                case Image.JBIG2:
                    Put(PdfName.FILTER, PdfName.JBIG2DECODE);
                    Put(PdfName.COLORSPACE, PdfName.DEVICEGRAY);
                    Put(PdfName.BITSPERCOMPONENT, new PdfNumber(1));
                    if (image.RawData != null)
                    {
                        bytes = image.RawData;
                        Put(PdfName.LENGTH, new PdfNumber(bytes.Length));
                        return;
                    }
                    streamBytes = new MemoryStream();
                    TransferBytes(isp, streamBytes, -1);
                    break;

                default:
                    throw new IOException(MessageLocalization.GetComposedMessage("1.is.an.unknown.image.format", errorID));
                }
                if (image.CompressionLevel > NO_COMPRESSION)
                {
                    FlateCompress(image.CompressionLevel);
                }
                Put(PdfName.LENGTH, new PdfNumber(streamBytes.Length));
            }
            finally {
                if (isp != null)
                {
                    try{
                        isp.Close();
                    }
                    catch  {
                        // empty on purpose
                    }
                }
            }
        }
Exemplo n.º 25
0
 internal PdfObject[] AddSimpleProperty(Object prop, PdfIndirectReference refi) {
     if (!documentProperties.ContainsKey(prop)) {
         if (prop is IPdfOCG)
             PdfWriter.CheckPdfIsoConformance(this, PdfIsoKeys.PDFISOKEY_LAYER, null);
         documentProperties[prop] = new PdfObject[]{new PdfName("Pr" + (documentProperties.Count + 1)), refi};
     }
     return documentProperties[prop];
 }
Exemplo n.º 26
0
        /// <summary>
        /// methods
        /// </summary>

        /// <summary>
        /// Adds an indirect reference pointing to a  PdfContents -object.
        /// </summary>
        /// <param name="contents">an indirect reference to a  PdfContents -object</param>

        internal void Add(PdfIndirectReference contents)
        {
            Put(PdfName.Contents, contents);
        }
Exemplo n.º 27
0
 internal PdfIndirectObject Add(PdfObject objecta, PdfIndirectReference refa, bool inObjStm) {
     return Add(objecta, refa.Number, inObjStm);
 }
        private ReturnType FindAndCopyMarks(PdfArray pages, int arrayNumber, int newArrayNumber)
        {
            if (pages.GetAsNumber(0).IntValue > arrayNumber)
            {
                return(ReturnType.BELOW);
            }
            if (pages.GetAsNumber(pages.Size - 2).IntValue < arrayNumber)
            {
                return(ReturnType.ABOVE);
            }
            int cur   = pages.Size / 4;
            int begin = 0;
            int curNumber;

            while (true)
            {
                curNumber = pages.GetAsNumber((begin + cur) * 2).IntValue;
                if (curNumber == arrayNumber)
                {
                    PdfObject obj  = pages.GetPdfObject((begin + cur) * 2 + 1);
                    PdfObject obj1 = obj;
                    while (obj.IsIndirect())
                    {
                        obj = PdfReader.GetPdfObjectRelease(obj);
                    }
                    //invalid Nums
                    if (obj.IsArray())
                    {
                        PdfObject firstNotNullKid = null;
                        foreach (PdfObject numObj in (PdfArray)obj)
                        {
                            if (numObj.IsNull())
                            {
                                if (nullReference == null)
                                {
                                    nullReference = writer.AddToBody(new PdfNull()).IndirectReference;
                                }
                                structureTreeRoot.SetPageMark(newArrayNumber, nullReference);
                            }
                            else
                            {
                                PdfObject res = writer.CopyObject(numObj, true, false);
                                if (firstNotNullKid == null)
                                {
                                    firstNotNullKid = res;
                                }
                                structureTreeRoot.SetPageMark(newArrayNumber, (PdfIndirectReference)res);
                            }
                        }
                        AttachStructTreeRootKids(firstNotNullKid);
                    }
                    else if (obj.IsDictionary())
                    {
                        PdfDictionary k = GetKDict((PdfDictionary)obj);
                        if (k == null)
                        {
                            return(ReturnType.NOTFOUND);
                        }
                        PdfObject res = writer.CopyObject(obj1, true, false);
                        structureTreeRoot.SetAnnotationMark(newArrayNumber, (PdfIndirectReference)res);
                    }
                    else
                    {
                        return(ReturnType.NOTFOUND);
                    }
                    return(ReturnType.FOUND);
                }
                if (curNumber < arrayNumber)
                {
                    if (cur == 0)
                    {
                        return(ReturnType.NOTFOUND);
                    }
                    begin += cur;
                    if (cur != 1)
                    {
                        cur /= 2;
                    }
                    if (cur + begin == pages.Size)
                    {
                        return(ReturnType.NOTFOUND);
                    }
                    continue;
                }
                if (cur + begin == 0)
                {
                    return(ReturnType.BELOW);
                }
                if (cur == 0)
                {
                    return(ReturnType.NOTFOUND);
                }
                cur /= 2;
            }
        }
Exemplo n.º 29
0
 /**
 * Adds an object to the PDF body.
 * @param object
 * @param ref
 * @param inObjStm
 * @return a PdfIndirectObject
 * @throws IOException
 */
 public PdfIndirectObject AddToBody(PdfObject objecta, PdfIndirectReference refa, bool inObjStm) {
     PdfIndirectObject iobj = body.Add(objecta, refa, inObjStm);
     return iobj;
 }
Exemplo n.º 30
0
 internal PdfName AddXObject(PdfName name, PdfIndirectReference reference) {
     name = TranslateName(name);
     xObjectDictionary.Put(name, reference);
     return name;
 }
Exemplo n.º 31
0
            private void SerObject(PdfObject obj, int level, ByteBuffer bb, Dictionary <RefKey, int> serialized)
            {
                if (level <= 0)
                {
                    return;
                }
                if (obj == null)
                {
                    bb.Append("$Lnull");
                    return;
                }

                PdfIndirectReference refe    = null;
                ByteBuffer           savedBb = null;

                if (obj.IsIndirect())
                {
                    refe = (PdfIndirectReference)obj;
                    RefKey key = new RefKey(refe);
                    if (serialized.ContainsKey(key))
                    {
                        bb.Append(serialized[key]);
                        return;
                    }
                    else
                    {
                        savedBb = bb;
                        bb      = new ByteBuffer();
                    }
                }
                obj = PdfReader.GetPdfObject(obj);
                if (obj.IsStream())
                {
                    bb.Append("$B");
                    SerDic((PdfDictionary)obj, level - 1, bb, serialized);
                    if (level > 0)
                    {
                        bb.Append(DigestAlgorithms.Digest("MD5", PdfReader.GetStreamBytesRaw((PRStream)obj)));
                    }
                }
                else if (obj.IsDictionary())
                {
                    SerDic((PdfDictionary)obj, level - 1, bb, serialized);
                }
                else if (obj.IsArray())
                {
                    SerArray((PdfArray)obj, level - 1, bb, serialized);
                }
                else if (obj.IsString())
                {
                    bb.Append("$S").Append(obj.ToString());
                }
                else if (obj.IsName())
                {
                    bb.Append("$N").Append(obj.ToString());
                }
                else
                {
                    bb.Append("$L").Append(obj.ToString());
                }

                if (savedBb != null)
                {
                    RefKey key = new RefKey(refe);
                    if (!serialized.ContainsKey(key))
                    {
                        serialized[key] = CalculateHash(bb.Buffer);
                    }
                    savedBb.Append(bb);
                }
            }
Exemplo n.º 32
0
        /** Generates the CIDFontTyte2 dictionary.
         * @param fontDescriptor the indirect reference to the font descriptor
         * @param subsetPrefix the subset prefix
         * @param metrics the horizontal width metrics
         * @return a stream
         */
        virtual public PdfDictionary GetCIDFontType2(PdfIndirectReference fontDescriptor, string subsetPrefix, Object[] metrics)
        {
            PdfDictionary dic = new PdfDictionary(PdfName.FONT);

            // sivan; cff
            if (cff)
            {
                dic.Put(PdfName.SUBTYPE, PdfName.CIDFONTTYPE0);
                dic.Put(PdfName.BASEFONT, new PdfName(subsetPrefix + fontName + "-" + encoding));
            }
            else
            {
                dic.Put(PdfName.SUBTYPE, PdfName.CIDFONTTYPE2);
                dic.Put(PdfName.BASEFONT, new PdfName(subsetPrefix + fontName));
            }
            dic.Put(PdfName.FONTDESCRIPTOR, fontDescriptor);
            if (!cff)
            {
                dic.Put(PdfName.CIDTOGIDMAP, PdfName.IDENTITY);
            }
            PdfDictionary cdic = new PdfDictionary();

            cdic.Put(PdfName.REGISTRY, new PdfString("Adobe"));
            cdic.Put(PdfName.ORDERING, new PdfString("Identity"));
            cdic.Put(PdfName.SUPPLEMENT, new PdfNumber(0));
            dic.Put(PdfName.CIDSYSTEMINFO, cdic);
            if (!vertical)
            {
                dic.Put(PdfName.DW, new PdfNumber(1000));
                StringBuilder buf        = new StringBuilder("[");
                int           lastNumber = -10;
                bool          firstTime  = true;
                for (int k = 0; k < metrics.Length; ++k)
                {
                    int[] metric = (int[])metrics[k];
                    if (metric[1] == 1000)
                    {
                        continue;
                    }
                    int m = metric[0];
                    if (m == lastNumber + 1)
                    {
                        buf.Append(' ').Append(metric[1]);
                    }
                    else
                    {
                        if (!firstTime)
                        {
                            buf.Append(']');
                        }
                        firstTime = false;
                        buf.Append(m).Append('[').Append(metric[1]);
                    }
                    lastNumber = m;
                }
                if (buf.Length > 1)
                {
                    buf.Append("]]");
                    dic.Put(PdfName.W, new PdfLiteral(buf.ToString()));
                }
            }
            return(dic);
        }
Exemplo n.º 33
0
 /**
  * Adds documentFields.
  */
 virtual public void AddDocumentField(PdfIndirectReference piref) {
     documentFields.Add(piref);
 }
        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(), System.Globalization.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(System.Globalization.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 });
        }
Exemplo n.º 35
0
 internal PdfName AddColor(PdfName name, PdfIndirectReference reference) {
     name = TranslateName(name);
     colorDictionary.Put(name, reference);
     return name;
 }
Exemplo n.º 36
0
        /**
         * Creates a file specification with the file embedded. The file may
         * come from the file system or from a byte array.
         * @param writer the <CODE>PdfWriter</CODE>
         * @param filePath the file path
         * @param fileDisplay the file information that is presented to the user
         * @param fileStore the byte array with the file. If it is not <CODE>null</CODE>
         * it takes precedence over <CODE>filePath</CODE>
         * @param mimeType the optional mimeType
         * @param fileParameter the optional extra file parameters such as the creation or modification date
         * @param compressionLevel the level of compression
         * @throws IOException on error
         * @return the file specification
         * @since   2.1.3
         */
        public static PdfFileSpecification FileEmbedded(PdfWriter writer, String filePath, String fileDisplay, byte[] fileStore, String mimeType, PdfDictionary fileParameter, int compressionLevel)
        {
            PdfFileSpecification fs = new PdfFileSpecification();

            fs.writer = writer;
            fs.Put(PdfName.F, new PdfString(fileDisplay));
            fs.SetUnicodeFileName(fileDisplay, false);
            PdfEFStream          stream;
            Stream               inp = null;
            PdfIndirectReference refi;
            PdfIndirectReference refFileLength = null;

            try {
                if (fileStore == null)
                {
                    refFileLength = writer.PdfIndirectReference;
                    if (File.Exists(filePath))
                    {
                        inp = new FileStream(filePath, FileMode.Open, FileAccess.Read);
                    }
                    else
                    {
                        if (filePath.StartsWith("file:/") || filePath.StartsWith("http://") || filePath.StartsWith("https://"))
                        {
                            WebRequest wr = WebRequest.Create(filePath);
                            wr.Credentials = CredentialCache.DefaultCredentials;
                            inp            = wr.GetResponse().GetResponseStream();
                        }
                        else
                        {
                            inp = StreamUtil.GetResourceStream(filePath);
                            if (inp == null)
                            {
                                throw new IOException(MessageLocalization.GetComposedMessage("1.not.found.as.file.or.resource", filePath));
                            }
                        }
                    }
                    stream = new PdfEFStream(inp, writer);
                }
                else
                {
                    stream = new PdfEFStream(fileStore);
                }
                stream.Put(PdfName.TYPE, PdfName.EMBEDDEDFILE);
                stream.FlateCompress(compressionLevel);

                PdfDictionary param = new PdfDictionary();
                if (fileParameter != null)
                {
                    param.Merge(fileParameter);
                }
                if (!param.Contains(PdfName.MODDATE))
                {
                    param.Put(PdfName.MODDATE, new PdfDate());
                }
                if (fileStore == null)
                {
                    stream.Put(PdfName.PARAMS, refFileLength);
                }
                else
                {
                    param.Put(PdfName.SIZE, new PdfNumber(stream.RawLength));
                    stream.Put(PdfName.PARAMS, param);
                }

                if (mimeType != null)
                {
                    stream.Put(PdfName.SUBTYPE, new PdfName(mimeType));
                }

                refi = writer.AddToBody(stream).IndirectReference;
                if (fileStore == null)
                {
                    stream.WriteLength();
                    param.Put(PdfName.SIZE, new PdfNumber(stream.RawLength));
                    writer.AddToBody(param, refFileLength);
                }
            }
            finally {
                if (inp != null)
                {
                    try{ inp.Close(); }catch {}
                }
            }
            PdfDictionary f = new PdfDictionary();

            f.Put(PdfName.F, refi);
            f.Put(PdfName.UF, refi);
            fs.Put(PdfName.EF, f);
            return(fs);
        }
Exemplo n.º 37
0
 internal PdfName AddPattern(PdfName name, PdfIndirectReference reference) {
     name = TranslateName(name);
     patternDictionary.Put(name, reference);
     return name;
 }
Exemplo n.º 38
0
 internal PdfName AddXObject(PdfName name, PdfIndirectReference reference)
 {
     name = TranslateName(name);
     xObjectDictionary.Put(name, reference);
     return(name);
 }
Exemplo n.º 39
0
 internal PdfName AddProperty(PdfName name, PdfIndirectReference reference) {
     name = TranslateName(name);
     propertyDictionary.Put(name, reference);
     return name;
 }
Exemplo n.º 40
0
 internal PdfName AddColor(PdfName name, PdfIndirectReference reference)
 {
     name = TranslateName(name);
     colorDictionary.Put(name, reference);
     return(name);
 }
Exemplo n.º 41
0
 /** Each font used in a document has an instance of this class.
  * This class stores the characters used in the document and other
  * specifics unique to the current working document.
  * @param fontName the font name
  * @param indirectReference the indirect reference to the font
  * @param baseFont the <CODE>BaseFont</CODE>
  */
 internal FontDetails(PdfName fontName, PdfIndirectReference indirectReference, BaseFont baseFont) {
     this.fontName = fontName;
     this.indirectReference = indirectReference;
     this.baseFont = baseFont;
     fontType = baseFont.FontType;
     switch (fontType) {
         case BaseFont.FONT_TYPE_T1:
         case BaseFont.FONT_TYPE_TT:
             shortTag = new byte[256];
             break;
         case BaseFont.FONT_TYPE_CJK:
             cjkTag = new IntHashtable();
             cjkFont = (CJKFont)baseFont;
             break;
         case BaseFont.FONT_TYPE_TTUNI:
             longTag = new Dictionary<int,int[]>();
             ttu = (TrueTypeFontUnicode)baseFont;
             symbolic = baseFont.IsFontSpecific();
             break;
     }
 }
Exemplo n.º 42
0
 internal PdfName AddShading(PdfName name, PdfIndirectReference reference)
 {
     name = TranslateName(name);
     shadingDictionary.Put(name, reference);
     return(name);
 }
Exemplo n.º 43
0
        // constructor
        /**
        * Constructs a <CODE>PdfImage</CODE>-object.
        *
        * @param image the <CODE>Image</CODE>-object
        * @param name the <CODE>PdfName</CODE> for this image
        * @throws BadPdfFormatException on error
        */
        public PdfImage(Image image, String name, PdfIndirectReference maskRef)
        {
            if (name == null)
                GenerateImgResName(image);
            else
                this.name = new PdfName(name);
            Put(PdfName.TYPE, PdfName.XOBJECT);
            Put(PdfName.SUBTYPE, PdfName.IMAGE);
            Put(PdfName.WIDTH, new PdfNumber(image.Width));
            Put(PdfName.HEIGHT, new PdfNumber(image.Height));
            if (image.Layer != null)
                Put(PdfName.OC, image.Layer.Ref);
            if (image.IsMask() && (image.Bpc == 1 || image.Bpc > 0xff))
                Put(PdfName.IMAGEMASK, PdfBoolean.PDFTRUE);
            if (maskRef != null) {
                if (image.Smask)
                    Put(PdfName.SMASK, maskRef);
                else
                    Put(PdfName.MASK, maskRef);
            }
            if (image.IsMask() && image.Inverted)
                Put(PdfName.DECODE, new PdfLiteral("[1 0]"));
            if (image.Interpolation)
                Put(PdfName.INTERPOLATE, PdfBoolean.PDFTRUE);
            Stream isp = null;
            try {
                // Raw Image data
                if (image.IsImgRaw()) {
                    // will also have the CCITT parameters
                    int colorspace = image.Colorspace;
                    int[] transparency = image.Transparency;
                    if (transparency != null && !image.IsMask() && maskRef == null) {
                        StringBuilder s = new StringBuilder("[");
                        for (int k = 0; k < transparency.Length; ++k)
                            s.Append(transparency[k]).Append(' ');
                        s.Append(']');
                        Put(PdfName.MASK, new PdfLiteral(s.ToString()));
                    }
                    bytes = image.RawData;
                    Put(PdfName.LENGTH, new PdfNumber(bytes.Length));
                    int bpc = image.Bpc;
                    if (bpc > 0xff) {
                        if (!image.IsMask())
                            Put(PdfName.COLORSPACE, PdfName.DEVICEGRAY);
                        Put(PdfName.BITSPERCOMPONENT, new PdfNumber(1));
                        Put(PdfName.FILTER, PdfName.CCITTFAXDECODE);
                        int k = bpc - Image.CCITTG3_1D;
                        PdfDictionary decodeparms = new PdfDictionary();
                        if (k != 0)
                            decodeparms.Put(PdfName.K, new PdfNumber(k));
                        if ((colorspace & Image.CCITT_BLACKIS1) != 0)
                            decodeparms.Put(PdfName.BLACKIS1, PdfBoolean.PDFTRUE);
                        if ((colorspace & Image.CCITT_ENCODEDBYTEALIGN) != 0)
                            decodeparms.Put(PdfName.ENCODEDBYTEALIGN, PdfBoolean.PDFTRUE);
                        if ((colorspace & Image.CCITT_ENDOFLINE) != 0)
                            decodeparms.Put(PdfName.ENDOFLINE, PdfBoolean.PDFTRUE);
                        if ((colorspace & Image.CCITT_ENDOFBLOCK) != 0)
                            decodeparms.Put(PdfName.ENDOFBLOCK, PdfBoolean.PDFFALSE);
                        decodeparms.Put(PdfName.COLUMNS, new PdfNumber(image.Width));
                        decodeparms.Put(PdfName.ROWS, new PdfNumber(image.Height));
                        Put(PdfName.DECODEPARMS, decodeparms);
                    }
                    else {
                        switch (colorspace) {
                            case 1:
                                Put(PdfName.COLORSPACE, PdfName.DEVICEGRAY);
                                if (image.Inverted)
                                    Put(PdfName.DECODE, new PdfLiteral("[1 0]"));
                                break;
                            case 3:
                                Put(PdfName.COLORSPACE, PdfName.DEVICERGB);
                                if (image.Inverted)
                                    Put(PdfName.DECODE, new PdfLiteral("[1 0 1 0 1 0]"));
                                break;
                            case 4:
                            default:
                                Put(PdfName.COLORSPACE, PdfName.DEVICECMYK);
                                if (image.Inverted)
                                    Put(PdfName.DECODE, new PdfLiteral("[1 0 1 0 1 0 1 0]"));
                                break;
                        }
                        PdfDictionary additional = image.Additional;
                        if (additional != null)
                            Merge(additional);
                        if (image.IsMask() && (image.Bpc == 1 || image.Bpc > 8))
                            Remove(PdfName.COLORSPACE);
                        Put(PdfName.BITSPERCOMPONENT, new PdfNumber(image.Bpc));
                        if (image.Deflated)
                            Put(PdfName.FILTER, PdfName.FLATEDECODE);
                        else {
                            FlateCompress(image.CompressionLevel);
                        }
                    }
                    return;
                }

                // GIF, JPEG or PNG
                String errorID;
                if (image.RawData == null){
                    WebRequest wr = WebRequest.Create(image.Url);
                    wr.Credentials = CredentialCache.DefaultCredentials;
                    isp = wr.GetResponse().GetResponseStream();
                    errorID = image.Url.ToString();
                }
                else{
                    isp = new MemoryStream(image.RawData);
                    errorID = "Byte array";
                }
                switch (image.Type) {
                    case Image.JPEG:
                        Put(PdfName.FILTER, PdfName.DCTDECODE);
                        switch (image.Colorspace) {
                            case 1:
                                Put(PdfName.COLORSPACE, PdfName.DEVICEGRAY);
                                break;
                            case 3:
                                Put(PdfName.COLORSPACE, PdfName.DEVICERGB);
                                break;
                            default:
                                Put(PdfName.COLORSPACE, PdfName.DEVICECMYK);
                                if (image.Inverted) {
                                    Put(PdfName.DECODE, new PdfLiteral("[1 0 1 0 1 0 1 0]"));
                                }
                                break;
                        }
                        Put(PdfName.BITSPERCOMPONENT, new PdfNumber(8));
                        if (image.RawData != null){
                            bytes = image.RawData;
                            Put(PdfName.LENGTH, new PdfNumber(bytes.Length));
                            return;
                        }
                        streamBytes = new MemoryStream();
                        TransferBytes(isp, streamBytes, -1);
                        break;
                    case Image.JPEG2000:
                        Put(PdfName.FILTER, PdfName.JPXDECODE);
                        if (image.Colorspace > 0) {
                            switch (image.Colorspace) {
                                case 1:
                                    Put(PdfName.COLORSPACE, PdfName.DEVICEGRAY);
                                    break;
                                case 3:
                                    Put(PdfName.COLORSPACE, PdfName.DEVICERGB);
                                    break;
                                default:
                                    Put(PdfName.COLORSPACE, PdfName.DEVICECMYK);
                                    break;
                            }
                            Put(PdfName.BITSPERCOMPONENT, new PdfNumber(image.Bpc));
                        }
                        if (image.RawData != null){
                            bytes = image.RawData;
                            Put(PdfName.LENGTH, new PdfNumber(bytes.Length));
                            return;
                        }
                        streamBytes = new MemoryStream();
                        TransferBytes(isp, streamBytes, -1);
                        break;
                    case Image.JBIG2:
                        Put(PdfName.FILTER, PdfName.JBIG2DECODE);
                        Put(PdfName.COLORSPACE, PdfName.DEVICEGRAY);
                        Put(PdfName.BITSPERCOMPONENT, new PdfNumber(1));
                        if (image.RawData != null){
                            bytes = image.RawData;
                            Put(PdfName.LENGTH, new PdfNumber(bytes.Length));
                            return;
                        }
                        streamBytes = new MemoryStream();
                        TransferBytes(isp, streamBytes, -1);
                        break;
                    default:
                        throw new IOException(MessageLocalization.GetComposedMessage("1.is.an.unknown.image.format", errorID));
                }
                Put(PdfName.LENGTH, new PdfNumber(streamBytes.Length));
            }
            finally {
                if (isp != null) {
                    try{
                        isp.Close();
                    }
                    catch  {
                        // empty on purpose
                    }
                }
            }
        }
Exemplo n.º 44
0
 internal PdfName AddExtGState(PdfName name, PdfIndirectReference reference)
 {
     name = TranslateName(name);
     extGStateDictionary.Put(name, reference);
     return(name);
 }
        /**
        * Gets the <CODE>PdfCatalog</CODE>-object.
        *
        * @param pages an indirect reference to this document pages
        * @return <CODE>PdfCatalog</CODE>
        */
        internal PdfCatalog GetCatalog(PdfIndirectReference pages) {
            PdfCatalog catalog = new PdfCatalog(pages, writer);
            
            // [C1] outlines
            if (rootOutline.Kids.Count > 0) {
                catalog.Put(PdfName.PAGEMODE, PdfName.USEOUTLINES);
                catalog.Put(PdfName.OUTLINES, rootOutline.IndirectReference);
            }
            
            // [C2] version
            writer.GetPdfVersion().AddToCatalog(catalog);
            
            // [C3] preferences
            viewerPreferences.AddToCatalog(catalog);
            
            // [C4] pagelabels
            if (pageLabels != null) {
                catalog.Put(PdfName.PAGELABELS, pageLabels.GetDictionary(writer));
            }
            
            // [C5] named objects
            catalog.AddNames(localDestinations, GetDocumentLevelJS(), documentFileAttachment, writer);
            
            // [C6] actions
            if (openActionName != null) {
                PdfAction action = GetLocalGotoAction(openActionName);
                catalog.OpenAction = action;
            }
            else if (openActionAction != null)
                catalog.OpenAction = openActionAction;
            if (additionalActions != null)   {
                catalog.AdditionalActions = additionalActions;
            }
            
            // [C7] portable collections
            if (collection != null) {
                catalog.Put(PdfName.COLLECTION, collection);
            }

            // [C8] AcroForm
            if (annotationsImp.HasValidAcroForm()) {
                catalog.Put(PdfName.ACROFORM, writer.AddToBody(annotationsImp.AcroForm).IndirectReference);
            }

            if (language != null) {
                catalog.Put(PdfName.LANG, language);
            }

            return catalog;
        }
Exemplo n.º 46
0
 internal PdfName AddProperty(PdfName name, PdfIndirectReference reference)
 {
     name = TranslateName(name);
     propertyDictionary.Put(name, reference);
     return(name);
 }
Exemplo n.º 47
0
 internal PdfAppearance(PdfIndirectReference iref)
 {
     thisReference = iref;
 }
Exemplo n.º 48
0
 /** Outputs to the writer the font dictionaries and streams.
  * @param writer the writer for this document
  * @param ref the font indirect reference
  * @param params several parameters that depend on the font type
  * @throws IOException on error
  * @throws DocumentException error in generating the object
  *
  */
 internal override void WriteFont(PdfWriter writer, PdfIndirectReference refi, Object[] param)
 {
 }
Exemplo n.º 49
0
 protected virtual void Close(PdfIndirectReference info, int skipInfo) {
     AlterContents();
     int rootN = ((PRIndirectReference)reader.trailer.Get(PdfName.ROOT)).Number;
     if (append) {
         int[] keys = marked.GetKeys();
         for (int k = 0; k < keys.Length; ++k) {
             int j = keys[k];
             PdfObject obj = reader.GetPdfObjectRelease(j);
             if (obj != null && skipInfo != j && j < initialXrefSize) {
                 AddToBody(obj, obj.IndRef, j != rootN);
             }
         }
         for (int k = initialXrefSize; k < reader.XrefSize; ++k) {
             PdfObject obj = reader.GetPdfObject(k);
             if (obj != null) {
                 AddToBody(obj, GetNewObjectNumber(reader, k, 0));
             }
         }
     } else {
         for (int k = 1; k < reader.XrefSize; ++k) {
             PdfObject obj = reader.GetPdfObjectRelease(k);
             if (obj != null && skipInfo != k) {
                 AddToBody(obj, GetNewObjectNumber(reader, k, 0), k != rootN);
             }
         }
     }
     PdfIndirectReference encryption = null;
     PdfObject fileID = null;
     if (crypto != null) {
         if (append) {
             encryption = reader.GetCryptoRef();
         } else {
             PdfIndirectObject encryptionObject = AddToBody(crypto.GetEncryptionDictionary(), false);
             encryption = encryptionObject.IndirectReference;
         }
         fileID = crypto.GetFileID(true);
     }
     else {
         PdfArray IDs = reader.trailer.GetAsArray(PdfName.ID);
         if(IDs != null && IDs.GetAsString(0) != null) {
             fileID = PdfEncryption.CreateInfoId(IDs.GetAsString(0).GetBytes(), true);
         }
         else {
             fileID = PdfEncryption.CreateInfoId(PdfEncryption.CreateDocumentId(), true);
         }
     }
     PRIndirectReference iRoot = (PRIndirectReference)reader.trailer.Get(PdfName.ROOT);
     PdfIndirectReference root = new PdfIndirectReference(0, GetNewObjectNumber(reader, iRoot.Number, 0));
     // write the cross-reference table of the body
     body.WriteCrossReferenceTable(os, root, info, encryption, fileID, prevxref);
     if (fullCompression) {
         WriteKeyInfo(os);
         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,
         root,
         info,
         encryption,
         fileID, prevxref);
         trailer.ToPdf(this, os);
     }
     os.Flush();
     if (CloseStream)
         os.Close();
     GetCounter().Written(os.Counter);
 }
Exemplo n.º 50
0
        /**
         * Translate a PRIndirectReference to a PdfIndirectReference
         * In addition, translates the object numbers, and copies the
         * referenced object to the output file if it wasn't available
         * in the cache yet. If it's in the cache, the reference to
         * the already used stream is returned.
         *
         * NB: PRIndirectReferences (and PRIndirectObjects) really need to know what
         * file they came from, because each file has its own namespace. The translation
         * we do from their namespace to ours is *at best* heuristic, and guaranteed to
         * fail under some circumstances.
         */
        protected override PdfIndirectReference CopyIndirect(PRIndirectReference inp)
        {
            PdfObject srcObj      = PdfReader.GetPdfObjectRelease(inp);
            ByteStore streamKey   = null;
            bool      validStream = false;

            if (srcObj.IsStream())
            {
                streamKey   = new ByteStore((PRStream)srcObj);
                validStream = true;
                PdfIndirectReference streamRef;
                if (streamMap.TryGetValue(streamKey, out streamRef))
                {
                    return(streamRef);
                }
            }
            else if (srcObj.IsDictionary())
            {
                streamKey   = new ByteStore((PdfDictionary)srcObj);
                validStream = true;
                PdfIndirectReference streamRef = null;
                if (streamMap.TryGetValue(streamKey, out streamRef))
                {
                    return(streamRef);
                }
            }

            PdfIndirectReference theRef;
            RefKey             key = new RefKey(inp);
            IndirectReferences iRef;

            indirects.TryGetValue(key, out iRef);
            if (iRef != null)
            {
                theRef = iRef.Ref;
                if (iRef.Copied)
                {
                    return(theRef);
                }
            }
            else
            {
                theRef         = body.PdfIndirectReference;
                iRef           = new IndirectReferences(theRef);
                indirects[key] = iRef;
            }
            if (srcObj != null && srcObj.IsDictionary())
            {
                PdfObject type = PdfReader.GetPdfObjectRelease(((PdfDictionary)srcObj).Get(PdfName.TYPE));
                if (type != null && PdfName.PAGE.Equals(type))
                {
                    return(theRef);
                }
            }
            iRef.SetCopied();

            if (validStream)
            {
                streamMap[streamKey] = theRef;
            }

            PdfObject obj = CopyObject(srcObj);

            AddToBody(obj, theRef);
            return(theRef);
        }
Exemplo n.º 51
0
 /**
 * 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 = 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 = 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;
 }
Exemplo n.º 52
0
        /**
         * Adds documentFields.
         */

        public void AddDocumentField(PdfIndirectReference piref)
        {
            documentFields.Add(piref);
        }
Exemplo n.º 53
0
 /**
 * Adds a <CODE>PdfObject</CODE> to the body given an already existing
 * PdfIndirectReference.
 * <P>
 * This methods creates a <CODE>PdfIndirectObject</CODE> with the number given by
 * <CODE>ref</CODE>, containing the given <CODE>PdfObject</CODE>.
 * It also adds a <CODE>PdfCrossReference</CODE> for this object
 * to an <CODE>List</CODE> that will be used to build the
 * Cross-reference Table.
 *
 * @param        object          a <CODE>PdfObject</CODE>
 * @param        ref             a <CODE>PdfIndirectReference</CODE>
 * @return       a <CODE>PdfIndirectObject</CODE>
 * @throws IOException
 */
 
 internal PdfIndirectObject Add(PdfObject objecta, PdfIndirectReference refa) {
     return Add(objecta, refa.Number);
 }
        internal void Propagate(PdfObject obj, PdfIndirectReference refo, bool restricted)
        {
            if (obj == null)
            {
                return;
            }
            //        if (refo != null)
            //            AddToBody(obj, refo);
            if (obj is PdfIndirectReference)
            {
                return;
            }

            switch (obj.Type)
            {
            case PdfObject.DICTIONARY:
            case PdfObject.STREAM:
            {
                var dic = (PdfDictionary)obj;
                foreach (PdfName key in dic.Keys)
                {
                    if (restricted && (key.Equals(PdfName.Parent) || key.Equals(PdfName.Kids)))
                    {
                        continue;
                    }

                    var ob = dic.Get(key);
                    if (ob != null && ob.IsIndirect())
                    {
                        var ind = (PrIndirectReference)ob;
                        if (!SetVisited(ind) && !IsPage(ind))
                        {
                            var refi = GetNewReference(ind);
                            Propagate(PdfReader.GetPdfObjectRelease(ind), refi, restricted);
                        }
                    }
                    else
                    {
                        Propagate(ob, null, restricted);
                    }
                }
                break;
            }

            case PdfObject.ARRAY:
            {
                //PdfArray arr = new PdfArray();
                for (var it = ((PdfArray)obj).GetListIterator(); it.HasNext();)
                {
                    var ob = (PdfObject)it.Next();
                    if (ob != null && ob.IsIndirect())
                    {
                        var ind = (PrIndirectReference)ob;
                        if (!IsVisited(ind) && !IsPage(ind))
                        {
                            var refi = GetNewReference(ind);
                            Propagate(PdfReader.GetPdfObjectRelease(ind), refi, restricted);
                        }
                    }
                    else
                    {
                        Propagate(ob, null, restricted);
                    }
                }
                break;
            }

            case PdfObject.INDIRECT:
            {
                throw new Exception("Reference pointing to reference.");
            }
            }
        }
Exemplo n.º 55
0
 /**
 * Returns the CrossReferenceTable of the <CODE>Body</CODE>.
 * @param os
 * @param root
 * @param info
 * @param encryption
 * @param fileID
 * @param prevxref
 * @throws IOException
 */
 virtual public void WriteCrossReferenceTable(Stream os, PdfIndirectReference root, PdfIndirectReference info, PdfIndirectReference encryption, PdfObject fileID, long 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;
     List<int> sections = new List<int>();
     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 = 5;
         long mask = 0xff00000000L;
         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(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);
         System.Collections.IEnumerator i = xrefs.Keys;
         i.MoveNext();
         for (int k = 0; k < sections.Count; k += 2) {
             first = sections[k];
             len = 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();
             }
         }
     }
 }
        protected PdfArray BranchForm(Hashtable level, PdfIndirectReference parent, string fname)
        {
            var arr = new PdfArray();

            foreach (DictionaryEntry entry in level)
            {
                var name = (string)entry.Key;
                var obj  = entry.Value;
                var ind  = PdfIndirectReference;
                var dic  = new PdfDictionary();
                if (parent != null)
                {
                    dic.Put(PdfName.Parent, parent);
                }

                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;
                }

                if (obj is Hashtable)
                {
                    dic.Put(PdfName.Kids, BranchForm((Hashtable)obj, ind, fname2));
                    arr.Add(ind);
                    AddToBody(dic, ind);
                }
                else
                {
                    var list = (ArrayList)obj;
                    dic.MergeDifferent((PdfDictionary)list[0]);
                    if (list.Count == 3)
                    {
                        dic.MergeDifferent((PdfDictionary)list[2]);
                        var page    = (int)list[1];
                        var pageDic = (PdfDictionary)PageDics[page - 1];
                        var annots  = pageDic.GetAsArray(PdfName.Annots);
                        if (annots == null)
                        {
                            annots = new PdfArray();
                            pageDic.Put(PdfName.Annots, annots);
                        }
                        var nn = (PdfNumber)dic.Get(_iTextTag);
                        dic.Remove(_iTextTag);
                        adjustTabOrder(annots, ind, nn);
                    }
                    else
                    {
                        var kids = new PdfArray();
                        for (var k = 1; k < list.Count; k += 2)
                        {
                            var page    = (int)list[k];
                            var pageDic = (PdfDictionary)PageDics[page - 1];
                            var annots  = pageDic.GetAsArray(PdfName.Annots);
                            if (annots == null)
                            {
                                annots = new PdfArray();
                                pageDic.Put(PdfName.Annots, annots);
                            }
                            var widget = new PdfDictionary();
                            widget.Merge((PdfDictionary)list[k + 1]);
                            widget.Put(PdfName.Parent, ind);
                            var nn = (PdfNumber)widget.Get(_iTextTag);
                            widget.Remove(_iTextTag);
                            var 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);
        }
Exemplo n.º 57
0
 /**
 * Adds an object to the PDF body.
 * @param object
 * @param ref
 * @return a PdfIndirectObject
 * @throws IOException
 */
 public virtual PdfIndirectObject AddToBody(PdfObject objecta, PdfIndirectReference refa) {
     PdfIndirectObject iobj = body.Add(objecta, refa);
     return iobj;
 }
Exemplo n.º 58
0
        internal override void WriteFont(PdfWriter writer, PdfIndirectReference piRef, Object[] oParams)
        {
            if (this.writer != writer)
            {
                throw new ArgumentException(MessageLocalization.GetComposedMessage("type3.font.used.with.the.wrong.pdfwriter"));
            }
            // Get first & lastchar ...
            int firstChar = 0;

            while (firstChar < usedSlot.Length && !usedSlot[firstChar])
            {
                firstChar++;
            }

            if (firstChar == usedSlot.Length)
            {
                throw new DocumentException(MessageLocalization.GetComposedMessage("no.glyphs.defined.for.type3.font"));
            }
            int lastChar = usedSlot.Length - 1;

            while (lastChar >= firstChar && !usedSlot[lastChar])
            {
                lastChar--;
            }

            int[] widths = new int[lastChar - firstChar + 1];
            int[] invOrd = new int[lastChar - firstChar + 1];

            int invOrdIndx = 0, w = 0;

            for (int u = firstChar; u <= lastChar; u++, w++)
            {
                if (usedSlot[u])
                {
                    invOrd[invOrdIndx++] = u;
                    widths[w]            = widths3[u];
                }
            }
            PdfArray      diffs     = new PdfArray();
            PdfDictionary charprocs = new PdfDictionary();
            int           last      = -1;

            for (int k = 0; k < invOrdIndx; ++k)
            {
                int c = invOrd[k];
                if (c > last)
                {
                    last = c;
                    diffs.Add(new PdfNumber(last));
                }
                ++last;
                int    c2 = invOrd[k];
                String s  = GlyphList.UnicodeToName(c2);
                if (s == null)
                {
                    s = "a" + c2;
                }
                PdfName n = new PdfName(s);
                diffs.Add(n);
                Type3Glyph glyph;
                char2glyph.TryGetValue((char)c2, out glyph);
                PdfStream stream = new PdfStream(glyph.ToPdf(null));
                stream.FlateCompress(compressionLevel);
                PdfIndirectReference refp = writer.AddToBody(stream).IndirectReference;
                charprocs.Put(n, refp);
            }
            PdfDictionary font = new PdfDictionary(PdfName.FONT);

            font.Put(PdfName.SUBTYPE, PdfName.TYPE3);
            if (colorized)
            {
                font.Put(PdfName.FONTBBOX, new PdfRectangle(0, 0, 0, 0));
            }
            else
            {
                font.Put(PdfName.FONTBBOX, new PdfRectangle(llx, lly, urx, ury));
            }
            font.Put(PdfName.FONTMATRIX, new PdfArray(new float[] { 0.001f, 0, 0, 0.001f, 0, 0 }));
            font.Put(PdfName.CHARPROCS, writer.AddToBody(charprocs).IndirectReference);
            PdfDictionary encoding = new PdfDictionary();

            encoding.Put(PdfName.DIFFERENCES, diffs);
            font.Put(PdfName.ENCODING, writer.AddToBody(encoding).IndirectReference);
            font.Put(PdfName.FIRSTCHAR, new PdfNumber(firstChar));
            font.Put(PdfName.LASTCHAR, new PdfNumber(lastChar));
            font.Put(PdfName.WIDTHS, writer.AddToBody(new PdfArray(widths)).IndirectReference);
            if (pageResources.HasResources())
            {
                font.Put(PdfName.RESOURCES, writer.AddToBody(pageResources.Resources).IndirectReference);
            }
            writer.AddToBody(font, piRef);
        }
Exemplo n.º 59
0
    //  PDF Catalog
        
    /*
    * The Catalog is also called the root object of the document.
    * Whereas the Cross-Reference maps the objects number with the
    * byte offset so that the viewer can find the objects, the
    * Catalog tells the viewer the numbers of the objects needed
    * to render the document.
    */

        protected virtual PdfDictionary GetCatalog(PdfIndirectReference rootObj) {
            PdfDictionary catalog = pdf.GetCatalog(rootObj);
            // [F12] tagged PDF 
            BuildStructTreeRootForTagged(catalog);
            // [F13] OCG
            if (documentOCG.Count > 0)
            {
                FillOCProperties(false);
                catalog.Put(PdfName.OCPROPERTIES, OCProperties);
            }
            return catalog;
        }
Exemplo n.º 60
0
        /**
         * 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;
            }
        }