Put() публичный Метод

public Put ( PdfName key, PdfObject value ) : void
key PdfName
value PdfObject
Результат void
Пример #1
0
// ---------------------------------------------------------------------------
    public byte[] CreatePdf() {
      using (MemoryStream ms = new MemoryStream()) {    
        // step 1
        using (Document document = new Document(new Rectangle(850, 600))) {
          // step 2
          PdfWriter writer = PdfWriter.GetInstance(document, ms);
          // step 3
          document.Open();
          // step 4
          PdfContentByte canvas = writer.DirectContent;
          // add the clipped image
          Image img = Image.GetInstance(
            Path.Combine(Utility.ResourceImage, RESOURCE)
          );
          float w = img.ScaledWidth;
          float h = img.ScaledHeight;
          canvas.Ellipse(1, 1, 848, 598);
          canvas.Clip();
          canvas.NewPath();
          canvas.AddImage(img, w, 0, 0, h, 0, -600);

          // Create a transparent PdfTemplate
          PdfTemplate t2 = writer.DirectContent.CreateTemplate(850, 600);
          PdfTransparencyGroup transGroup = new PdfTransparencyGroup();
          transGroup.Put( PdfName.CS, PdfName.DEVICEGRAY);
          transGroup.Isolated = true;
          transGroup.Knockout = false;
          t2.Group = transGroup;

          // Add transparent ellipses to the template
          int gradationStep = 30;
          float[] gradationRatioList = new float[gradationStep];
          for(int i = 0; i < gradationStep; i++) {
/*
* gotta love .NET, guess they forgot to copy java.lang.Math.toRadians
*/
            double radians = (Math.PI / 180) * 90.0f / gradationStep * (i + 1);
            gradationRatioList[i] = 1 - (float) Math.Sin(radians);
          }
          for(int i = 1; i < gradationStep + 1; i++) {
              t2.SetLineWidth(5 * (gradationStep + 1 - i));
              t2.SetGrayStroke(gradationRatioList[gradationStep - i]);
              t2.Ellipse(0, 0, 850, 600);
              t2.Stroke();
          }
          
          // Create an image mask for the direct content
          PdfDictionary maskDict = new PdfDictionary();
          maskDict.Put(PdfName.TYPE, PdfName.MASK);
          maskDict.Put(PdfName.S, new PdfName("Luminosity"));
          maskDict.Put(new PdfName("G"), t2.IndirectReference);
          PdfGState gState = new PdfGState();
          gState.Put(PdfName.SMASK, maskDict );
          canvas.SetGState(gState);
          
          canvas.AddTemplate(t2, 0, 0);        
        }
        return ms.ToArray();
      }
    }
Пример #2
0
        /// <summary>
        /// Sets PDF/A Conformance ColorProfile.
        /// </summary>
        public void SetColorProfile()
        {
            if (PageSetup.ConformanceLevel == PdfXConformance.PDFXNONE) return;

            var pdfDictionary = new PdfDictionary(PdfName.OUTPUTINTENT);
            pdfDictionary.Put(PdfName.OUTPUTCONDITIONIDENTIFIER, new PdfString("sRGB IEC61966-2.1"));
            pdfDictionary.Put(PdfName.INFO, new PdfString("sRGB IEC61966-2.1"));
            pdfDictionary.Put(PdfName.S, PdfName.GTS_PDFA1);

            var profileStream = StreamHelper.GetResourceByName("PdfRpt.Core.Helper.srgb.profile");
            var pdfICCBased = new PdfICCBased(ICC_Profile.GetInstance(profileStream));
            pdfICCBased.Remove(PdfName.ALTERNATE);
            pdfDictionary.Put(PdfName.DESTOUTPUTPROFILE, PdfWriter.AddToBody(pdfICCBased).IndirectReference);

            PdfWriter.ExtraCatalog.Put(PdfName.OUTPUTINTENTS, new PdfArray(pdfDictionary));
        }
Пример #3
0
 internal void AddPage(PdfDictionary page) {
     if ((pages.Count % leafSize) == 0)
         parents.Add(writer.PdfIndirectReference);
     PdfIndirectReference parent = parents[parents.Count - 1];
     page.Put(PdfName.PARENT, parent);
     PdfIndirectReference current = writer.CurrentPage;
     writer.AddToBody(page, current);
     pages.Add(current);
 }
Пример #4
0
 internal PdfMediaClipData(String file, PdfFileSpecification fs, String mimeType) {
     Put(PdfName.TYPE,new PdfName("MediaClip"));
     Put(PdfName.S, new PdfName("MCD"));
     Put(PdfName.N, new PdfString("Media clip for "+file));
     Put(new PdfName("CT"), new PdfString(mimeType));
     PdfDictionary dic = new PdfDictionary();
     dic.Put(new PdfName("TF"), new PdfString("TEMPACCESS"));
     Put(new PdfName("P"), dic);
     Put(PdfName.D, fs.Reference);
 }
Пример #5
0
        private void addAsAttachment(IDataExporter exporter, byte[] data)
        {
            if (string.IsNullOrEmpty(exporter.FileName))
                throw new InvalidOperationException("Please fill the exporter.FileName.");

            if (string.IsNullOrEmpty(exporter.Description))
                exporter.Description = "Exported data";

            var pdfDictionary = new PdfDictionary();
            pdfDictionary.Put(PdfName.MODDATE, new PdfDate(DateTime.Now));
            var fs = PdfFileSpecification.FileEmbedded(_sharedData.PdfWriter, null, exporter.FileName, data, true, null, pdfDictionary);
            _sharedData.PdfWriter.AddFileAttachment(exporter.Description, fs);
        }
Пример #6
0
        // ---------------------------------------------------------------------------
        public void Write(Stream stream)
        {
            // step 1
              using (Document document = new Document()) {
            // step 2
            PdfWriter writer = PdfWriter.GetInstance(document, stream);
            // step 3
            document.Open();
            // step 4
            Rectangle rect = new Rectangle(100, 400, 500, 800);
            rect.Border = Rectangle.BOX;
            rect.BorderWidth = 0.5f;
            rect.BorderColor = new BaseColor(0xFF, 0x00, 0x00);
            document.Add(rect);

            PdfIndirectObject streamObject = null;
            using (FileStream fs =
              new FileStream(RESOURCE, FileMode.Open, FileAccess.Read))
            {
              PdfStream stream3D = new PdfStream(fs, writer);

              stream3D.Put(PdfName.TYPE, new PdfName("3D"));
              stream3D.Put(PdfName.SUBTYPE, new PdfName("U3D"));
              stream3D.FlateCompress();
              streamObject = writer.AddToBody(stream3D);
              stream3D.WriteLength();
            }

            PdfDictionary dict3D = new PdfDictionary();
            dict3D.Put(PdfName.TYPE, new PdfName("3DView"));
            dict3D.Put(new PdfName("XN"), new PdfString("Default"));
            dict3D.Put(new PdfName("IN"), new PdfString("Unnamed"));
            dict3D.Put(new PdfName("MS"), PdfName.M);
            dict3D.Put(
              new PdfName("C2W"),
              new PdfArray(
            new float[] { 1, 0, 0, 0, 0, -1, 0, 1, 0, 3, -235, 28 }
              )
            );
            dict3D.Put(PdfName.CO, new PdfNumber(235));

            PdfIndirectObject dictObject = writer.AddToBody(dict3D);

            PdfAnnotation annot = new PdfAnnotation(writer, rect);
            annot.Put(PdfName.CONTENTS, new PdfString("3D Model"));
            annot.Put(PdfName.SUBTYPE, new PdfName("3D"));
            annot.Put(PdfName.TYPE, PdfName.ANNOT);
            annot.Put(new PdfName("3DD"), streamObject.IndirectReference);
            annot.Put(new PdfName("3DV"), dictObject.IndirectReference);
            PdfAppearance ap = writer.DirectContent.CreateAppearance(
              rect.Width, rect.Height
            );
            annot.SetAppearance(PdfAnnotation.APPEARANCE_NORMAL, ap);
            annot.SetPage();

            writer.AddAnnotation(annot);
              }
        }
Пример #7
0
 public virtual PdfObject GetPdfObject(PdfWriter writer) {
     PdfArray array = new PdfArray(PdfName.LAB);
     PdfDictionary dictionary = new PdfDictionary();
     if (whitePoint == null
         || whitePoint.Length != 3
         || whitePoint[0] < 0.000001f || whitePoint[2] < 0.000001f
         || whitePoint[1] < 0.999999f || whitePoint[1] > 1.000001f)
         throw new Exception(MessageLocalization.GetComposedMessage("lab.cs.white.point"));
     dictionary.Put(PdfName.WHITEPOINT, new PdfArray(whitePoint));
     if (blackPoint != null) {
         if (blackPoint.Length != 3
             || blackPoint[0] < -0.000001f || blackPoint[1] < -0.000001f || blackPoint[2] < -0.000001f)
             throw new Exception(MessageLocalization.GetComposedMessage("lab.cs.black.point"));
         dictionary.Put(PdfName.BLACKPOINT, new PdfArray(blackPoint));
     }
     if (range != null) {
         if (range.Length != 4 || range[0] > range[1] || range[2] > range[3])
             throw new Exception(MessageLocalization.GetComposedMessage("lab.cs.range"));
         dictionary.Put(PdfName.RANGE, new PdfArray(range));
     }
     array.Add(dictionary);
     return array;
 }
Пример #8
0
 internal void SetOriginalResources(PdfDictionary resources, int[] newNamePtr) {
     if (newNamePtr != null)
         namePtr = newNamePtr;
     forbiddenNames = new Dictionary<PdfName,object>();
     usedNames = new Dictionary<PdfName,PdfName>();
     if (resources == null)
         return;
     originalResources = new PdfDictionary();
     originalResources.Merge(resources);
     foreach (PdfName key in resources.Keys) {
         PdfObject sub = PdfReader.GetPdfObject(resources.Get(key));
         if (sub != null && sub.IsDictionary()) {
             PdfDictionary dic = (PdfDictionary)sub;
             foreach (PdfName name in dic.Keys) {
                 forbiddenNames[name] = null;
             }
             PdfDictionary dic2 = new PdfDictionary();
             dic2.Merge(dic);
             originalResources.Put(key, dic2);
         }
     }
 }
Пример #9
0
        void Manipulate(ip.PdfDictionary element)
        {
            if (element == null)
            {
                return;
            }

            if (ip.PdfName.FIGURE.Equals(element.Get(ip.PdfName.S)))
            {
                element.Put(ip.PdfName.ALT, new ip.PdfString("Image"));
            }

            var kids = element.GetAsArray(ip.PdfName.K);

            if (kids == null)
            {
                return;
            }
            for (var i = 0; i < kids.Size; i++)
            {
                Manipulate(kids.GetAsDict(i));
            }
        }
        public void WriteOERApprovalSignature(PdfStructureElement tag)
        {
            if (this.Strategy.isIncludeOERSignature == false)
                return;

            PdfStructureElement part = new PdfStructureElement(tag, new PdfName("Part"));
            content.BeginMarkedContentSequence(part);
            content.EndMarkedContentSequence();

            helper.AddLine(2);
            helper.SetMargins(1f);
            SetWidths(signaturecolumns);
            SetColumns();

            var table = new tTable(this, "");
            table.ParentTag = part;
            table.ColumnCount = Columns.Length;

            var dict = new PdfDictionary();

            // row 1
            var cell = new tCell(0, "P", it.Element.ALIGN_LEFT, GrantFonts.BOLD, "");
            dict = new PdfDictionary();
            dict.Put(PdfName.ACTUALTEXT, new PdfString("Deputy Director OER Approval"));
            cell.Dictionary = dict;
            cell.fontSize = 6.0f;
            var row = new tRow();
            row.Add(cell);

            cell = new tCell(1, "P", it.Element.ALIGN_LEFT, GrantFonts.NORMAL, "");
            dict = new PdfDictionary();
            dict.Put(PdfName.ACTUALTEXT, new PdfString("Date "));
            cell.Dictionary = dict;
            cell.fontSize = 6.0f;
            row.Add(cell);
            table.Add(row);


            //  row 2
            row = new tRow();
            cell = new tCell();
            cell.MakeDoubleLine(0, 2);
            row.Add(cell);
            table.Add(row);


            // row 3
            row = new tRow();
            cell = new tCell(0, "P", "Deputy Director OER Approval");
            cell.isSpoken = false;
            cell.fontSize = 6.0f;
            row.Add(cell);

            cell = new tCell(1, "P", it.Element.ALIGN_LEFT, GrantFonts.NORMAL, "Date");
            cell.isSpoken = false;
            cell.fontSize = 6.0f;
            row.Add(cell);
            table.Add(row);

            table.Write();
        }
Пример #11
0
        virtual internal protected void AddFieldResources() {
            if (fieldTemplates.Count == 0)
                return;
            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);
            }
            PdfDictionary dr = (PdfDictionary)PdfReader.GetPdfObject(acroForm.Get(PdfName.DR), acroForm);
            if (dr == null) {
                dr = new PdfDictionary();
                acroForm.Put(PdfName.DR, dr);
                MarkUsed(acroForm);
            }
            MarkUsed(dr);
            foreach (PdfTemplate template in fieldTemplates) {
                PdfFormField.MergeResources(dr, (PdfDictionary)template.Resources, this);
            }
//            if (dr.Get(PdfName.ENCODING) == null)
//                dr.Put(PdfName.ENCODING, PdfName.WIN_ANSI_ENCODING);
            PdfDictionary fonts = dr.GetAsDict(PdfName.FONT);
            if (fonts == null) {
                fonts = new PdfDictionary();
                dr.Put(PdfName.FONT, fonts);
            }
            if (!fonts.Contains(PdfName.HELV)) {
                PdfDictionary dic = new PdfDictionary(PdfName.FONT);
                dic.Put(PdfName.BASEFONT, PdfName.HELVETICA);
                dic.Put(PdfName.ENCODING, PdfName.WIN_ANSI_ENCODING);
                dic.Put(PdfName.NAME, PdfName.HELV);
                dic.Put(PdfName.SUBTYPE, PdfName.TYPE1);
                fonts.Put(PdfName.HELV, AddToBody(dic).IndirectReference);
            }
            if (!fonts.Contains(PdfName.ZADB)) {
                PdfDictionary dic = new PdfDictionary(PdfName.FONT);
                dic.Put(PdfName.BASEFONT, PdfName.ZAPFDINGBATS);
                dic.Put(PdfName.NAME, PdfName.ZADB);
                dic.Put(PdfName.SUBTYPE, PdfName.TYPE1);
                fonts.Put(PdfName.ZADB, AddToBody(dic).IndirectReference);
            }
            if (acroForm.Get(PdfName.DA) == null) {
                acroForm.Put(PdfName.DA, new PdfString("/Helv 0 Tf 0 g "));
                MarkUsed(acroForm);
            }
        }
        /**
        * Writes a text line to the document. It takes care of all the attributes.
        * <P>
        * Before entering the line position must have been established and the
        * <CODE>text</CODE> argument must be in text object scope (<CODE>beginText()</CODE>).
        * @param line the line to be written
        * @param text the <CODE>PdfContentByte</CODE> where the text will be written to
        * @param graphics the <CODE>PdfContentByte</CODE> where the graphics will be written to
        * @param currentValues the current font and extra spacing values
        * @param ratio
        * @throws DocumentException on error
        */
        internal float WriteLineToContent(PdfLine line, PdfContentByte text, PdfContentByte graphics, Object[] currentValues, float ratio)  {
            PdfFont currentFont = (PdfFont)(currentValues[0]);
            float lastBaseFactor = (float)currentValues[1];
            //PdfChunk chunkz;
            int numberOfSpaces;
            int lineLen;
            bool isJustified;
            float hangingCorrection = 0;
            float hScale = 1;
            float lastHScale = float.NaN;
            float baseWordSpacing = 0;
            float baseCharacterSpacing = 0;
            float glueWidth = 0;
            float lastX = text.XTLM + line.OriginalWidth;
            
            numberOfSpaces = line.NumberOfSpaces;
            lineLen = line.GetLineLengthUtf32();
            // does the line need to be justified?
            isJustified = line.HasToBeJustified() && (numberOfSpaces != 0 || lineLen > 1);
            int separatorCount = line.GetSeparatorCount();
            if (separatorCount > 0) {
                glueWidth = line.WidthLeft / separatorCount;
            }
            else if (isJustified && separatorCount == 0) {
                if (line.NewlineSplit && line.WidthLeft >= (lastBaseFactor * (ratio * numberOfSpaces + lineLen - 1))) {
                    if (line.RTL) {
                        text.MoveText(line.WidthLeft - lastBaseFactor * (ratio * numberOfSpaces + lineLen - 1), 0);
                    }
                    baseWordSpacing = ratio * lastBaseFactor;
                    baseCharacterSpacing = lastBaseFactor;
                }
                else {
                    float width = line.WidthLeft;
                    PdfChunk last = line.GetChunk(line.Size - 1);
                    if (last != null) {
                        String s = last.ToString();
                        char c;
                        if (s.Length > 0 && hangingPunctuation.IndexOf((c = s[s.Length - 1])) >= 0) {
                            float oldWidth = width;
                            width += last.Font.Width(c) * 0.4f;
                            hangingCorrection = width - oldWidth;
                        }
                    }
                    float baseFactor = width / (ratio * numberOfSpaces + lineLen - 1);
                    baseWordSpacing = ratio * baseFactor;
                    baseCharacterSpacing = baseFactor;
                    lastBaseFactor = baseFactor;
                }
            }
            else if (line.alignment == Element.ALIGN_LEFT || line.alignment == Element.ALIGN_UNDEFINED) {
                lastX -= line.WidthLeft;
            }
            
            int lastChunkStroke = line.LastStrokeChunk;
            int chunkStrokeIdx = 0;
            float xMarker = text.XTLM;
            float baseXMarker = xMarker;
            float yMarker = text.YTLM;
            bool adjustMatrix = false;
            float tabPosition = 0;
            
            // looping over all the chunks in 1 line
            foreach (PdfChunk chunk in line) {
                if (IsTagged(writer) && chunk.accessibleElement != null) {
                    text.OpenMCBlock(chunk.accessibleElement);
                }
                BaseColor color = chunk.Color;
                float fontSize = chunk.Font.Size;
                float ascender;
                float descender;
                if (chunk.IsImage())
                {
                    ascender = chunk.Height();
                    descender = 0;
                }
                else
                {
                    ascender = chunk.Font.Font.GetFontDescriptor(BaseFont.ASCENT, fontSize);
                    descender = chunk.Font.Font.GetFontDescriptor(BaseFont.DESCENT, fontSize);
                }
                hScale = 1;
                
                if (chunkStrokeIdx <= lastChunkStroke) {
                    float width;
                    if (isJustified) {
                        width = chunk.GetWidthCorrected(baseCharacterSpacing, baseWordSpacing);
                    }
                    else {
                        width = chunk.Width();
                    }
                    if (chunk.IsStroked()) {
                        PdfChunk nextChunk = line.GetChunk(chunkStrokeIdx + 1);
                        if (chunk.IsSeparator()) {
                            width = glueWidth;
                            Object[] sep = (Object[])chunk.GetAttribute(Chunk.SEPARATOR);
                            IDrawInterface di = (IDrawInterface)sep[0];
                            bool vertical = (bool)sep[1];
                            if (vertical) {
                                di.Draw(graphics, baseXMarker, yMarker + descender, baseXMarker + line.OriginalWidth, ascender - descender, yMarker);      
                            }
                            else {
                                di.Draw(graphics, xMarker, yMarker + descender, xMarker + width, ascender - descender, yMarker);
                            }
                        }
                        if (chunk.IsTab()) {
                            if (chunk.IsAttribute(Chunk.TABSETTINGS))
                            {
                                TabStop tabStop = chunk.TabStop;
                                if (tabStop != null) {
                                    tabPosition = tabStop.Position + baseXMarker;
                                    if (tabStop.Leader != null)
                                        tabStop.Leader.Draw(graphics, xMarker, yMarker + descender, tabPosition, ascender - descender, yMarker);
                                }
                                else {
                                    tabPosition = xMarker;
                                }
                            } else {
                                //Keep deprecated tab logic for backward compatibility...
                                Object[] tab = (Object[])chunk.GetAttribute(Chunk.TAB);
                                IDrawInterface di = (IDrawInterface)tab[0];
                                tabPosition = (float)tab[1] + (float)tab[3];
                                if (tabPosition > xMarker)
                                    di.Draw(graphics, xMarker, yMarker + descender, tabPosition, ascender - descender, yMarker);
                            }
                            float tmp = xMarker;
                            xMarker = tabPosition;
                            tabPosition = tmp;
                        }
                        if (chunk.IsAttribute(Chunk.BACKGROUND)) {
                            bool inText = graphics.InText;
                            if (inText && IsTagged(writer)) {
                                graphics.EndText();
                            }
                            float subtract = lastBaseFactor;
                            if (nextChunk != null && nextChunk.IsAttribute(Chunk.BACKGROUND))
                                subtract = 0;
                            if (nextChunk == null)
                                subtract += hangingCorrection;
                            Object[] bgr = (Object[])chunk.GetAttribute(Chunk.BACKGROUND);
                            graphics.SetColorFill((BaseColor)bgr[0]);
                            float[] extra = (float[])bgr[1];
                            graphics.Rectangle(xMarker - extra[0],
                                yMarker + descender - extra[1] + chunk.TextRise,
                                width - subtract + extra[0] + extra[2],
                                ascender - descender + extra[1] + extra[3]);
                            graphics.Fill();
                            graphics.SetGrayFill(0);
                            if (inText && IsTagged(writer)) {
                                graphics.BeginText(true);
                            }
                        }
                        if (chunk.IsAttribute(Chunk.UNDERLINE) && !chunk.IsNewlineSplit()) {
                            bool inText = graphics.InText;
                            if (inText && IsTagged(writer)) {
                                graphics.EndText();
                            }
                            float subtract = lastBaseFactor;
                            if (nextChunk != null && nextChunk.IsAttribute(Chunk.UNDERLINE))
                                subtract = 0;
                            if (nextChunk == null)
                                subtract += hangingCorrection;
                            Object[][] unders = (Object[][])chunk.GetAttribute(Chunk.UNDERLINE);
                            BaseColor scolor = null;
                            for (int k = 0; k < unders.Length; ++k) {
                                Object[] obj = unders[k];
                                scolor = (BaseColor)obj[0];
                                float[] ps = (float[])obj[1];
                                if (scolor == null)
                                    scolor = color;
                                if (scolor != null)
                                    graphics.SetColorStroke(scolor);
                                graphics.SetLineWidth(ps[0] + fontSize * ps[1]);
                                float shift = ps[2] + fontSize * ps[3];
                                int cap2 = (int)ps[4];
                                if (cap2 != 0)
                                    graphics.SetLineCap(cap2);
                                graphics.MoveTo(xMarker, yMarker + shift);
                                graphics.LineTo(xMarker + width - subtract, yMarker + shift);
                                graphics.Stroke();
                                if (scolor != null)
                                    graphics.ResetGrayStroke();
                                if (cap2 != 0)
                                    graphics.SetLineCap(0);
                            }
                            graphics.SetLineWidth(1);
                            if (inText && IsTagged(writer)) {
                                graphics.BeginText(true);
                            }
                        }
                        if (chunk.IsAttribute(Chunk.ACTION))
                        {
                            float subtract = lastBaseFactor;
                            if (nextChunk != null && nextChunk.IsAttribute(Chunk.ACTION))
                                subtract = 0;
                            if (nextChunk == null)
                                subtract += hangingCorrection;
                            PdfAnnotation annot = null;
                            if (chunk.IsImage()) {
                                annot = new PdfAnnotation(writer, xMarker, yMarker + chunk.ImageOffsetY, xMarker + width - subtract, yMarker + chunk.ImageHeight + chunk.ImageOffsetY, (PdfAction)chunk.GetAttribute(Chunk.ACTION));
                            }
                            else {
                        	    annot = new PdfAnnotation(writer, xMarker, yMarker + descender + chunk.TextRise, xMarker + width - subtract, yMarker + ascender + chunk.TextRise, (PdfAction)chunk.GetAttribute(Chunk.ACTION));
                            }
                            text.AddAnnotation(annot, true);
                            if (IsTagged(writer) && chunk.accessibleElement != null) {
                                int structParent = GetStructParentIndex(annot);
                                annot.Put(PdfName.STRUCTPARENT, new PdfNumber(structParent));
                                PdfStructureElement strucElem;
                                structElements.TryGetValue(chunk.accessibleElement.ID, out strucElem);
                                if (strucElem != null) {
                                    PdfArray kArray = strucElem.GetAsArray(PdfName.K);
                                    if (kArray == null) {
                                        kArray = new PdfArray();
                                        PdfObject k = strucElem.Get(PdfName.K);
                                        if (k != null) {
                                            kArray.Add(k);
                                        }
                                        strucElem.Put(PdfName.K, kArray);
                                    }
                                    PdfDictionary dict = new PdfDictionary();
                                    dict.Put(PdfName.TYPE, PdfName.OBJR);
                                    dict.Put(PdfName.OBJ, annot.IndirectReference);
                                    kArray.Add(dict);
                                    writer.StructureTreeRoot.SetAnnotationMark(structParent, strucElem.Reference);
                                }
                            }
                        }
                        if (chunk.IsAttribute(Chunk.REMOTEGOTO)) {
                            float subtract = lastBaseFactor;
                            if (nextChunk != null && nextChunk.IsAttribute(Chunk.REMOTEGOTO))
                                subtract = 0;
                            if (nextChunk == null)
                                subtract += hangingCorrection;
                            Object[] obj = (Object[])chunk.GetAttribute(Chunk.REMOTEGOTO);
                            String filename = (String)obj[0];
                            if (obj[1] is String)
                                RemoteGoto(filename, (String)obj[1], xMarker, yMarker + descender + chunk.TextRise, xMarker + width - subtract, yMarker + ascender + chunk.TextRise);
                            else
                                RemoteGoto(filename, (int)obj[1], xMarker, yMarker + descender + chunk.TextRise, xMarker + width - subtract, yMarker + ascender + chunk.TextRise);
                        }
                        if (chunk.IsAttribute(Chunk.LOCALGOTO)) {
                            float subtract = lastBaseFactor;
                            if (nextChunk != null && nextChunk.IsAttribute(Chunk.LOCALGOTO))
                                subtract = 0;
                            if (nextChunk == null)
                                subtract += hangingCorrection;
                            LocalGoto((String)chunk.GetAttribute(Chunk.LOCALGOTO), xMarker, yMarker, xMarker + width - subtract, yMarker + fontSize);
                        }
                        if (chunk.IsAttribute(Chunk.LOCALDESTINATION)) {
                            /*float subtract = lastBaseFactor;
                            if (nextChunk != null && nextChunk.IsAttribute(Chunk.LOCALDESTINATION))
                                subtract = 0;
                            if (nextChunk == null)
                                subtract += hangingCorrection;*/
                            LocalDestination((String)chunk.GetAttribute(Chunk.LOCALDESTINATION), new PdfDestination(PdfDestination.XYZ, xMarker, yMarker + fontSize, 0));
                        }
                        if (chunk.IsAttribute(Chunk.GENERICTAG)) {
                            float subtract = lastBaseFactor;
                            if (nextChunk != null && nextChunk.IsAttribute(Chunk.GENERICTAG))
                                subtract = 0;
                            if (nextChunk == null)
                                subtract += hangingCorrection;
                            Rectangle rect = new Rectangle(xMarker, yMarker, xMarker + width - subtract, yMarker + fontSize);
                            IPdfPageEvent pev = writer.PageEvent;
                            if (pev != null)
                                pev.OnGenericTag(writer, this, rect, (String)chunk.GetAttribute(Chunk.GENERICTAG));
                        }
                        if (chunk.IsAttribute(Chunk.PDFANNOTATION)) {
                            float subtract = lastBaseFactor;
                            if (nextChunk != null && nextChunk.IsAttribute(Chunk.PDFANNOTATION))
                                subtract = 0;
                            if (nextChunk == null)
                                subtract += hangingCorrection;
                            PdfAnnotation annot = PdfFormField.ShallowDuplicate((PdfAnnotation)chunk.GetAttribute(Chunk.PDFANNOTATION));
                            annot.Put(PdfName.RECT, new PdfRectangle(xMarker, yMarker + descender, xMarker + width - subtract, yMarker + ascender));
                            text.AddAnnotation(annot, true);
                        }
                        float[] paramsx = (float[])chunk.GetAttribute(Chunk.SKEW);
                        object hs = chunk.GetAttribute(Chunk.HSCALE);
                        if (paramsx != null || hs != null) {
                            float b = 0, c = 0;
                            if (paramsx != null) {
                                b = paramsx[0];
                                c = paramsx[1];
                            }
                            if (hs != null)
                                hScale = (float)hs;
                            text.SetTextMatrix(hScale, b, c, 1, xMarker, yMarker);
                        }
                        if (!isJustified)
                        {
                            if (chunk.IsAttribute(Chunk.WORD_SPACING))
                            {
                                float ws = (float)chunk.GetAttribute(Chunk.WORD_SPACING);
                                text.SetWordSpacing(ws);
                            }
                        }

                        if (chunk.IsAttribute(Chunk.CHAR_SPACING)) {
                    	    float cs = (float) chunk.GetAttribute(Chunk.CHAR_SPACING);
						    text.SetCharacterSpacing(cs);
					    }
                        if (chunk.IsImage()) {
                            Image image = chunk.Image;
                            width = chunk.ImageWidth;
                            float[] matrix = image.GetMatrix(chunk.ImageScalePercentage);
                            matrix[Image.CX] = xMarker + chunk.ImageOffsetX - matrix[Image.CX];
                            matrix[Image.CY] = yMarker + chunk.ImageOffsetY - matrix[Image.CY];
                            graphics.AddImage(image, matrix[0], matrix[1], matrix[2], matrix[3], matrix[4], matrix[5]);
                            text.MoveText(xMarker + lastBaseFactor + chunk.ImageWidth - text.XTLM, 0);
                        }
                    }

                    xMarker += width;
                    ++chunkStrokeIdx;
                }

                if (!chunk.IsImage() && chunk.Font.CompareTo(currentFont) != 0) {
                    currentFont = chunk.Font;
                    text.SetFontAndSize(currentFont.Font, currentFont.Size);
                }
                float rise = 0;
                Object[] textRender = (Object[])chunk.GetAttribute(Chunk.TEXTRENDERMODE);
                int tr = 0;
                float strokeWidth = 1;
                BaseColor strokeColor = null;
                object fr = chunk.GetAttribute(Chunk.SUBSUPSCRIPT);
                if (textRender != null) {
                    tr = (int)textRender[0] & 3;
                    if (tr != PdfContentByte.TEXT_RENDER_MODE_FILL)
                        text.SetTextRenderingMode(tr);
                    if (tr == PdfContentByte.TEXT_RENDER_MODE_STROKE || tr == PdfContentByte.TEXT_RENDER_MODE_FILL_STROKE) {
                        strokeWidth = (float)textRender[1];
                        if (strokeWidth != 1)
                            text.SetLineWidth(strokeWidth);
                        strokeColor = (BaseColor)textRender[2];
                        if (strokeColor == null)
                            strokeColor = color;
                        if (strokeColor != null)
                            text.SetColorStroke(strokeColor);
                    }
                }
                if (fr != null)
                    rise = (float)fr;
                if (color != null)
                    text.SetColorFill(color);
                if (rise != 0)
                    text.SetTextRise(rise);
                if (chunk.IsImage()) {
                    adjustMatrix = true;
                }
                else if (chunk.IsHorizontalSeparator()) {
                    PdfTextArray array = new PdfTextArray();
                    array.Add(-glueWidth * 1000f / chunk.Font.Size / hScale);
                    text.ShowText(array);
                }
                else if (chunk.IsTab() && tabPosition != xMarker)
                {
                    PdfTextArray array = new PdfTextArray();
                    array.Add((tabPosition - xMarker) * 1000f / chunk.Font.Size / hScale);
                    text.ShowText(array);
                }
                
                // If it is a CJK chunk or Unicode TTF we will have to simulate the
                // space adjustment.
                else if (isJustified && numberOfSpaces > 0 && chunk.IsSpecialEncoding()) {
                    if (hScale != lastHScale) {
                        lastHScale = hScale;
                        text.SetWordSpacing(baseWordSpacing / hScale);
                        text.SetCharacterSpacing(baseCharacterSpacing / hScale + text.CharacterSpacing);
                    }
                    String s = chunk.ToString();
                    int idx = s.IndexOf(' ');
                    if (idx < 0)
                        text.ShowText(s);
                    else {
                        float spaceCorrection = - baseWordSpacing * 1000f / chunk.Font.Size / hScale;
                        PdfTextArray textArray = new PdfTextArray(s.Substring(0, idx));
                        int lastIdx = idx;
                        while ((idx = s.IndexOf(' ', lastIdx + 1)) >= 0) {
                            textArray.Add(spaceCorrection);
                            textArray.Add(s.Substring(lastIdx, idx - lastIdx));
                            lastIdx = idx;
                        }
                        textArray.Add(spaceCorrection);
                        textArray.Add(s.Substring(lastIdx));
                        text.ShowText(textArray);
                    }
                }
                else {
                    if (isJustified && hScale != lastHScale) {
                        lastHScale = hScale;
                        text.SetWordSpacing(baseWordSpacing / hScale);
                        text.SetCharacterSpacing(baseCharacterSpacing / hScale + text.CharacterSpacing);
                    }
                    text.ShowText(chunk.ToString());
                }
                
                if (rise != 0)
                    text.SetTextRise(0);
                if (color != null)
                    text.ResetRGBColorFill();
                if (tr != PdfContentByte.TEXT_RENDER_MODE_FILL)
                    text.SetTextRenderingMode(PdfContentByte.TEXT_RENDER_MODE_FILL);
                if (strokeColor != null)
                    text.ResetRGBColorStroke();
                if (strokeWidth != 1)
                    text.SetLineWidth(1);            
                if (chunk.IsAttribute(Chunk.SKEW) || chunk.IsAttribute(Chunk.HSCALE)) {
                    adjustMatrix = true;
                    text.SetTextMatrix(xMarker, yMarker);
                }
                if (chunk.IsAttribute(Chunk.CHAR_SPACING)) {
				    text.SetCharacterSpacing(baseCharacterSpacing);
                }
                if (chunk.IsAttribute(Chunk.WORD_SPACING)) {
                    text.SetWordSpacing(baseWordSpacing);
                }
                if (IsTagged(writer) && chunk.accessibleElement != null) {
                    text.CloseMCBlock(chunk.accessibleElement);
                }
            }
            if (isJustified) {
                text.SetWordSpacing(0);
                text.SetCharacterSpacing(0);
                if (line.NewlineSplit)
                    lastBaseFactor = 0;
            }
            if (adjustMatrix)
                text.MoveText(baseXMarker - text.XTLM, 0);
            currentValues[0] = currentFont;
            currentValues[1] = lastBaseFactor;
            return lastX;
        }
        /**
        * Makes a new page and sends it to the <CODE>PdfWriter</CODE>.
        *
        * @return a <CODE>bool</CODE>
        * @throws DocumentException on error
        */
        public override bool NewPage() {
            FlushFloatingElements();

            lastElementType = -1;
            if (PageEmpty) {
                SetNewPageSizeAndMargins();
                return false;
            }
            if (!open || close) {
                throw new Exception(MessageLocalization.GetComposedMessage("the.document.is.not.open"));
            }
            IPdfPageEvent pageEvent = writer.PageEvent;
            if (pageEvent != null)
                pageEvent.OnEndPage(writer, this);
            
            //Added to inform any listeners that we are moving to a new page (added by David Freels)
            base.NewPage();
            
            // the following 2 lines were added by Pelikan Stephan
            indentation.imageIndentLeft = 0;
            indentation.imageIndentRight = 0;
            
            // we flush the arraylist with recently written lines
            FlushLines();
            // we prepare the elements of the page dictionary
            
            // [U1] page size and rotation
            int rotation = pageSize.Rotation;
            
            // [C10]
            if (writer.IsPdfIso()) {
                if (thisBoxSize.ContainsKey("art") && thisBoxSize.ContainsKey("trim"))
                    throw new PdfXConformanceException(MessageLocalization.GetComposedMessage("only.one.of.artbox.or.trimbox.can.exist.in.the.page"));
                if (!thisBoxSize.ContainsKey("art") && !thisBoxSize.ContainsKey("trim")) {
                    if (thisBoxSize.ContainsKey("crop"))
                        thisBoxSize["trim"] = thisBoxSize["crop"];
                    else
                        thisBoxSize["trim"] = new PdfRectangle(pageSize, pageSize.Rotation);
                }
            }
            
            // [M1]
            pageResources.AddDefaultColorDiff(writer.DefaultColorspace);        
            if (writer.RgbTransparencyBlending) {
                PdfDictionary dcs = new PdfDictionary();
                dcs.Put(PdfName.CS, PdfName.DEVICERGB);
                pageResources.AddDefaultColorDiff(dcs);
            }
            PdfDictionary resources = pageResources.Resources;
            
            // we create the page dictionary
            
            PdfPage page = new PdfPage(new PdfRectangle(pageSize, rotation), thisBoxSize, resources, rotation);
            if (IsTagged(writer)) {
                page.Put(PdfName.TABS, PdfName.S);
            } else {
                page.Put(PdfName.TABS, writer.Tabs);
            }
            page.Merge(writer.PageDictEntries);
            writer.ResetPageDictEntries();

            // we complete the page dictionary
            
        	// [U3] page actions: additional actions
            if (pageAA != null) {
                page.Put(PdfName.AA, writer.AddToBody(pageAA).IndirectReference);
                pageAA = null;
            }
            
            // [C5] and [C8] we add the annotations
            if (annotationsImp.HasUnusedAnnotations()) {
                PdfArray array = annotationsImp.RotateAnnotations(writer, pageSize);
                if (array.Size != 0)
                    page.Put(PdfName.ANNOTS, array);
            }
            
            // [F12] we add tag info
            if (IsTagged(writer))
                page.Put(PdfName.STRUCTPARENTS, new PdfNumber(GetStructParentIndex(writer.CurrentPage)));

             if (text.Size > textEmptySize || IsTagged(writer))
                text.EndText();
            else
                text = null;
             IList<IAccessibleElement> mcBlocks = null;
             if (IsTagged(writer)) {
                 mcBlocks = writer.DirectContent.SaveMCBlocks();
             }
            writer.Add(page, new PdfContents(writer.DirectContentUnder, graphics, !IsTagged(writer) ? text : null, writer.DirectContent, pageSize));
            // we initialize the new page
            InitPage();
            if (IsTagged(writer)) {
                writer.DirectContentUnder.RestoreMCBlocks(mcBlocks);
            }
            return true;
        }
Пример #14
0
 private void AddASEvent(PdfName eventa, PdfName category) {
     PdfArray arr = new PdfArray();
     foreach (PdfLayer layer in documentOCG.Keys) {
         PdfDictionary usage = layer.GetAsDict(PdfName.USAGE);
         if (usage != null && usage.Get(category) != null)
             arr.Add(layer.Ref);
     }
     if (arr.Size == 0)
         return;
     PdfDictionary d = vOCProperties.GetAsDict(PdfName.D);
     PdfArray arras = d.GetAsArray(PdfName.AS);
     if (arras == null) {
         arras = new PdfArray();
         d.Put(PdfName.AS, arras);
     }
     PdfDictionary asa = new PdfDictionary();
     asa.Put(PdfName.EVENT, eventa);
     asa.Put(PdfName.CATEGORY, new PdfArray(category));
     asa.Put(PdfName.OCGS, arr);
     arras.Add(asa);
 }
        /**
         * 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);
        }
Пример #16
0
        internal void MergeField(String name, AcroFields.Item item)
        {
            Dictionary <string, object> map = fieldTree;
            StringTokenizer             tk  = new StringTokenizer(name, ".");

            if (!tk.HasMoreTokens())
            {
                return;
            }
            while (true)
            {
                String s = tk.NextToken();
                Object obj;
                map.TryGetValue(s, out obj);
                if (tk.HasMoreTokens())
                {
                    if (obj == null)
                    {
                        obj    = new Dictionary <string, object>();
                        map[s] = obj;
                        map    = (Dictionary <string, object>)obj;
                        continue;
                    }
                    else if (obj is Dictionary <string, object> )
                    {
                        map = (Dictionary <string, object>)obj;
                    }
                    else
                    {
                        return;
                    }
                }
                else
                {
                    if (obj is Dictionary <string, object> )
                    {
                        return;
                    }
                    PdfDictionary merged = item.GetMerged(0);
                    if (obj == null)
                    {
                        PdfDictionary field = new PdfDictionary();
                        if (PdfName.SIG.Equals(merged.Get(PdfName.FT)))
                        {
                            hasSignature = true;
                        }
                        foreach (PdfName key in merged.Keys)
                        {
                            if (fieldKeys.ContainsKey(key))
                            {
                                field.Put(key, merged.Get(key));
                            }
                        }
                        List <object> list = new List <object>();
                        list.Add(field);
                        CreateWidgets(list, item);
                        map[s] = list;
                    }
                    else
                    {
                        List <object> list  = (List <object>)obj;
                        PdfDictionary field = (PdfDictionary)list[0];
                        PdfName       type1 = (PdfName)field.Get(PdfName.FT);
                        PdfName       type2 = (PdfName)merged.Get(PdfName.FT);
                        if (type1 == null || !type1.Equals(type2))
                        {
                            return;
                        }
                        int       flag1 = 0;
                        PdfObject f1    = field.Get(PdfName.FF);
                        if (f1 != null && f1.IsNumber())
                        {
                            flag1 = ((PdfNumber)f1).IntValue;
                        }
                        int       flag2 = 0;
                        PdfObject f2    = merged.Get(PdfName.FF);
                        if (f2 != null && f2.IsNumber())
                        {
                            flag2 = ((PdfNumber)f2).IntValue;
                        }
                        if (type1.Equals(PdfName.BTN))
                        {
                            if (((flag1 ^ flag2) & PdfFormField.FF_PUSHBUTTON) != 0)
                            {
                                return;
                            }
                            if ((flag1 & PdfFormField.FF_PUSHBUTTON) == 0 && ((flag1 ^ flag2) & PdfFormField.FF_RADIO) != 0)
                            {
                                return;
                            }
                        }
                        else if (type1.Equals(PdfName.CH))
                        {
                            if (((flag1 ^ flag2) & PdfFormField.FF_COMBO) != 0)
                            {
                                return;
                            }
                        }
                        CreateWidgets(list, item);
                    }
                    return;
                }
            }
        }
Пример #17
0
 /**
  * Adds some <CODE>PdfContents</CODE> to this Writer.
  * <P>
  * The document has to be open before you can begin to add content
  * to the body of the document.
  *
  * @return a <CODE>PdfIndirectReference</CODE>
  * @param page the <CODE>PdfPage</CODE> to add
  * @param contents the <CODE>PdfContents</CODE> of the page
  * @throws PdfException on error
  */
  internal virtual PdfIndirectReference Add(PdfPage page, PdfContents contents) {
      if (!open) {
          throw new PdfException(MessageLocalization.GetComposedMessage("the.document.is.not.open"));
      }
      PdfIndirectObject objecta;
      objecta = AddToBody(contents);
      page.Add(objecta.IndirectReference);
      if (group != null) {
          page.Put(PdfName.GROUP, group);
          group = null;
      }
      else if (rgbTransparencyBlending) {
          PdfDictionary pp = new PdfDictionary();
          pp.Put(PdfName.TYPE, PdfName.GROUP);
          pp.Put(PdfName.S, PdfName.TRANSPARENCY);
          pp.Put(PdfName.CS, PdfName.DEVICERGB);
          page.Put(PdfName.GROUP, pp);
      }
      root.AddPage(page);
      currentPageNumber++;
      return null;
  }
Пример #18
0
            public void AlterContents()
            {
                if (over == null && under == null)
                {
                    return;
                }
                PdfArray  ar      = null;
                PdfObject content = PdfReader.GetPdfObject(pageN.Get(PdfName.CONTENTS), pageN);

                if (content == null)
                {
                    ar = new PdfArray();
                    pageN.Put(PdfName.CONTENTS, ar);
                }
                else if (content.IsArray())
                {
                    ar = (PdfArray)content;
                }
                else if (content.IsStream())
                {
                    ar = new PdfArray();
                    ar.Add(pageN.Get(PdfName.CONTENTS));
                    pageN.Put(PdfName.CONTENTS, ar);
                }
                else
                {
                    ar = new PdfArray();
                    pageN.Put(PdfName.CONTENTS, ar);
                }
                ByteBuffer out_p = new ByteBuffer();

                if (under != null)
                {
                    out_p.Append(PdfContents.SAVESTATE);
                    ApplyRotation(pageN, out_p);
                    out_p.Append(under.InternalBuffer);
                    out_p.Append(PdfContents.RESTORESTATE);
                }
                if (over != null)
                {
                    out_p.Append(PdfContents.SAVESTATE);
                }
                PdfStream stream = new PdfStream(out_p.ToByteArray());

                stream.FlateCompress(cstp.CompressionLevel);
                PdfIndirectReference ref1 = cstp.AddToBody(stream).IndirectReference;

                ar.AddFirst(ref1);
                out_p.Reset();
                if (over != null)
                {
                    out_p.Append(' ');
                    out_p.Append(PdfContents.RESTORESTATE);
                    out_p.Append(PdfContents.SAVESTATE);
                    ApplyRotation(pageN, out_p);
                    out_p.Append(over.InternalBuffer);
                    out_p.Append(PdfContents.RESTORESTATE);
                    stream = new PdfStream(out_p.ToByteArray());
                    stream.FlateCompress(cstp.CompressionLevel);
                    ar.Add(cstp.AddToBody(stream).IndirectReference);
                }
                pageN.Put(PdfName.RESOURCES, pageResources.Resources);
            }
Пример #19
0
        virtual 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
                    {
                        PdfDictionary field = (PdfDictionary)list[0];
                        PdfName       v     = field.GetAsName(PdfName.V);
                        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);
                            if (PdfCopy.IsCheckButton(field))
                            {
                                PdfName _as = widget.GetAsName(PdfName.AS);
                                if (v != null && _as != null)
                                {
                                    widget.Put(PdfName.AS, v);
                                }
                            }
                            else if (PdfCopy.IsRadioButton(field))
                            {
                                PdfName _as = widget.GetAsName(PdfName.AS);
                                if (v != null && _as != null && !_as.Equals(GetOffStateName(widget)))
                                {
                                    if (!mergedRadioButtons.ContainsKey(list))
                                    {
                                        mergedRadioButtons[list] = null;
                                        widget.Put(PdfName.AS, v);
                                    }
                                    else
                                    {
                                        widget.Put(PdfName.AS, GetOffStateName(widget));
                                    }
                                }
                            }
                            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);
        }
Пример #20
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);
        }
Пример #21
0
        public static Object[] IterateOutlines(PdfWriter writer, PdfIndirectReference parent, IList <Dictionary <String, Object> > 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 (Dictionary <String, Object> map in kids)
            {
                Object[] lower = null;
                IList <Dictionary <String, Object> > subKid = null;
                if (map.ContainsKey("Kids"))
                {
                    subKid = (IList <Dictionary <String, Object> >)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 (map.ContainsKey("Open") && "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 = null;
                if (map.ContainsKey("Color"))
                {
                    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 = GetVal(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 });
        }
Пример #22
0
 internal static void CreateOutlineAction(PdfDictionary outline, Dictionary <String, Object> map, PdfWriter writer, bool namedAsNames)
 {
     try {
         String action = GetVal(map, "Action");
         if ("GoTo".Equals(action))
         {
             String p;
             if ((p = GetVal(map, "Named")) != null)
             {
                 if (namedAsNames)
                 {
                     outline.Put(PdfName.DEST, new PdfName(p));
                 }
                 else
                 {
                     outline.Put(PdfName.DEST, new PdfString(p, null));
                 }
             }
             else if ((p = GetVal(map, "Page")) != null)
             {
                 PdfArray        ar = new PdfArray();
                 StringTokenizer tk = new StringTokenizer(p);
                 int             n  = int.Parse(tk.NextToken());
                 ar.Add(writer.GetPageReference(n));
                 if (!tk.HasMoreTokens())
                 {
                     ar.Add(PdfName.XYZ);
                     ar.Add(new float[] { 0, 10000, 0 });
                 }
                 else
                 {
                     String fn = tk.NextToken();
                     if (fn.StartsWith("/"))
                     {
                         fn = fn.Substring(1);
                     }
                     ar.Add(new PdfName(fn));
                     for (int k = 0; k < 4 && tk.HasMoreTokens(); ++k)
                     {
                         fn = tk.NextToken();
                         if (fn.Equals("null"))
                         {
                             ar.Add(PdfNull.PDFNULL);
                         }
                         else
                         {
                             ar.Add(new PdfNumber(fn));
                         }
                     }
                 }
                 outline.Put(PdfName.DEST, ar);
             }
         }
         else if ("GoToR".Equals(action))
         {
             String        p;
             PdfDictionary dic = new PdfDictionary();
             if ((p = GetVal(map, "Named")) != null)
             {
                 dic.Put(PdfName.D, new PdfString(p, null));
             }
             else if ((p = GetVal(map, "NamedN")) != null)
             {
                 dic.Put(PdfName.D, new PdfName(p));
             }
             else if ((p = GetVal(map, "Page")) != null)
             {
                 PdfArray        ar = new PdfArray();
                 StringTokenizer tk = new StringTokenizer(p);
                 ar.Add(new PdfNumber(tk.NextToken()));
                 if (!tk.HasMoreTokens())
                 {
                     ar.Add(PdfName.XYZ);
                     ar.Add(new float[] { 0, 10000, 0 });
                 }
                 else
                 {
                     String fn = tk.NextToken();
                     if (fn.StartsWith("/"))
                     {
                         fn = fn.Substring(1);
                     }
                     ar.Add(new PdfName(fn));
                     for (int k = 0; k < 4 && tk.HasMoreTokens(); ++k)
                     {
                         fn = tk.NextToken();
                         if (fn.Equals("null"))
                         {
                             ar.Add(PdfNull.PDFNULL);
                         }
                         else
                         {
                             ar.Add(new PdfNumber(fn));
                         }
                     }
                 }
                 dic.Put(PdfName.D, ar);
             }
             String file = GetVal(map, "File");
             if (dic.Size > 0 && file != null)
             {
                 dic.Put(PdfName.S, PdfName.GOTOR);
                 dic.Put(PdfName.F, new PdfString(file));
                 String nw = GetVal(map, "NewWindow");
                 if (nw != null)
                 {
                     if (nw.Equals("true"))
                     {
                         dic.Put(PdfName.NEWWINDOW, PdfBoolean.PDFTRUE);
                     }
                     else if (nw.Equals("false"))
                     {
                         dic.Put(PdfName.NEWWINDOW, PdfBoolean.PDFFALSE);
                     }
                 }
                 outline.Put(PdfName.A, dic);
             }
         }
         else if ("URI".Equals(action))
         {
             String uri = GetVal(map, "URI");
             if (uri != null)
             {
                 PdfDictionary dic = new PdfDictionary();
                 dic.Put(PdfName.S, PdfName.URI);
                 dic.Put(PdfName.URI, new PdfString(uri));
                 outline.Put(PdfName.A, dic);
             }
         }
         else if ("JS".Equals(action))
         {
             String code = GetVal(map, "Code");
             if (code != null)
             {
                 outline.Put(PdfName.A, PdfAction.JavaScript(code, writer));
             }
         }
         else if ("Launch".Equals(action))
         {
             String file = GetVal(map, "File");
             if (file != null)
             {
                 PdfDictionary dic = new PdfDictionary();
                 dic.Put(PdfName.S, PdfName.LAUNCH);
                 dic.Put(PdfName.F, new PdfString(file));
                 outline.Put(PdfName.A, dic);
             }
         }
     }
     catch  {
         // empty on purpose
     }
 }
Пример #23
0
        virtual internal protected void Close(IDictionary<String, String> moreInfo) {
            if (closed) {
                return;
            }
            if (useVp) {
                SetViewerPreferences();
            }
            if (flat) {
                FlatFields();
            }
            if (flatFreeText) {
                FlatFreeTextFields();
            }
            if (flatannotations) {
                FlattenAnnotations();
            }
            AddFieldResources();
            PdfDictionary catalog = reader.Catalog;
            GetPdfVersion().AddToCatalog(catalog);
            PdfDictionary acroForm = (PdfDictionary)PdfReader.GetPdfObject(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);
                    MarkUsed(catalog);
                }
            }
            closed = true;
            AddSharedObjectsToBody();
            SetOutlines();
            SetJavaScript();
            AddFileAttachments();
            // [C11] Output Intents
            if (extraCatalog != null) {
                catalog.MergeDifferent(extraCatalog);
            }
            if (openAction != null) {
                catalog.Put(PdfName.OPENACTION, openAction);
            }
            if (pdf.pageLabels != null) {
                catalog.Put(PdfName.PAGELABELS, pdf.pageLabels.GetDictionary(this));
            }
            // OCG
            if (documentOCG.Count > 0) {
                FillOCProperties(false);
                PdfDictionary ocdict = catalog.GetAsDict(PdfName.OCPROPERTIES);
                if (ocdict == null) {
                    reader.Catalog.Put(PdfName.OCPROPERTIES, OCProperties);
                }
                else {
                    ocdict.Put(PdfName.OCGS, OCProperties.Get(PdfName.OCGS));
                    PdfDictionary ddict = ocdict.GetAsDict(PdfName.D);
                    if (ddict == null) {
                        ddict = new PdfDictionary();
                        ocdict.Put(PdfName.D, ddict);
                    }
                    ddict.Put(PdfName.ORDER, OCProperties.GetAsDict(PdfName.D).Get(PdfName.ORDER));
                    ddict.Put(PdfName.RBGROUPS, OCProperties.GetAsDict(PdfName.D).Get(PdfName.RBGROUPS));
                    ddict.Put(PdfName.OFF, OCProperties.GetAsDict(PdfName.D).Get(PdfName.OFF));
                    ddict.Put(PdfName.AS, OCProperties.GetAsDict(PdfName.D).Get(PdfName.AS));
                }
                PdfWriter.CheckPdfIsoConformance(this, PdfIsoKeys.PDFISOKEY_LAYER, OCProperties);
            }
            // metadata
            int skipInfo = -1;
            PdfIndirectReference iInfo = reader.Trailer.GetAsIndirectObject(PdfName.INFO);
            if (iInfo != null) {
                skipInfo = iInfo.Number;
            }
            PdfDictionary oldInfo = reader.Trailer.GetAsDict(PdfName.INFO);
            String producer = null;
            if (oldInfo != null && oldInfo.Get(PdfName.PRODUCER) != null) {
                producer = oldInfo.GetAsString(PdfName.PRODUCER).ToUnicodeString();
            }
            Version version = Version.GetInstance();
            if (producer == null || version.GetVersion.IndexOf(version.Product) == -1) {
                producer = version.GetVersion;
            } else {
                int idx = producer.IndexOf("; modified using");
                StringBuilder buf;
                if (idx == -1)
                    buf = new StringBuilder(producer);
                else
                    buf = new StringBuilder(producer.Substring(0, idx));
                buf.Append("; modified using ");
                buf.Append(version.GetVersion);
                producer = buf.ToString();
            }
            PdfIndirectReference info = null;
            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 (KeyValuePair<string,string> entry in moreInfo) {
                    PdfName keyName = new PdfName(entry.Key);
                    String value = entry.Value;
                    if (value == null)
                        newInfo.Remove(keyName);
                    else
                        newInfo.Put(keyName, new PdfString(value, PdfObject.TEXT_UNICODE));
                }
            }
            PdfDate date = new PdfDate();
            newInfo.Put(PdfName.MODDATE, date);
            newInfo.Put(PdfName.PRODUCER, new PdfString(producer, PdfObject.TEXT_UNICODE));
            if (append) {
                if (iInfo == null) {
                    info = AddToBody(newInfo, false).IndirectReference;
                } else {
                    info = AddToBody(newInfo, iInfo.Number, false).IndirectReference;
                }
            } else {
                info = AddToBody(newInfo, false).IndirectReference;
            }
            // XMP
            byte[] altMetadata = null;
            PdfObject xmpo = PdfReader.GetPdfObject(catalog.Get(PdfName.METADATA));
            if (xmpo != null && xmpo.IsStream()) {
                altMetadata = PdfReader.GetStreamBytesRaw((PRStream)xmpo);
                PdfReader.KillIndirect(catalog.Get(PdfName.METADATA));
            }
            PdfStream xmp = null;
            if (xmpMetadata != null) {
                altMetadata = xmpMetadata;
            } else if (xmpWriter != null) {
                try {
                    MemoryStream baos = new MemoryStream();
                    PdfProperties.SetProducer(xmpWriter.XmpMeta, producer);
                    XmpBasicProperties.SetModDate(xmpWriter.XmpMeta, date.GetW3CDate());
                    XmpBasicProperties.SetMetaDataDate(xmpWriter.XmpMeta, date.GetW3CDate());
                    xmpWriter.Serialize(baos);
                    xmpWriter.Close();
                    xmp = new PdfStream(baos.ToArray());
                } catch (XmpException) {
                    xmpWriter = null;
                }
            }
            if (xmp == null && altMetadata != null) {
                try {
                    MemoryStream baos = new MemoryStream();
                    if (moreInfo == null || xmpMetadata != null) {
                        IXmpMeta xmpMeta = XmpMetaFactory.ParseFromBuffer(altMetadata);

                        PdfProperties.SetProducer(xmpMeta, producer);
                        XmpBasicProperties.SetModDate(xmpMeta, date.GetW3CDate());
                        XmpBasicProperties.SetMetaDataDate(xmpMeta, date.GetW3CDate());

                        SerializeOptions serializeOptions = new SerializeOptions();
                        serializeOptions.Padding = 2000;
                        XmpMetaFactory.Serialize(xmpMeta, baos, serializeOptions);
                    } else {
                        XmpWriter xmpw = CreateXmpWriter(baos, newInfo);
                        xmpw.Close();
                    }
                    xmp = new PdfStream(baos.ToArray());
                } catch (XmpException) {
                    xmp = new PdfStream(altMetadata);
                } catch (IOException) {
                    xmp = new PdfStream(altMetadata);
                }
            }
            if (xmp != null) {
                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);
                }
                if (append && xmpo != null) {
                    body.Add(xmp, xmpo.IndRef);
                }
                else {
                    catalog.Put(PdfName.METADATA, body.Add(xmp).IndirectReference);
                    MarkUsed(catalog);
                }
            }
            Close(info, skipInfo);
        }
Пример #24
0
        void ManipulatePdf(string src, string dest, MetaData md)
        {
            using (var reader = new ip.PdfReader(src))
            {
                var catalog        = reader.Catalog;
                var structTreeRoot = catalog.GetAsDict(ip.PdfName.STRUCTTREEROOT);

                Manipulate(structTreeRoot);
                using (var stamper = new ip.PdfStamper(reader, new FileStream(dest, FileMode.Create)))
                {
                    var page = reader.GetPageN(1);
                    using (var ms = new MemoryStream())
                    {
                        var dic = new ip.PdfDictionary();

                        DateTime time = DateTime.Now;

                        if (reader.Info.ContainsKey(ip.PdfName.CREATIONDATE.ToString().Substring(1)))
                        {
                            var temp = reader.Info[ip.PdfName.CREATIONDATE.ToString().Substring(1)].Substring(2).Replace('\'', ':');
                            temp = temp.Substring(0, temp.Length - 1);
                            time = DateTime.ParseExact(temp, "yyyyMMddHHmmsszzz", CultureInfo.InvariantCulture);
                        }

                        dic.Put(ip.PdfName.PRODUCER, new ip.PdfString(md.Creator));
                        dic.Put(ip.PdfName.TITLE, new ip.PdfString(Path.GetFileNameWithoutExtension(dest)));
                        dic.Put(ip.PdfName.CREATOR, new ip.PdfString(md.Creator));
                        dic.Put(ip.PdfName.AUTHOR, new ip.PdfString(md.Author));
                        dic.Put(ip.PdfName.CREATIONDATE, new ip.PdfDate(time));


                        var xmp = new XmpWriter(ms, dic);
                        xmp.Close();
                        var reference = stamper.Writer.AddToBody(new ip.PdfStream(ms.ToArray()));
                        page.Put(ip.PdfName.METADATA, reference.IndirectReference);

                        if (ms != null)
                        {
                            var d   = Encoding.UTF8.GetString(ms.ToArray());
                            var xml = new XmlDocument();
                            xml.LoadXml(d);
                            var node = xml.DocumentElement.FirstChild;
                            node = node.FirstChild;

                            if (node != null)
                            {
                                //node.AppendAttribute("xmlns:pdfaid", "http://www.aiim.org/pdfa/ns/id/");
                                var attrId = xml.CreateAttribute("xmlns:pdfaid");
                                attrId.Value = "http://www.aiim.org/pdfa/ns/id/";
                                node.Attributes.Append(attrId);

                                var attrPart = xml.CreateAttribute("pdfaid:part", "http://www.aiim.org/pdfa/ns/id/");
                                attrPart.Value = "1";
                                node.Attributes.Append(attrPart);

                                var attrConf = xml.CreateAttribute("pdfaid:conformance", "http://www.aiim.org/pdfa/ns/id/");
                                attrConf.Value = "A";
                                node.Attributes.Append(attrConf);

                                if (md.CustomMetadata != null && md.CustomMetadata.Length > 0)
                                {
                                    var dataNode = node.OwnerDocument.CreateElement("CustomMetaData");
                                    node.AppendChild(dataNode);
                                    dataNode.InnerText = System.Convert.ToBase64String(md.CustomMetadata);
                                }
                            }

                            ms.Position = 0;
                            xml.Save(ms);
                            d = Encoding.UTF8.GetString(ms.ToArray());
                        }

                        stamper.XmpMetadata = ms.ToArray();

                        stamper.Close();
                        reader.Close();
                    }
                }
            }
        }
Пример #25
0
 private static void MoveRectangle(PdfDictionary dic2, PdfReader r, int pageImported, PdfName key, String name) {
     Rectangle m = r.GetBoxSize(pageImported, name);
     if (m == null)
         dic2.Remove(key);
     else
         dic2.Put(key, new PdfRectangle(m));
 }
Пример #26
0
        internal void MergeField(string name, AcroFields.Item item)
        {
            Hashtable       map = FieldTree;
            StringTokenizer tk  = new StringTokenizer(name, ".");

            if (!tk.HasMoreTokens())
            {
                return;
            }
            while (true)
            {
                string s   = tk.NextToken();
                object obj = map[s];
                if (tk.HasMoreTokens())
                {
                    if (obj == null)
                    {
                        obj    = new Hashtable();
                        map[s] = obj;
                        map    = (Hashtable)obj;
                        continue;
                    }
                    else if (obj is Hashtable)
                    {
                        map = (Hashtable)obj;
                    }
                    else
                    {
                        return;
                    }
                }
                else
                {
                    if (obj is Hashtable)
                    {
                        return;
                    }
                    PdfDictionary merged = item.GetMerged(0);
                    if (obj == null)
                    {
                        PdfDictionary field = new PdfDictionary();
                        if (PdfName.Sig.Equals(merged.Get(PdfName.Ft)))
                        {
                            _hasSignature = true;
                        }
                        foreach (PdfName key in merged.Keys)
                        {
                            if (FieldKeys.ContainsKey(key))
                            {
                                field.Put(key, merged.Get(key));
                            }
                        }
                        ArrayList list = new ArrayList();
                        list.Add(field);
                        CreateWidgets(list, item);
                        map[s] = list;
                    }
                    else
                    {
                        ArrayList     list  = (ArrayList)obj;
                        PdfDictionary field = (PdfDictionary)list[0];
                        PdfName       type1 = (PdfName)field.Get(PdfName.Ft);
                        PdfName       type2 = (PdfName)merged.Get(PdfName.Ft);
                        if (type1 == null || !type1.Equals(type2))
                        {
                            return;
                        }
                        int       flag1 = 0;
                        PdfObject f1    = field.Get(PdfName.Ff);
                        if (f1 != null && f1.IsNumber())
                        {
                            flag1 = ((PdfNumber)f1).IntValue;
                        }
                        int       flag2 = 0;
                        PdfObject f2    = merged.Get(PdfName.Ff);
                        if (f2 != null && f2.IsNumber())
                        {
                            flag2 = ((PdfNumber)f2).IntValue;
                        }
                        if (type1.Equals(PdfName.Btn))
                        {
                            if (((flag1 ^ flag2) & PdfFormField.FF_PUSHBUTTON) != 0)
                            {
                                return;
                            }
                            if ((flag1 & PdfFormField.FF_PUSHBUTTON) == 0 && ((flag1 ^ flag2) & PdfFormField.FF_RADIO) != 0)
                            {
                                return;
                            }
                        }
                        else if (type1.Equals(PdfName.Ch))
                        {
                            if (((flag1 ^ flag2) & PdfFormField.FF_COMBO) != 0)
                            {
                                return;
                            }
                        }
                        CreateWidgets(list, item);
                    }
                    return;
                }
            }
        }
Пример #27
0
 protected internal void WriteOutlines(PdfDictionary catalog, bool namedAsNames) {
     if (newBookmarks == null || newBookmarks.Count == 0)
         return;
     PdfDictionary top = new PdfDictionary();
     PdfIndirectReference topRef = this.PdfIndirectReference;
     Object[] kids = SimpleBookmark.IterateOutlines(this, topRef, newBookmarks, namedAsNames);
     top.Put(PdfName.FIRST, (PdfIndirectReference)kids[0]);
     top.Put(PdfName.LAST, (PdfIndirectReference)kids[1]);
     top.Put(PdfName.COUNT, new PdfNumber((int)kids[2]));
     AddToBody(top, topRef);
     catalog.Put(PdfName.OUTLINES, topRef);
 }
Пример #28
0
        private void OutputDss(PdfDictionary dss, PdfDictionary vrim, PdfArray ocsps, PdfArray crls, PdfArray certs)
        {
            PdfDictionary catalog = reader.Catalog;

            writer.MarkUsed(catalog);
            foreach (PdfName vkey in validated.Keys)
            {
                PdfArray      ocsp = new PdfArray();
                PdfArray      crl  = new PdfArray();
                PdfArray      cert = new PdfArray();
                PdfDictionary vri  = new PdfDictionary();
                foreach (byte[] b in validated[vkey].crls)
                {
                    PdfStream ps = new PdfStream(b);
                    ps.FlateCompress();
                    PdfIndirectReference iref = writer.AddToBody(ps, false).IndirectReference;
                    crl.Add(iref);
                    crls.Add(iref);
                }
                foreach (byte[] b in validated[vkey].ocsps)
                {
                    PdfStream ps = new PdfStream(b);
                    ps.FlateCompress();
                    PdfIndirectReference iref = writer.AddToBody(ps, false).IndirectReference;
                    ocsp.Add(iref);
                    ocsps.Add(iref);
                }
                foreach (byte[] b in validated[vkey].certs)
                {
                    PdfStream ps = new PdfStream(b);
                    ps.FlateCompress();
                    PdfIndirectReference iref = writer.AddToBody(ps, false).IndirectReference;
                    cert.Add(iref);
                    certs.Add(iref);
                }
                if (ocsp.Size > 0)
                {
                    vri.Put(PdfName.OCSP, writer.AddToBody(ocsp, false).IndirectReference);
                }
                if (crl.Size > 0)
                {
                    vri.Put(PdfName.CRL, writer.AddToBody(crl, false).IndirectReference);
                }
                if (cert.Size > 0)
                {
                    vri.Put(PdfName.CERT, writer.AddToBody(cert, false).IndirectReference);
                }
                vrim.Put(vkey, writer.AddToBody(vri, false).IndirectReference);
            }
            dss.Put(PdfName.VRI, writer.AddToBody(vrim, false).IndirectReference);
            if (ocsps.Size > 0)
            {
                dss.Put(PdfName.OCSPS, writer.AddToBody(ocsps, false).IndirectReference);
            }
            if (crls.Size > 0)
            {
                dss.Put(PdfName.CRLS, writer.AddToBody(crls, false).IndirectReference);
            }
            if (certs.Size > 0)
            {
                dss.Put(PdfName.CERTS, writer.AddToBody(certs, false).IndirectReference);
            }
            catalog.Put(PdfName.DSS, writer.AddToBody(dss, false).IndirectReference);
        }
Пример #29
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;
 }
Пример #30
0
        protected PdfArray BranchForm(Hashtable level, PdfIndirectReference parent, string fname)
        {
            PdfArray arr = new PdfArray();

            foreach (DictionaryEntry entry in level)
            {
                string name = (string)entry.Key;
                object obj  = entry.Value;
                PdfIndirectReference ind = PdfIndirectReference;
                PdfDictionary        dic = new PdfDictionary();
                if (parent != null)
                {
                    dic.Put(PdfName.Parent, parent);
                }
                dic.Put(PdfName.T, new PdfString(name, PdfObject.TEXT_UNICODE));
                string fname2 = $"{fname}.{name}";
                int    coidx  = _calculationOrder.IndexOf(fname2);
                if (coidx >= 0)
                {
                    _calculationOrderRefs[coidx] = ind;
                }
                if (obj is Hashtable)
                {
                    dic.Put(PdfName.Kids, BranchForm((Hashtable)obj, ind, fname2));
                    arr.Add(ind);
                    AddToBody(dic, ind);
                }
                else
                {
                    ArrayList list = (ArrayList)obj;
                    dic.MergeDifferent((PdfDictionary)list[0]);
                    if (list.Count == 3)
                    {
                        dic.MergeDifferent((PdfDictionary)list[2]);
                        int           page    = (int)list[1];
                        PdfDictionary pageDic = (PdfDictionary)PageDics[page - 1];
                        PdfArray      annots  = pageDic.GetAsArray(PdfName.Annots);
                        if (annots == null)
                        {
                            annots = new PdfArray();
                            pageDic.Put(PdfName.Annots, annots);
                        }
                        PdfNumber nn = (PdfNumber)dic.Get(_iTextTag);
                        dic.Remove(_iTextTag);
                        adjustTabOrder(annots, ind, nn);
                    }
                    else
                    {
                        PdfArray kids = new PdfArray();
                        for (int k = 1; k < list.Count; k += 2)
                        {
                            int           page    = (int)list[k];
                            PdfDictionary pageDic = (PdfDictionary)PageDics[page - 1];
                            PdfArray      annots  = pageDic.GetAsArray(PdfName.Annots);
                            if (annots == null)
                            {
                                annots = new PdfArray();
                                pageDic.Put(PdfName.Annots, annots);
                            }
                            PdfDictionary widget = new PdfDictionary();
                            widget.Merge((PdfDictionary)list[k + 1]);
                            widget.Put(PdfName.Parent, ind);
                            PdfNumber nn = (PdfNumber)widget.Get(_iTextTag);
                            widget.Remove(_iTextTag);
                            PdfIndirectReference wref = AddToBody(widget).IndirectReference;
                            adjustTabOrder(annots, wref, nn);
                            kids.Add(wref);
                            Propagate(widget, null, false);
                        }
                        dic.Put(PdfName.Kids, kids);
                    }
                    arr.Add(ind);
                    AddToBody(dic, ind);
                    Propagate(dic, null, false);
                }
            }
            return(arr);
        }
Пример #31
0
        // returns the top parent to include in the catalog
        internal PdfIndirectReference WritePageTree()
        {
            if (pages.Count == 0)
            {
                throw new IOException("The document has no pages.");
            }
            int       leaf        = 1;
            ArrayList tParents    = parents;
            ArrayList tPages      = pages;
            ArrayList nextParents = new ArrayList();

            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();
                    ArrayList intern = kids.ArrayList;
                    intern.AddRange(tPages.GetRange(p * stdCount, count));
                    top.Put(PdfName.KIDS, kids);
                    if (tParents.Count > 1)
                    {
                        if ((p % leafSize) == 0)
                        {
                            nextParents.Add(writer.PdfIndirectReference);
                        }
                        top.Put(PdfName.PARENT, (PdfIndirectReference)nextParents[p / leafSize]);
                    }
                    writer.AddToBody(top, (PdfIndirectReference)tParents[p]);
                }
                if (tParents.Count == 1)
                {
                    topParent = (PdfIndirectReference)tParents[0];
                    return(topParent);
                }
                tPages      = tParents;
                tParents    = nextParents;
                nextParents = new ArrayList();
            }
        }
Пример #32
0
        public PdfDictionary GetEncryptionDictionary()
        {
            PdfDictionary dic = new PdfDictionary();

            if (publicKeyHandler.GetRecipientsSize() > 0)
            {
                PdfArray recipients = null;

                dic.Put(PdfName.FILTER, PdfName.PUBSEC);
                dic.Put(PdfName.R, new PdfNumber(revision));

                recipients = publicKeyHandler.GetEncodedRecipients();

                if (revision == STANDARD_ENCRYPTION_40)
                {
                    dic.Put(PdfName.V, new PdfNumber(1));
                    dic.Put(PdfName.SUBFILTER, PdfName.ADBE_PKCS7_S4);
                    dic.Put(PdfName.RECIPIENTS, recipients);
                }
                else if (revision == STANDARD_ENCRYPTION_128 && encryptMetadata)
                {
                    dic.Put(PdfName.V, new PdfNumber(2));
                    dic.Put(PdfName.LENGTH, new PdfNumber(128));
                    dic.Put(PdfName.SUBFILTER, PdfName.ADBE_PKCS7_S4);
                    dic.Put(PdfName.RECIPIENTS, recipients);
                }
                else
                {
                    if (revision == AES_256)
                    {
                        dic.Put(PdfName.R, new PdfNumber(AES_256));
                        dic.Put(PdfName.V, new PdfNumber(5));
                    }
                    else
                    {
                        dic.Put(PdfName.R, new PdfNumber(AES_128));
                        dic.Put(PdfName.V, new PdfNumber(4));
                    }
                    dic.Put(PdfName.SUBFILTER, PdfName.ADBE_PKCS7_S5);

                    PdfDictionary stdcf = new PdfDictionary();
                    stdcf.Put(PdfName.RECIPIENTS, recipients);
                    if (!encryptMetadata)
                    {
                        stdcf.Put(PdfName.ENCRYPTMETADATA, PdfBoolean.PDFFALSE);
                    }

                    if (revision == AES_128)
                    {
                        stdcf.Put(PdfName.CFM, PdfName.AESV2);
                        stdcf.Put(PdfName.LENGTH, new PdfNumber(128));
                    }
                    else if (revision == AES_256)
                    {
                        stdcf.Put(PdfName.CFM, PdfName.AESV3);
                        stdcf.Put(PdfName.LENGTH, new PdfNumber(256));
                    }
                    else
                    {
                        stdcf.Put(PdfName.CFM, PdfName.V2);
                    }
                    PdfDictionary cf = new PdfDictionary();
                    cf.Put(PdfName.DEFAULTCRYPTFILTER, stdcf);
                    dic.Put(PdfName.CF, cf);
                    if (embeddedFilesOnly)
                    {
                        dic.Put(PdfName.EFF, PdfName.DEFAULTCRYPTFILTER);
                        dic.Put(PdfName.STRF, PdfName.IDENTITY);
                        dic.Put(PdfName.STMF, PdfName.IDENTITY);
                    }
                    else
                    {
                        dic.Put(PdfName.STRF, PdfName.DEFAULTCRYPTFILTER);
                        dic.Put(PdfName.STMF, PdfName.DEFAULTCRYPTFILTER);
                    }
                }

                IDigest sh;
                if (revision == AES_256)
                {
                    sh = DigestUtilities.GetDigest("SHA-256");
                }
                else
                {
                    sh = DigestUtilities.GetDigest("SHA-1");
                }
                byte[] encodedRecipient = null;
                byte[] seed             = publicKeyHandler.GetSeed();
                sh.BlockUpdate(seed, 0, seed.Length);
                for (int i = 0; i < publicKeyHandler.GetRecipientsSize(); i++)
                {
                    encodedRecipient = publicKeyHandler.GetEncodedRecipient(i);
                    sh.BlockUpdate(encodedRecipient, 0, encodedRecipient.Length);
                }
                if (!encryptMetadata)
                {
                    sh.BlockUpdate(metadataPad, 0, metadataPad.Length);
                }
                byte[] mdResult = new byte[sh.GetDigestSize()];
                sh.DoFinal(mdResult, 0);
                if (revision == AES_256)
                {
                    key = mdResult;
                }
                else
                {
                    SetupByEncryptionKey(mdResult, keyLength);
                }
            }
            else
            {
                dic.Put(PdfName.FILTER, PdfName.STANDARD);
                dic.Put(PdfName.O, new PdfLiteral(PdfContentByte.EscapeString(ownerKey)));
                dic.Put(PdfName.U, new PdfLiteral(PdfContentByte.EscapeString(userKey)));
                dic.Put(PdfName.P, new PdfNumber(permissions));
                dic.Put(PdfName.R, new PdfNumber(revision));
                if (revision == STANDARD_ENCRYPTION_40)
                {
                    dic.Put(PdfName.V, new PdfNumber(1));
                }
                else if (revision == STANDARD_ENCRYPTION_128 && encryptMetadata)
                {
                    dic.Put(PdfName.V, new PdfNumber(2));
                    dic.Put(PdfName.LENGTH, new PdfNumber(128));
                }
                else if (revision == AES_256)
                {
                    if (!encryptMetadata)
                    {
                        dic.Put(PdfName.ENCRYPTMETADATA, PdfBoolean.PDFFALSE);
                    }
                    dic.Put(PdfName.OE, new PdfLiteral(PdfContentByte.EscapeString(oeKey)));
                    dic.Put(PdfName.UE, new PdfLiteral(PdfContentByte.EscapeString(ueKey)));
                    dic.Put(PdfName.PERMS, new PdfLiteral(PdfContentByte.EscapeString(perms)));
                    dic.Put(PdfName.V, new PdfNumber(revision));
                    dic.Put(PdfName.LENGTH, new PdfNumber(256));
                    PdfDictionary stdcf = new PdfDictionary();
                    stdcf.Put(PdfName.LENGTH, new PdfNumber(32));
                    if (embeddedFilesOnly)
                    {
                        stdcf.Put(PdfName.AUTHEVENT, PdfName.EFOPEN);
                        dic.Put(PdfName.EFF, PdfName.STDCF);
                        dic.Put(PdfName.STRF, PdfName.IDENTITY);
                        dic.Put(PdfName.STMF, PdfName.IDENTITY);
                    }
                    else
                    {
                        stdcf.Put(PdfName.AUTHEVENT, PdfName.DOCOPEN);
                        dic.Put(PdfName.STRF, PdfName.STDCF);
                        dic.Put(PdfName.STMF, PdfName.STDCF);
                    }
                    stdcf.Put(PdfName.CFM, PdfName.AESV3);
                    PdfDictionary cf = new PdfDictionary();
                    cf.Put(PdfName.STDCF, stdcf);
                    dic.Put(PdfName.CF, cf);
                }
                else
                {
                    if (!encryptMetadata)
                    {
                        dic.Put(PdfName.ENCRYPTMETADATA, PdfBoolean.PDFFALSE);
                    }
                    dic.Put(PdfName.R, new PdfNumber(AES_128));
                    dic.Put(PdfName.V, new PdfNumber(4));
                    dic.Put(PdfName.LENGTH, new PdfNumber(128));
                    PdfDictionary stdcf = new PdfDictionary();
                    stdcf.Put(PdfName.LENGTH, new PdfNumber(16));
                    if (embeddedFilesOnly)
                    {
                        stdcf.Put(PdfName.AUTHEVENT, PdfName.EFOPEN);
                        dic.Put(PdfName.EFF, PdfName.STDCF);
                        dic.Put(PdfName.STRF, PdfName.IDENTITY);
                        dic.Put(PdfName.STMF, PdfName.IDENTITY);
                    }
                    else
                    {
                        stdcf.Put(PdfName.AUTHEVENT, PdfName.DOCOPEN);
                        dic.Put(PdfName.STRF, PdfName.STDCF);
                        dic.Put(PdfName.STMF, PdfName.STDCF);
                    }
                    if (revision == AES_128)
                    {
                        stdcf.Put(PdfName.CFM, PdfName.AESV2);
                    }
                    else
                    {
                        stdcf.Put(PdfName.CFM, PdfName.V2);
                    }
                    PdfDictionary cf = new PdfDictionary();
                    cf.Put(PdfName.STDCF, stdcf);
                    dic.Put(PdfName.CF, cf);
                }
            }
            return(dic);
        }
Пример #33
0
 internal PdfName AddXObject(PdfName name, PdfIndirectReference reference)
 {
     name = TranslateName(name);
     xObjectDictionary.Put(name, reference);
     return(name);
 }
Пример #34
0
 internal PdfName AddColor(PdfName name, PdfIndirectReference reference)
 {
     name = TranslateName(name);
     colorDictionary.Put(name, reference);
     return(name);
 }
 /**
 * Adds the names of the named destinations to the catalog.
 * @param localDestinations the local destinations
 * @param documentJavaScript the javascript used in the document
 * @param writer the writer the catalog applies to
 */
 internal void AddNames(SortedDictionary<string,Destination> localDestinations, Dictionary<String, PdfObject> documentLevelJS, Dictionary<String, PdfObject> documentFileAttachment, PdfWriter writer) {
     if (localDestinations.Count == 0 && documentLevelJS.Count == 0 && documentFileAttachment.Count == 0)
         return;
     PdfDictionary names = new PdfDictionary();
     if (localDestinations.Count > 0) {
         PdfArray ar = new PdfArray();
         foreach (String name in localDestinations.Keys) {
             Destination dest;
             if (!localDestinations.TryGetValue(name, out dest))
                 continue;
             PdfIndirectReference refi = dest.reference;
             ar.Add(new PdfString(name, null));
             ar.Add(refi);
         }
         if (ar.Size > 0) {
             PdfDictionary dests = new PdfDictionary();
             dests.Put(PdfName.NAMES, ar);
             names.Put(PdfName.DESTS, writer.AddToBody(dests).IndirectReference);
         }
     }
     if (documentLevelJS.Count > 0) {
         PdfDictionary tree = PdfNameTree.WriteTree(documentLevelJS, writer);
         names.Put(PdfName.JAVASCRIPT, writer.AddToBody(tree).IndirectReference);
     }
     if (documentFileAttachment.Count > 0) {
         names.Put(PdfName.EMBEDDEDFILES, writer.AddToBody(PdfNameTree.WriteTree(documentFileAttachment, writer)).IndirectReference);
     }
     if (names.Size > 0)
         Put(PdfName.NAMES, writer.AddToBody(names).IndirectReference);
 }
Пример #36
0
 internal PdfName AddShading(PdfName name, PdfIndirectReference reference)
 {
     name = TranslateName(name);
     shadingDictionary.Put(name, reference);
     return(name);
 }
        public void WriteSignatures(PdfStructureElement tag)
        {
            if (this.Strategy.isIncludeFinalSignature == false)
                return;

            PdfStructureElement part = new PdfStructureElement(tag, new PdfName("Part"));
            content.BeginMarkedContentSequence(part);
            content.EndMarkedContentSequence();

            helper.AddLine(2);
            helper.SetMargins(1f);
            SetWidths(signaturecolumns);
            SetColumns();

            var ChiefGMO = helper.Portfolio.History[1].UpdatedBy;
            var BranchChief = helper.Portfolio.History[0].UpdatedBy;

            var DivisionDirector = helper.Portfolio.History[2].UpdatedBy;
            var NIEHSDirector = helper.Portfolio.History[3].UpdatedBy;

            var BranchChief_ApprovalDate = helper.Portfolio.History[0].UpdateDate.ToString("d");
            var ChiefGMO_ApprovalDate = helper.Portfolio.History[0].UpdateDate.ToString("d");
            var DivisionDirector_ApprovalDate = helper.Portfolio.History[0].UpdateDate.ToString("d");
            var NIEHSDirector_ApprovalDate = helper.Portfolio.History[0].UpdateDate.ToString("d");

            var TitleProxyOrDirector = helper.Portfolio.History[3].ValueOld.Contains("Pending NIEHS Director") ? "Director NIEHS" : "Deputy Director OER";

            var table = new tTable(this, "");
            table.ParentTag = part;
            table.ColumnCount = Columns.Length;

            var dict = new PdfDictionary();

            // row 1
            var cell = new tCell(0, "P", it.Element.ALIGN_LEFT, GrantFonts.BOLD, BranchChief );
            dict = new PdfDictionary();
            dict.Put(PdfName.ACTUALTEXT, new PdfString(string.Format("Branch Chief {0}",BranchChief)));
            cell.Dictionary = dict;
            cell.fontSize = 6.0f;
            var row = new tRow();
            row.Add(cell);

            cell = new tCell(1, "P", it.Element.ALIGN_LEFT, GrantFonts.NORMAL, BranchChief_ApprovalDate);
            dict = new PdfDictionary();
            dict.Put(PdfName.ACTUALTEXT, new PdfString(string.Format("Date {0}", ChiefGMO_ApprovalDate)));
            cell.Dictionary = dict;
            cell.fontSize = 6.0f;
            row.Add(cell);

            cell = new tCell(3, "P", it.Element.ALIGN_LEFT, GrantFonts.BOLD, ChiefGMO);
            dict = new PdfDictionary();
            dict.Put(PdfName.ACTUALTEXT, new PdfString(string.Format("Chief GMO {0}",ChiefGMO)));
            cell.Dictionary = dict;
            cell.fontSize = 6.0f;
            row.Add(cell);

            cell = new tCell(4, "P", it.Element.ALIGN_LEFT, GrantFonts.NORMAL,ChiefGMO_ApprovalDate);
            dict = new PdfDictionary();
            dict.Put(PdfName.ACTUALTEXT, new PdfString(string.Format("Date {0}",BranchChief_ApprovalDate)));
            cell.Dictionary = dict;
            cell.fontSize = 6.0f;
            row.Add(cell);

            // 6, 7
            cell = new tCell(6, "P", DivisionDirector);
            dict = new PdfDictionary();
            dict.Put(PdfName.ACTUALTEXT, new PdfString(string.Format("Division Director {0}",DivisionDirector)));
            cell.Dictionary = dict;
            cell.Font = GrantFonts.BOLD;
            cell.fontSize = 6.0f;
            row.Add(cell);

            cell = new tCell(7, "P", it.Element.ALIGN_LEFT, GrantFonts.NORMAL, DivisionDirector_ApprovalDate);
            dict = new PdfDictionary();
            dict.Put(PdfName.ACTUALTEXT, new PdfString(string.Format("Date {0}",DivisionDirector_ApprovalDate)));
            cell.Dictionary = dict;
            cell.fontSize = 6.0f;
            row.Add(cell);

            // 9, 10
            cell = new tCell(9, "P", it.Element.ALIGN_LEFT, GrantFonts.BOLD, NIEHSDirector);
            dict = new PdfDictionary();
            dict.Put(PdfName.ACTUALTEXT, new PdfString(string.Format("{0} {1}",TitleProxyOrDirector, NIEHSDirector)));
            cell.Dictionary = dict;
            cell.fontSize = 6.0f;
            row.Add(cell);

            cell = new tCell(10, "P", it.Element.ALIGN_LEFT, GrantFonts.NORMAL, NIEHSDirector_ApprovalDate);
            dict = new PdfDictionary();
            dict.Put(PdfName.ACTUALTEXT, new PdfString(string.Format("Date {0}", NIEHSDirector_ApprovalDate)));
            cell.Dictionary = dict;
            cell.fontSize = 6.0f;
            row.Add(cell);
            table.Add(row);


            //  row 2
            row = new tRow();
            cell = new tCell();
            cell.MakeDoubleLine(0, 2);
            row.Add(cell);

            cell = new tCell();
            cell.MakeDoubleLine(3, 2);
            row.Add(cell);

            cell = new tCell();
            cell.MakeDoubleLine(6, 2);
            row.Add(cell);

            cell = new tCell();
            cell.MakeDoubleLine(9, 2);
            row.Add(cell);
            table.Add(row);


            // row 3
            row = new tRow();
            cell = new tCell(0, "P", "Branch Chief"); 
            cell.isSpoken = false;
            cell.fontSize = 6.0f;
            row.Add(cell);

            cell = new tCell(1, "P", it.Element.ALIGN_LEFT, GrantFonts.NORMAL, "Date");
            cell.isSpoken = false;
            cell.fontSize = 6.0f;
            row.Add(cell);

            cell = new tCell(3, "P", "Chief GMO");
            cell.isSpoken = false;
            cell.fontSize = 6.0f;
            row.Add(cell);

            cell = new tCell(4, "P", it.Element.ALIGN_LEFT, GrantFonts.NORMAL, "Date");
            cell.isSpoken = false;
            cell.fontSize = 6.0f;
            row.Add(cell);

            // 6, 7
            cell = new tCell(6, "P", "Division Director");
            cell.isSpoken = false;
            cell.fontSize = 6.0f;
            row.Add(cell);

            cell = new tCell(7, "P", it.Element.ALIGN_LEFT, GrantFonts.NORMAL, "Date");
            cell.isSpoken = false;
            cell.fontSize = 6.0f;
            row.Add(cell);

            // 9, 10
            cell = new tCell(9, "P", TitleProxyOrDirector);
            cell.isSpoken = false;
            cell.fontSize = 6.0f;
            row.Add(cell);

            cell = new tCell(10, "P", it.Element.ALIGN_LEFT, GrantFonts.NORMAL, "Date");
            cell.isSpoken = false;
            cell.fontSize = 6.0f;
            row.Add(cell);
            table.Add(row);

            table.Write();
        }
Пример #38
0
 internal PdfName AddExtGState(PdfName name, PdfIndirectReference reference)
 {
     name = TranslateName(name);
     extGStateDictionary.Put(name, reference);
     return(name);
 }
Пример #39
0
     internal void EliminateAcroformObjects() {
         PdfObject acro = reader.Catalog.Get(PdfName.ACROFORM);
         if (acro == null)
             return;
         PdfDictionary acrodic = (PdfDictionary)PdfReader.GetPdfObject(acro);
         reader.KillXref(acrodic.Get(PdfName.XFA));
         acrodic.Remove(PdfName.XFA);
         PdfObject iFields = acrodic.Get(PdfName.FIELDS);
         if (iFields != null) {
             PdfDictionary kids = new PdfDictionary();
             kids.Put(PdfName.KIDS, iFields);
             SweepKids(kids);
             PdfReader.KillIndirect(iFields);
             acrodic.Put(PdfName.FIELDS, new PdfArray());
         }
         acrodic.Remove(PdfName.SIGFLAGS);
         acrodic.Remove(PdfName.NEEDAPPEARANCES);
         acrodic.Remove(PdfName.DR);
 //        PdfReader.KillIndirect(acro);
 //        reader.GetCatalog().Remove(PdfName.ACROFORM);
     }
Пример #40
0
 internal PdfName AddProperty(PdfName name, PdfIndirectReference reference)
 {
     name = TranslateName(name);
     propertyDictionary.Put(name, reference);
     return(name);
 }
Пример #41
0
 internal void AddAnnotation(PdfAnnotation annot, PdfDictionary pageN) {
     List<PdfAnnotation> allAnnots = new List<PdfAnnotation>();
     if (annot.IsForm()) {
         fieldsAdded = true;
         GetAcroFields();
         PdfFormField field = (PdfFormField)annot;
         if (field.Parent != null)
             return;
         ExpandFields(field, allAnnots);
     }
     else
         allAnnots.Add(annot);
     for (int k = 0; k < allAnnots.Count; ++k) {
         annot = allAnnots[k];
         if (annot.PlaceInPage > 0)
             pageN = reader.GetPageN(annot.PlaceInPage);
         if (annot.IsForm()) { 
             if (!annot.IsUsed()) {
                 HashSet2<PdfTemplate> templates = annot.GetTemplates();
                 if (templates != null)
                     fieldTemplates.AddAll(templates);
             }
             PdfFormField field = (PdfFormField)annot;
             if (field.Parent == null)
                 AddDocumentField(field.IndirectReference);
         }
         if (annot.IsAnnotation()) {
             PdfObject pdfobj = PdfReader.GetPdfObject(pageN.Get(PdfName.ANNOTS), pageN);
             PdfArray annots = null;
             if (pdfobj == null || !pdfobj.IsArray()) {
                 annots = new PdfArray();
                 pageN.Put(PdfName.ANNOTS, annots);
                 MarkUsed(pageN);
             }
             else 
                annots = (PdfArray)pdfobj;
             annots.Add(annot.IndirectReference);
             MarkUsed(annots);
             if (!annot.IsUsed()) {
                 PdfRectangle rect = (PdfRectangle)annot.Get(PdfName.RECT);
                 if (rect != null && (rect.Left != 0 || rect.Right != 0 || rect.Top != 0 || rect.Bottom != 0)) {
                     int rotation = reader.GetPageRotation(pageN);
                     Rectangle pageSize = reader.GetPageSizeWithRotation(pageN);
                     switch (rotation) {
                         case 90:
                             annot.Put(PdfName.RECT, new PdfRectangle(
                                 pageSize.Top - rect.Top,
                                 rect.Right,
                                 pageSize.Top - rect.Bottom,
                                 rect.Left));
                             break;
                         case 180:
                             annot.Put(PdfName.RECT, new PdfRectangle(
                                 pageSize.Right - rect.Left,
                                 pageSize.Top - rect.Bottom,
                                 pageSize.Right - rect.Right,
                                 pageSize.Top - rect.Top));
                             break;
                         case 270:
                             annot.Put(PdfName.RECT, new PdfRectangle(
                                 rect.Bottom,
                                 pageSize.Right - rect.Left,
                                 rect.Top,
                                 pageSize.Right - rect.Right));
                             break;
                     }
                 }
             }
         }
         if (!annot.IsUsed()) {
             annot.SetUsed();
             AddToBody(annot, annot.IndirectReference);
         }
     }
 }
Пример #42
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;
            }
        }
Пример #43
0
 /**
 * @param fdf
 * @throws IOException
 */
 virtual public void AddComments(FdfReader fdf) {
     if (readers2intrefs.ContainsKey(fdf))
         return;
     PdfDictionary catalog = fdf.Catalog;
     catalog = catalog.GetAsDict(PdfName.FDF);
     if (catalog == null)
         return;
     PdfArray annots = catalog.GetAsArray(PdfName.ANNOTS);
     if (annots == null || annots.Size == 0)
         return;
     RegisterReader(fdf, false);
     IntHashtable hits = new IntHashtable();
     Dictionary<String, PdfObject> irt = new Dictionary<string,PdfObject>();
     List<PdfObject> an = new List<PdfObject>();
     for (int k = 0; k < annots.Size; ++k) {
         PdfObject obj = annots[k];
         PdfDictionary annot = (PdfDictionary)PdfReader.GetPdfObject(obj);
         PdfNumber page = annot.GetAsNumber(PdfName.PAGE);
         if (page == null || page.IntValue >= reader.NumberOfPages)
             continue;
         FindAllObjects(fdf, obj, hits);
         an.Add(obj);
         if (obj.Type == PdfObject.INDIRECT) {
             PdfObject nm = PdfReader.GetPdfObject(annot.Get(PdfName.NM));
             if (nm != null && nm.Type == PdfObject.STRING)
                 irt[nm.ToString()] = obj;
         }
     }
     int[] arhits = hits.GetKeys();
     for (int k = 0; k < arhits.Length; ++k) {
         int n = arhits[k];
         PdfObject obj = fdf.GetPdfObject(n);
         if (obj.Type == PdfObject.DICTIONARY) {
             PdfObject str = PdfReader.GetPdfObject(((PdfDictionary)obj).Get(PdfName.IRT));
             if (str != null && str.Type == PdfObject.STRING) {
                 PdfObject i;
                 irt.TryGetValue(str.ToString(), out i);
                 if (i != null) {
                     PdfDictionary dic2 = new PdfDictionary();
                     dic2.Merge((PdfDictionary)obj);
                     dic2.Put(PdfName.IRT, i);
                     obj = dic2;
                 }
             }
         }
         AddToBody(obj, GetNewObjectNumber(fdf, n, 0));
     }
     for (int k = 0; k < an.Count; ++k) {
         PdfObject obj = an[k];
         PdfDictionary annot = (PdfDictionary)PdfReader.GetPdfObject(obj);
         PdfNumber page = annot.GetAsNumber(PdfName.PAGE);
         PdfDictionary dic = reader.GetPageN(page.IntValue + 1);
         PdfArray annotsp = (PdfArray)PdfReader.GetPdfObject(dic.Get(PdfName.ANNOTS), dic);
         if (annotsp == null) {
             annotsp = new PdfArray();
             dic.Put(PdfName.ANNOTS, annotsp);
             MarkUsed(dic);
         }
         MarkUsed(annotsp);
         annotsp.Add(obj);
     }
 }
        /** 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
         */
        private 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);
        }
Пример #45
0
 internal void InsertPage(int pageNumber, Rectangle mediabox) {
     Rectangle media = new Rectangle(mediabox);
     int rotation = media.Rotation % 360;
     PdfDictionary page = new PdfDictionary(PdfName.PAGE);
     page.Put(PdfName.RESOURCES, new PdfDictionary());
     page.Put(PdfName.ROTATE, new PdfNumber(rotation));
     page.Put(PdfName.MEDIABOX, new PdfRectangle(media, rotation));
     PRIndirectReference pref = reader.AddPdfObject(page);
     PdfDictionary parent;
     PRIndirectReference parentRef;
     if (pageNumber > reader.NumberOfPages) {
         PdfDictionary lastPage = reader.GetPageNRelease(reader.NumberOfPages);
         parentRef = (PRIndirectReference)lastPage.Get(PdfName.PARENT);
         parentRef = new PRIndirectReference(reader, parentRef.Number);
         parent = (PdfDictionary)PdfReader.GetPdfObject(parentRef);
         PdfArray kids = (PdfArray)PdfReader.GetPdfObject(parent.Get(PdfName.KIDS), parent);
         kids.Add(pref);
         MarkUsed(kids);
         reader.pageRefs.InsertPage(pageNumber, pref);
     }
     else {
         if (pageNumber < 1)
             pageNumber = 1;
         PdfDictionary firstPage = reader.GetPageN(pageNumber);
         PRIndirectReference firstPageRef = reader.GetPageOrigRef(pageNumber);
         reader.ReleasePage(pageNumber);
         parentRef = (PRIndirectReference)firstPage.Get(PdfName.PARENT);
         parentRef = new PRIndirectReference(reader, parentRef.Number);
         parent = (PdfDictionary)PdfReader.GetPdfObject(parentRef);
         PdfArray kids = (PdfArray)PdfReader.GetPdfObject(parent.Get(PdfName.KIDS), parent);
         int len = kids.Size;
         int num = firstPageRef.Number;
         for (int k = 0; k < len; ++k) {
             PRIndirectReference cur = (PRIndirectReference)kids[k];
             if (num == cur.Number) {
                 kids.Add(k, pref);
                 break;
             }
         }
         if (len == kids.Size)
             throw new Exception(MessageLocalization.GetComposedMessage("internal.inconsistence"));
         MarkUsed(kids);
         reader.pageRefs.InsertPage(pageNumber, pref);
         CorrectAcroFieldPages(pageNumber);
     }
     page.Put(PdfName.PARENT, parentRef);
     while (parent != null) {
         MarkUsed(parent);
         PdfNumber count = (PdfNumber)PdfReader.GetPdfObjectRelease(parent.Get(PdfName.COUNT));
         parent.Put(PdfName.COUNT, new PdfNumber(count.IntValue + 1));
         parent = parent.GetAsDict(PdfName.PARENT);
     }
 }
Пример #46
0
 private void CompleteExtraCatalog(PdfDictionary extraCatalog) {
     if (IsPdfX()) {
         if (extraCatalog.Get(PdfName.OUTPUTINTENTS) == null) {
             PdfDictionary outD = new PdfDictionary(PdfName.OUTPUTINTENT);
             outD.Put(PdfName.OUTPUTCONDITION, new PdfString("SWOP CGATS TR 001-1995"));
             outD.Put(PdfName.OUTPUTCONDITIONIDENTIFIER, new PdfString("CGATS TR 001"));
             outD.Put(PdfName.REGISTRYNAME, new PdfString("http://www.color.org"));
             outD.Put(PdfName.INFO, new PdfString(""));
             outD.Put(PdfName.S, PdfName.GTS_PDFX);
             extraCatalog.Put(PdfName.OUTPUTINTENTS, new PdfArray(outD));
         }
     }
 }
Пример #47
0
 /**
 * Signals that the <CODE>Document</CODE> has been opened and that
 * <CODE>Elements</CODE> can be added.
 * <P>
 * When this method is called, the PDF-document header is
 * written to the outputstream.
 */
 public override void Open() {
     base.Open();
     pdf_version.WriteHeader(os);
     body = new PdfBody(this);
     if (IsPdfX() && ((PdfXConformanceImp)pdfIsoConformance).IsPdfX32002())
     {
         PdfDictionary sec = new PdfDictionary();
         sec.Put(PdfName.GAMMA, new PdfArray(new float[]{2.2f,2.2f,2.2f}));
         sec.Put(PdfName.MATRIX, new PdfArray(new float[]{0.4124f,0.2126f,0.0193f,0.3576f,0.7152f,0.1192f,0.1805f,0.0722f,0.9505f}));
         sec.Put(PdfName.WHITEPOINT, new PdfArray(new float[]{0.9505f,1f,1.089f}));
         PdfArray arr = new PdfArray(PdfName.CALRGB);
         arr.Add(sec);
         SetDefaultColorspace(PdfName.DEFAULTRGB, AddToBody(arr).IndirectReference);
     }
 }
Пример #48
0
        /// <summary>
        /// @see com.lowagie.text.pdf.PdfDictionary#toPdf(com.lowagie.text.pdf.PdfWriter, java.io.OutputStream)
        /// </summary>
        public override void ToPdf(PdfWriter writer, Stream os)
        {
            if (InputStream != null && Compressed)
            {
                Put(PdfName.Filter, PdfName.Flatedecode);
            }

            PdfEncryption crypto = null;

            if (writer != null)
            {
                crypto = writer.Encryption;
            }

            if (crypto != null)
            {
                var filter = Get(PdfName.Filter);
                if (filter != null)
                {
                    if (PdfName.Crypt.Equals(filter))
                    {
                        crypto = null;
                    }
                    else if (filter.IsArray())
                    {
                        var a = (PdfArray)filter;
                        if (!a.IsEmpty() && PdfName.Crypt.Equals(a[0]))
                        {
                            crypto = null;
                        }
                    }
                }
            }
            if (crypto != null && crypto.IsEmbeddedFilesOnly())
            {
                var filter      = new PdfArray();
                var decodeparms = new PdfArray();
                var crypt       = new PdfDictionary();
                crypt.Put(PdfName.Name, PdfName.Stdcf);
                filter.Add(PdfName.Crypt);
                decodeparms.Add(crypt);
                if (Compressed)
                {
                    filter.Add(PdfName.Flatedecode);
                    decodeparms.Add(new PdfNull());
                }
                Put(PdfName.Filter, filter);
                Put(PdfName.Decodeparms, decodeparms);
            }
            var nn = Get(PdfName.LENGTH);

            if (crypto != null && nn != null && nn.IsNumber())
            {
                var sz = ((PdfNumber)nn).IntValue;
                Put(PdfName.LENGTH, new PdfNumber(crypto.CalculateStreamSize(sz)));
                SuperToPdf(writer, os);
                Put(PdfName.LENGTH, nn);
            }
            else
            {
                SuperToPdf(writer, os);
            }

            os.Write(Startstream, 0, Startstream.Length);
            if (InputStream != null)
            {
                rawLength = 0;
                ZDeflaterOutputStream def = null;
                var osc = new OutputStreamCounter(os);
                OutputStreamEncryption ose = null;
                Stream fout = osc;
                if (crypto != null)
                {
                    fout = ose = crypto.GetEncryptionStream(fout);
                }

                if (Compressed)
                {
                    fout = def = new ZDeflaterOutputStream(fout, CompressionLevel);
                }

                var buf = new byte[4192];
                while (true)
                {
                    var n = InputStream.Read(buf, 0, buf.Length);
                    if (n <= 0)
                    {
                        break;
                    }

                    fout.Write(buf, 0, n);
                    rawLength += n;
                }
                if (def != null)
                {
                    def.Finish();
                }

                if (ose != null)
                {
                    ose.Finish();
                }

                InputStreamLength = osc.Counter;
            }
            else
            {
                if (crypto == null)
                {
                    if (StreamBytes != null)
                    {
                        StreamBytes.WriteTo(os);
                    }
                    else
                    {
                        os.Write(Bytes, 0, Bytes.Length);
                    }
                }
                else
                {
                    byte[] b;
                    if (StreamBytes != null)
                    {
                        b = crypto.EncryptByteArray(StreamBytes.ToArray());
                    }
                    else
                    {
                        b = crypto.EncryptByteArray(Bytes);
                    }
                    os.Write(b, 0, b.Length);
                }
            }
            os.Write(Endstream, 0, Endstream.Length);
        }
Пример #49
0
    //  [C11] Output intents

        /**
        * Sets the values of the output intent dictionary. Null values are allowed to
        * suppress any key.
        * @param outputConditionIdentifier a value
        * @param outputCondition a value
        * @param registryName a value
        * @param info a value
        * @param destOutputProfile a value
        * @throws IOException on error
        */
        public virtual void SetOutputIntents(String outputConditionIdentifier, String outputCondition, String registryName, String info, ICC_Profile colorProfile)
        {
            PdfDictionary outa = ExtraCatalog; //force the creation
            outa = new PdfDictionary(PdfName.OUTPUTINTENT);
            if (outputCondition != null)
                outa.Put(PdfName.OUTPUTCONDITION, new PdfString(outputCondition, PdfObject.TEXT_UNICODE));
            if (outputConditionIdentifier != null)
                outa.Put(PdfName.OUTPUTCONDITIONIDENTIFIER, new PdfString(outputConditionIdentifier, PdfObject.TEXT_UNICODE));
            if (registryName != null)
                outa.Put(PdfName.REGISTRYNAME, new PdfString(registryName, PdfObject.TEXT_UNICODE));
            if (info != null)
                outa.Put(PdfName.INFO, new PdfString(info, PdfObject.TEXT_UNICODE));
            if (colorProfile != null) {
                PdfStream stream = new PdfICCBased(colorProfile, compressionLevel);
                outa.Put(PdfName.DESTOUTPUTPROFILE, AddToBody(stream).IndirectReference);
            }

            outa.Put(PdfName.S, PdfName.GTS_PDFX);

            extraCatalog.Put(PdfName.OUTPUTINTENTS, new PdfArray(outa));
        }
Пример #50
0
        internal override void WriteFont(PdfWriter writer, PdfIndirectReference piRef, Object[] oParams)
        {
            if (this.writer != writer)
            {
                throw new ArgumentException("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("No glyphs defined for Type3 font");
            }
            int lastChar = usedSlot.Length - 1;

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

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

            int invOrdIndx = 0, w = 0;

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

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

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

            encoding.Put(PdfName.DIFFERENCES, diffs);
            font.Put(PdfName.ENCODING, writer.AddToBody(encoding).IndirectReference);
            font.Put(PdfName.FIRSTCHAR, new PdfNumber(firstChar));
            font.Put(PdfName.LASTCHAR, new PdfNumber(lastChar));
            font.Put(PdfName.WIDTHS, writer.AddToBody(new PdfArray(widths)).IndirectReference);
            if (pageResources.HasResources())
            {
                font.Put(PdfName.RESOURCES, writer.AddToBody(pageResources.Resources).IndirectReference);
            }
            writer.AddToBody(font, piRef);
        }
Пример #51
0
 protected void FillOCProperties(bool erase) {
     if (vOCProperties == null)
         vOCProperties = new PdfOCProperties();
     if (erase) {
         vOCProperties.Remove(PdfName.OCGS);
         vOCProperties.Remove(PdfName.D);
     }
     if (vOCProperties.Get(PdfName.OCGS) == null) {
         PdfArray gr = new PdfArray();
         foreach (PdfLayer layer in documentOCG.Keys) {
             gr.Add(layer.Ref);
         }
         vOCProperties.Put(PdfName.OCGS, gr);
     }
     if (vOCProperties.Get(PdfName.D) != null)
         return;
     List<IPdfOCG> docOrder = new List<IPdfOCG>(documentOCGorder);
     for (ListIterator<IPdfOCG> it = new ListIterator<IPdfOCG>(docOrder); it.HasNext();) {
         PdfLayer layer = (PdfLayer)it.Next();
         if (layer.Parent != null)
             it.Remove();
     }
     PdfArray order = new PdfArray();
     foreach (PdfLayer layer in docOrder) {
         GetOCGOrder(order, layer);
     }
     PdfDictionary d = new PdfDictionary();
     vOCProperties.Put(PdfName.D, d);
     d.Put(PdfName.ORDER, order);
     PdfArray grx = new PdfArray();
     foreach (PdfLayer layer in documentOCG.Keys) {
         if (!layer.On)
             grx.Add(layer.Ref);
     }
     if (grx.Size > 0)
         d.Put(PdfName.OFF, grx);
     if (OCGRadioGroup.Size > 0)
         d.Put(PdfName.RBGROUPS, OCGRadioGroup);
     if (OCGLocked.Size > 0)
         d.Put(PdfName.LOCKED, OCGLocked);
     AddASEvent(PdfName.VIEW, PdfName.ZOOM);
     AddASEvent(PdfName.VIEW, PdfName.VIEW);
     AddASEvent(PdfName.PRINT, PdfName.PRINT);
     AddASEvent(PdfName.EXPORT, PdfName.EXPORT);
     d.Put(PdfName.LISTMODE, PdfName.VISIBLEPAGES);
 }
Пример #52
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
                    }
                }
            }
        }
Пример #53
0
 private void CompleteInfoDictionary(PdfDictionary info) {
     if (IsPdfX()) {
         if (info.Get(PdfName.GTS_PDFXVERSION) == null) {
             if (((PdfXConformanceImp)pdfIsoConformance).IsPdfX1A2001()) {
                 info.Put(PdfName.GTS_PDFXVERSION, new PdfString("PDF/X-1:2001"));
                 info.Put(new PdfName("GTS_PDFXConformance"), new PdfString("PDF/X-1a:2001"));
             }
             else if (((PdfXConformanceImp)pdfIsoConformance).IsPdfX32002())
                 info.Put(PdfName.GTS_PDFXVERSION, new PdfString("PDF/X-3:2002"));
         }
         if (info.Get(PdfName.TITLE) == null) {
             info.Put(PdfName.TITLE, new PdfString("Pdf document"));
         }
         if (info.Get(PdfName.CREATOR) == null) {
             info.Put(PdfName.CREATOR, new PdfString("Unknown"));
         }
         if (info.Get(PdfName.TRAPPED) == null) {
             info.Put(PdfName.TRAPPED, new PdfName("False"));
         }
     }
 }
Пример #54
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>();
            }
        }
Пример #55
0
 protected void BuildStructTreeRootForTagged(PdfDictionary catalog)
 {
     if (tagged) {
         this.StructureTreeRoot.BuildTree();
         catalog.Put(PdfName.STRUCTTREEROOT, structureTreeRoot.Reference);
         PdfDictionary mi = new PdfDictionary();
         mi.Put(PdfName.MARKED, PdfBoolean.PDFTRUE);
         if (userProperties)
             mi.Put(PdfName.USERPROPERTIES, PdfBoolean.PDFTRUE);
         catalog.Put(PdfName.MARKINFO, mi);
     }
 }
 /**
 * Generations the developer extension dictionary corresponding
 * with the prefix.
 * @return  a PdfDictionary
 */
 public PdfDictionary GetDeveloperExtensions() {
     PdfDictionary developerextensions = new PdfDictionary();
     developerextensions.Put(PdfName.BASEVERSION, baseversion);
     developerextensions.Put(PdfName.EXTENSIONLEVEL, new PdfNumber(extensionLevel));
     return developerextensions;
 }