示例#1
0
		public void Save (System.IO.Stream stream)
		{
			try {
				XmlTextWriter text;
				RdfXmlWriter writer;
                                XmlDocument rdfdoc = new XmlDocument();

                                // first, construct the rdf guts, semweb style
                                writer = new XmpWriter (rdfdoc);
				//writer.Namespaces.Parent = MetadataStore.Namespaces;
				writer.Write (store);
				writer.Close ();
			       
                                // now construct the xmp wrapper packet
				text = new XmlTextWriter (stream, System.Text.Encoding.UTF8);
 				text.Formatting = Formatting.Indented;
                        
                                text.WriteProcessingInstruction ("xpacket", "begin=\"\ufeff\" id=\"W5M0MpCehiHzreSzNTczkc9d\"");
                                text.WriteStartElement ("x:xmpmeta");
                                text.WriteAttributeString ("xmlns", "x", null, "adobe:ns:meta/");

				((XmlElement)rdfdoc.ChildNodes[1]).RemoveAttribute ("xml:base");
				rdfdoc.ChildNodes[1].WriteTo (text);

                                // now close off the xmp packet
                                text.WriteEndElement ();
                                text.WriteProcessingInstruction ("xpacket", "end=\"r\"");
				text.Close ();
				
			} catch (System.Exception e) {
				//System.Console.WriteLine (e);
			}
		}
示例#2
0
        public void Save(System.IO.Stream stream)
        {
            try {
                XmlTextWriter text;
                RdfXmlWriter  writer;
                XmlDocument   rdfdoc = new XmlDocument();

                // first, construct the rdf guts, semweb style
                writer = new XmpWriter(rdfdoc);
                //writer.Namespaces.Parent = MetadataStore.Namespaces;
                writer.Write(store);
                writer.Close();

                // now construct the xmp wrapper packet
                text            = new XmlTextWriter(stream, System.Text.Encoding.UTF8);
                text.Formatting = Formatting.Indented;

                text.WriteProcessingInstruction("xpacket", "begin=\"\ufeff\" id=\"W5M0MpCehiHzreSzNTczkc9d\"");
                text.WriteStartElement("x:xmpmeta");
                text.WriteAttributeString("xmlns", "x", null, "adobe:ns:meta/");

                ((XmlElement)rdfdoc.ChildNodes[1]).RemoveAttribute("xml:base");
                rdfdoc.ChildNodes[1].WriteTo(text);

                // now close off the xmp packet
                text.WriteEndElement();
                text.WriteProcessingInstruction("xpacket", "end=\"r\"");
                text.Close();
            } catch (System.Exception e) {
                //System.Console.WriteLine (e);
            }
        }
示例#3
0
        public byte[] GetStreamedMetaData()
        {
            var os  = new System.IO.MemoryStream();
            var xmp = new XmpWriter(os, this.Info);

            xmp.Close();
            return(os.ToArray());
        }
示例#4
0
    public byte[] getStreamedMetaData()
    {
        MemoryStream os  = new System.IO.MemoryStream();
        XmpWriter    xmp = new XmpWriter(os, info);

        xmp.Close();
        return(os.ToArray());
    }
示例#5
0
        /**
         * Метод упрощающий запись в xmp файл, т.к. из Java перекочевал ключевой недостаток библиотеки: 4 разных метода для записи свойства объектов
         * в качестве аргементов принимает
         * 1 Объект XmpWriter созданный выше
         * 2 Объект карты из map
         * 3 значение для записи
         */
        static void SetValue(XmpWriter writer, MapObject mapObject, string value)
        {
            // Проверяет что значение НЕ записывается одной строкой и что это не требуемое значения не типа "Свойство"
            if (!mapObject.IsSingle && mapObject.ValueType != ValueType.Property)
            {
                // делит значения по точке с запятой или запятой
                string[] values = value.Split(new string[] { " ; ", "," }, StringSplitOptions.RemoveEmptyEntries);
                // перебирает только что разделенную строку и последовательно записывает в коллекцию соответствующим способом
                foreach (string v in values)
                {
                    PropertyOptions arrayOptions = new PropertyOptions();

                    if (mapObject.ValueType == ValueType.Bag)
                    {
                        arrayOptions.Array = true;
                    }
                    if (mapObject.ValueType == ValueType.Alt)
                    {
                        arrayOptions.ArrayAlternate = true;
                    }
                    if (mapObject.ValueType == ValueType.Seq)
                    {
                        arrayOptions.ArrayOrdered = true;
                    }

                    writer.XmpMeta.AppendArrayItem(mapObject.XmlSchemaNs, mapObject.ValueName, arrayOptions, v.Trim(), new PropertyOptions {
                        HasLanguage = true, HasQualifiers = true
                    });
                }
            }
            else
            {
                if (mapObject.ValueType != ValueType.Property)
                {
                    PropertyOptions arrayOptions = new PropertyOptions();
                    if (mapObject.ValueType == ValueType.Bag)
                    {
                        arrayOptions.Array = true;
                    }
                    if (mapObject.ValueType == ValueType.Alt)
                    {
                        arrayOptions.ArrayAlternate = true;
                    }
                    if (mapObject.ValueType == ValueType.Seq)
                    {
                        arrayOptions.ArrayOrdered = true;
                    }

                    writer.XmpMeta.AppendArrayItem(mapObject.XmlSchemaNs, mapObject.ValueName, arrayOptions, value.Trim(), new PropertyOptions {
                        HasLanguage = true
                    });
                }
                else
                {
                    writer.XmpMeta.SetProperty(mapObject.XmlSchemaNs, mapObject.ValueName, value);
                }
            }
        }
示例#6
0
        public byte[] GetStreamedMetaData()
        {
            MemoryStream os        = new System.IO.MemoryStream();
            var          hashTable = new Hashtable(this.info);
            XmpWriter    xmp       = new XmpWriter(os, hashTable);

            xmp.Close();
            return(os.ToArray());
        }
示例#7
0
        public static void Obey(Dictionary <NameToken, IToken> catalog, Func <IToken, ObjectToken> writerFunc,
                                PdfDocumentBuilder.DocumentInformationBuilder documentInformationBuilder,
                                PdfAStandard archiveStandard)
        {
            catalog[NameToken.OutputIntents] = OutputIntentsFactory.GetOutputIntentsArray(writerFunc);
            var xmpStream = XmpWriter.GenerateXmpStream(documentInformationBuilder, 1.7m, archiveStandard);
            var xmpObj    = writerFunc(xmpStream);

            catalog[NameToken.Metadata] = new IndirectReferenceToken(xmpObj.Number);
        }
示例#8
0
        private void GenerateEAttachmentDocument(PdfAWriter writer, XmpWriter xmpWriter, EAttactment attachment)
        {
            // Use default intent if output intent of this instance was not set
            if (attachment.outputIntents == null)
            {
                //byte[] iccProfile = File.ReadAllBytes("/Resources/sRGB Color Space Profile.icm");
                byte[]      iccProfile = Properties.Resources.sRGB_Color_Space_Profile;
                ICC_Profile icc        = ICC_Profile.GetInstance(iccProfile);
                writer.SetOutputIntents("sRGB IEC61966-2.1", "", "http://www.color.org", "sRGB IEC61966-2.1", icc);
            }
            else
            {
                OutputIntents outputIntents       = attachment.outputIntents;
                byte[]        iccProfileByteArray = File.ReadAllBytes(outputIntents.colorProfilePath);
                ICC_Profile   icc = ICC_Profile.GetInstance(iccProfileByteArray);
                writer.SetOutputIntents(outputIntents.outputConditionIdentifier, outputIntents.outputCondition, outputIntents.registryName, outputIntents.info, icc);
            }

            //============= Create Exchange ECertificate =================
            // 1 add ContentInformation.xml to document
            PdfArray attachmentArray = new PdfArray();

            writer.ExtraCatalog.Put(new PdfName("AF"), attachmentArray);
            PdfFileSpecification contentSpec = this.EmbeddedAttachment(attachment.contentInformationXMLPath, attachment.attachmentName,
                                                                       attachment.attachmentMIME, new PdfName(attachment.attachmentType), writer, attachment.attachmentDescription);

            attachmentArray.Add(contentSpec.Reference);

            foreach (var item in attachment.fileAttachments)
            {
                contentSpec = this.EmbeddedAttachment(item.attachmentPath, item.attachmentName,
                                                      item.attachmentMIME, new PdfName(item.attachmentType), writer, item.attachmentDescription);
                attachmentArray.Add(contentSpec.Reference);
            }

            // 2 add Electronic Document XMP Metadata
            ElectronicDocumentSchema ed = ElectronicDocumentSchema.generateED(attachment.attachmentName, attachment.documentVersion, attachment.documentID, attachment.documentOID);

            xmpWriter.AddRdfDescription(ed);

            string pdfaSchema = Properties.Resources.EDocument_PDFAExtensionSchema;

            // convert string to stream
            byte[] byteArray = Encoding.UTF8.GetBytes(pdfaSchema);


            //byte[] byteArray = Encoding.ASCII.GetBytes(contents);
            MemoryStream stream          = new MemoryStream(byteArray);
            IXmpMeta     edPDFAextension = XmpMetaFactory.Parse(stream);
            IXmpMeta     originalXMP     = xmpWriter.XmpMeta;

            XmpUtils.AppendProperties(edPDFAextension, originalXMP, true, true);
        }
 protected override void Draw(XmpWriter xmpWriter)
 {
     xmpWriter.BeginDescription("http://ns.adobe.com/xap/1.0/", "xmp", " ");
     if (userName != null)
     {
         xmpWriter.Draw("\t\t<xmp:CreatedBy>" + userName + "</xmp:CreatedBy>\n");
     }
     xmpWriter.Draw("\t\t<xmp:DateCreated>" + creationDate.ToString("yyyy-MM-dd'T'HH:mm:sszzz") + "</xmp:DateCreated>\n");
     xmpWriter.Draw("\t\t<xmp:CreatorTool>" + xmpWriter.Producer + "</xmp:CreatorTool>\n");
     xmpWriter.Draw("\t\t<xmp:MetadataDate>" + xmpWriter.Date.ToLocalTime().ToString("yyyy-MM-dd'T'HH:mm:sszzz") + "</xmp:MetadataDate>\n");
     xmpWriter.EndDescription();
 }
示例#10
0
// ---------------------------------------------------------------------------

        /**
         * Manipulates a PDF file src with the file dest as result
         * @param src the original PDF
         */
        public byte[] ManipulatePdf(byte[] src)
        {
            PdfReader reader = new PdfReader(src);

            using (MemoryStream ms = new MemoryStream()) {
                using (PdfStamper stamper = new PdfStamper(reader, ms)) {
                    Dictionary <String, String> info = reader.Info;
                    using (MemoryStream msXmp = new MemoryStream()) {
                        XmpWriter xmp = new XmpWriter(msXmp, info);
                        xmp.Close();
                        stamper.XmpMetadata = msXmp.ToArray();
                    }
                }
                return(ms.ToArray());
            }
        }
示例#11
0
 public static byte[] AddPdfAFlag(byte[] fileContents)
 {
     using (var memoryStream = new MemoryStream())
     {
         using (var pdfReader = new PdfReader(fileContents))
         {
             using (var pdfStamper = new PdfStamper(pdfReader, memoryStream, '\0', true))
             {
                 using (var pdfaMemoryStream = new MemoryStream())
                 {
                     var xmpWriter = new XmpWriter(pdfaMemoryStream, pdfStamper.MoreInfo);
                     xmpWriter.SetProperty(XmpConst.NS_PDFA_ID, PdfAProperties.PART, "3");
                     xmpWriter.SetProperty(XmpConst.NS_PDFA_ID, PdfAProperties.CONFORMANCE, "A");
                     xmpWriter.Close();
                     pdfStamper.XmpMetadata = pdfaMemoryStream.ToArray();
                 }
             }
         }
         return(memoryStream.ToArray());
     }
 }
示例#12
0
// ---------------------------------------------------------------------------

/**
 * Creates a PDF document.
 */
        public byte[] CreatePdf()
        {
            using (MemoryStream ms = new MemoryStream()) {
                // step 1
                using (Document document = new Document()) {
                    // step 2
                    PdfWriter writer = PdfWriter.GetInstance(document, ms);
                    using (MemoryStream msXmp = new MemoryStream()) {
                        XmpWriter xmp     = new XmpWriter(msXmp);
                        XmpSchema dc      = new DublinCoreSchema();
                        XmpArray  subject = new XmpArray(XmpArray.UNORDERED);
                        subject.Add("Hello World");
                        subject.Add("XMP & Metadata");
                        subject.Add("Metadata");
                        dc.SetProperty(DublinCoreSchema.SUBJECT, subject);
                        xmp.AddRdfDescription(dc);
                        PdfSchema pdf = new PdfSchema();

/*
 *  iTextSharp uses Item property instead of Java setProperty() method
 *
 *      pdf.SetProperty(PdfSchema.KEYWORDS, "Hello World, XMP, Metadata");
 *      pdf.SetProperty(PdfSchema.VERSION, "1.4");
 */
                        pdf[PdfSchema.KEYWORDS] = "Hello World, XMP, Metadata";
                        pdf[PdfSchema.VERSION]  = "1.4";
                        xmp.AddRdfDescription(pdf);
                        xmp.Close();
                        writer.XmpMetadata = ms.ToArray();
                    }
                    // step 3
                    document.Open();
                    // step 4
                    document.Add(new Paragraph("Hello World"));
                }
                return(ms.ToArray());
            }
        }
示例#13
0
        public byte[] Pdf2PdfA(byte[] pdf, List <KeyValuePair <string, string> > properties, OutputIntents outputIntents)
        {
            PdfReader    document     = new PdfReader(pdf);
            MemoryStream stream       = new MemoryStream();
            Document     pdfADocument = new Document();

            PdfAWriter writer = this.CreatePDFAInstance(pdfADocument, document, stream);

            writer.CreateXmpMetadata();
            XmpWriter xmpWriter = writer.XmpWriter;

            properties.ForEach(delegate(KeyValuePair <string, string> keyValuePairs)
            {
                xmpWriter.AddDocInfoProperty(keyValuePairs.Key, keyValuePairs.Value);
            });

            generatePDFA3Document(writer, outputIntents);

            pdfADocument.Close();
            document.Close();

            return(stream.ToArray());
        }
示例#14
0
        public static void AddPdfAFlag(string filePath)
        {
            var newFilePath = filePath.CombineFilePathWithGuid();

            using (var fileStream = new FileStream(newFilePath, FileMode.Create))
            {
                using (var pdfReader = new PdfReader(filePath))
                {
                    using (var pdfStamper = new PdfStamper(pdfReader, fileStream, '\0', true))
                    {
                        using (var pdfaMemoryStream = new MemoryStream())
                        {
                            var xmpWriter = new XmpWriter(pdfaMemoryStream, pdfStamper.MoreInfo);
                            xmpWriter.SetProperty(XmpConst.NS_PDFA_ID, PdfAProperties.PART, "3");
                            xmpWriter.SetProperty(XmpConst.NS_PDFA_ID, PdfAProperties.CONFORMANCE, "A");
                            xmpWriter.Close();
                            pdfStamper.XmpMetadata = pdfaMemoryStream.ToArray();
                        }
                    }
                }
            }

            File.Copy(newFilePath, filePath, true);
        }
示例#15
0
        public string CreatePDF(int poid)
        {
            var po = OrderRepository.Single(poid);

            if (po == null)
            {
                throw new ItemNotFoundException <Ordering.PurchaseOrder>(x => x.POID, poid);
            }

            var basePath = ConfigurationManager.AppSettings["PdfBasePath"];

            if (string.IsNullOrEmpty(basePath))
            {
                throw new InvalidOperationException("Missing required appSetting: PdfBasePath");
            }

            if (!Directory.Exists(basePath))
            {
                throw new InvalidOperationException($"Directory not found: {basePath}");
            }

            string tempPath = Path.Combine(basePath, "temp");

            if (!Directory.Exists(tempPath))
            {
                Directory.CreateDirectory(tempPath);
            }

            string imagePath = Path.Combine(basePath, "images");

            if (!Directory.Exists(imagePath))
            {
                Directory.CreateDirectory(imagePath);
            }

            string template = Path.Combine(basePath, "IOFTemplate.pdf");

            if (!File.Exists(template))
            {
                throw new InvalidOperationException($"Missing template file: {template}");
            }

            string templatePage2 = Path.Combine(basePath, "IOFTemplatePage2.pdf");

            if (!File.Exists(templatePage2))
            {
                throw new InvalidOperationException($"Missing template page 2 file: {templatePage2}");
            }

            var c = ClientRepository.Single(po.ClientID);

            string pdfName = $"IOF_{po.POID}_{c.LName}{c.FName}_{DateTime.Now:yyMmddHHmmss}.pdf";
            string pdfPath = Path.Combine(tempPath, pdfName);

            if (File.Exists(pdfPath))
            {
                File.Delete(pdfPath);
            }

            using (var fs = new FileStream(pdfPath, FileMode.Create, FileAccess.Write))
            {
                PdfReader  pr = new PdfReader(template);
                PdfStamper ps = new PdfStamper(pr, fs);
                AcroFields af = ps.AcroFields;

                var info = pr.Info;
                info["Title"] = $"IOF #{po.POID} : {po.VendorName} : {c.FName} {c.LName}";
                ps.MoreInfo   = info;

                using (var ms = new MemoryStream())
                {
                    var xmp = new XmpWriter(ms, info);
                    ps.XmpMetadata = ms.ToArray();
                    xmp.Close();
                }

                af.SetField("poID", $"IOF # {po.POID}");
                af.SetField("RequestedBy", c.DisplayName);
                af.SetField("Email", c.Email);
                af.SetField("Phone", c.Phone);

                var approver = ClientRepository.GetApprover(po);

                if (po.IsApproved())
                {
                    string imageFile = Path.Combine(imagePath, $"{approver.LName}.tif");
                    if (File.Exists(imageFile))
                    {
                        var sig = Image.GetInstance(imageFile);
                        ps.GetOverContent(1).AddImage(sig, 50, 0, 0, 24, 231, 539);
                    }
                    af.SetField("ApprovedBy", approver.DisplayName);
                }

                // fill in shipping info
                af.SetField("Date", po.CreatedDate.ToShortDateString());
                af.SetField("DateNeeded", po.NeededDate.ToShortDateString());
                af.SetField("Advisor", approver.DisplayName);
                af.SetField("Shipping", po.ShippingMethodName);

                var acct = AccountRepository.Single(po.ClientID, po.AccountID);

                if (acct == null)
                {
                    af.SetField("Account", string.Empty);
                }
                else
                {
                    af.SetField("Account", acct.ShortCode);
                }

                if (po.Oversized)
                {
                    af.SetField("chkOverSized", "Yes");
                }
                af.SetField("PurchaseTotal", po.TotalPrice.ToString("#,##0.00"));

                // fill in vendor info
                var vendor = VendorRepository.Single(po.VendorID);
                af.SetField("Vendor", vendor.VendorName);
                af.SetField("VendAddr1", vendor.Address1);
                af.SetField("VendAddr2", vendor.Address2);
                af.SetField("VendAddr3", vendor.Address3);
                af.SetField("Contact", vendor.Contact);
                af.SetField("ContactPhone", vendor.Phone);
                af.SetField("ContactFax", vendor.Fax);
                af.SetField("VendorWWW", vendor.URL);
                af.SetField("ContactEmail", vendor.Email);

                // in the 'office use only' box
                af.SetField("VendorOffice", vendor.VendorName);

                // notes
                var items = GetItems(po.POID).ToList();

                if (!string.IsNullOrEmpty(po.Notes))
                {
                    items.Add(new PdfItem()
                    {
                        Description = po.Notes, IsNotes = true
                    });
                }

                // items
                int   x          = 0;
                float y          = 410F; //page 1 starting position
                int   pageNumber = 1;
                float width      = pr.GetPageSize(pageNumber).Width - x;

                //DrawLine(ps.GetOverContent(page), 280)

                foreach (var item in items.OrderByDescending(i => i.PODID))
                {
                    var tbl = CreateTable(item, width);
                    if (pageNumber < 2)
                    {
                        if (y + tbl.TotalHeight < 280)
                        {
                            pageNumber = 2;
                            y          = 580; //page 2 starting position
                            ps.InsertPage(pageNumber, pr.GetPageSize(1));
                            var p2reader = new PdfReader(templatePage2);
                            ps.ReplacePage(p2reader, 1, 2);
                            ps.Writer.FreeReader(p2reader);
                            p2reader.Close();

                            //DrawLine(ps.GetOverContent(page), 60)
                        }
                    }
                    else
                    {
                        if (y + tbl.TotalHeight < 60)
                        {
                            pageNumber += 1;
                            y           = 580; //page n starting position
                            ps.InsertPage(pageNumber, pr.GetPageSize(1));
                            var p2reader = new PdfReader(templatePage2);
                            ps.ReplacePage(p2reader, 1, pageNumber);
                            ps.Writer.FreeReader(p2reader);
                            p2reader.Close();

                            //DrawLine(ps.GetOverContent(page), 60)
                        }
                    }

                    var ct = new ColumnText(ps.GetOverContent(pageNumber))
                    {
                        Alignment = Element.ALIGN_LEFT
                    };

                    ct.SetSimpleColumn(x, y, width, y + 100);
                    ct.AddElement(tbl);
                    ct.Go();
                    y -= tbl.TotalHeight;
                }

                AddPageNumberFooter(ps, pr.NumberOfPages, width);

                ps.FormFlattening = true;
                ps.Close();
            }

            return(pdfPath);
        }
示例#16
0
        static void Main(string[] args)
        {
            if (args.Length != 3)
            {
                System.Console.WriteLine("The correct number of arguments is 3");
                System.Console.WriteLine("Description:");
                System.Console.WriteLine("Metimpdf is the program for [met]adata [im]port into a [pdf] file");
                System.Console.WriteLine("as a part of the Math-Net.Ru Meta Data Creator Tools.");
                System.Console.WriteLine("Use:");
                System.Console.WriteLine("metimpdf <pdf file> <metadata> <output pdf file>");
                System.Console.WriteLine("Example:");
                System.Console.WriteLine("metimpdf source.pdf meta.data output.pdf");
                Console.Write("Press any key to continue . . . ");
                Console.ReadKey(true);
                return;
            }

            if (args.Length == 3)
            {
                //System.Console.WriteLine(args[0]);
                //System.Console.WriteLine(args[1]);
                //System.Console.WriteLine(args[2]);
                try{
                    string SourcePdfFile = args[0];
                    string MetadataFile  = args[1];
                    string OutputPdfFile = args[2];

                    string prismSchema = "http://prismstandard.org/namespaces/basic/2.2/";

                    // Создаем и регистрируем несуществующую в системе схему prism
                    XmpMetaFactory.SchemaRegistry.RegisterNamespace(prismSchema, "prism");

                    /**
                     * Создаём карту для корректной конвертации и вставки значений в metadata
                     * т.к. ключевые слова указанные в .data файле не существуют в пространствах
                     */
                    List <MapObject> map = new List <MapObject>();
                    map.Add(new MapObject(XmpConst.NS_DC, "Title", "title", ValueType.Alt));
                    map.Add(new MapObject(XmpConst.NS_DC, "Author", "creator", ValueType.Seq, false));
                    map.Add(new MapObject(XmpConst.NS_DC, "Keywords", "subject", ValueType.Bag, false));
                    map.Add(new MapObject(XmpConst.NS_DC, "Doi", "identifier", ValueType.Property));
                    map.Add(new MapObject(XmpConst.NS_DC, "Publisher", "publisher", ValueType.Bag));
                    map.Add(new MapObject(XmpConst.NS_DC, "Rights", "rights", ValueType.Alt));
                    map.Add(new MapObject(XmpConst.NS_DC, "Description", "description", ValueType.Alt));

                    map.Add(new MapObject(XmpConst.NS_PDF, "Keywords", ValueType.Property));
                    map.Add(new MapObject(XmpConst.NS_PDF, "Producer", ValueType.Property));

                    map.Add(new MapObject(XmpConst.NS_XMP, "CreatorTool", ValueType.Property));

                    map.Add(new MapObject(XmpConst.NS_XMP_RIGHTS, "Rights", "UsageTerms", ValueType.Alt));
                    map.Add(new MapObject(XmpConst.NS_XMP_RIGHTS, "Marked", "Marked", ValueType.Property));
                    map.Add(new MapObject(XmpConst.NS_XMP_RIGHTS, "RightsUrl", "WebStatement", ValueType.Property));

                    map.Add(new MapObject(prismSchema, "Doi", "doi", ValueType.Property));
                    map.Add(new MapObject(prismSchema, "DoiUrl", "url", ValueType.Property));
                    map.Add(new MapObject(prismSchema, "Issn", "issn", ValueType.Property));
                    map.Add(new MapObject(prismSchema, "eIssn", "eissn", ValueType.Property));
                    map.Add(new MapObject(prismSchema, "Volume", "volume", ValueType.Property));
                    map.Add(new MapObject(prismSchema, "Number", "number", ValueType.Property));
                    map.Add(new MapObject(prismSchema, "CoverDisplayDate", "coverDisplayDate", ValueType.Property));
                    map.Add(new MapObject(prismSchema, "CoverDate", "coverDate", ValueType.Property));
                    map.Add(new MapObject(prismSchema, "IssueName", "issueName", ValueType.Property));
                    map.Add(new MapObject(prismSchema, "PageRange", "pageRange", ValueType.Property));
                    map.Add(new MapObject(prismSchema, "StartingPage", "startingPage", ValueType.Property));
                    map.Add(new MapObject(prismSchema, "EndingPage", "endingPage", ValueType.Property));
                    map.Add(new MapObject(prismSchema, "AggregationType", "aggregationType", ValueType.Property));
                    map.Add(new MapObject(prismSchema, "Platform", "originPlatform", ValueType.Property));
                    map.Add(new MapObject(prismSchema, "PublicationName", "publicationName", ValueType.Property));
                    map.Add(new MapObject(prismSchema, "Edition", "edition", ValueType.Property));
                    map.Add(new MapObject(prismSchema, "Section", "section", ValueType.Property));
                    map.Add(new MapObject(prismSchema, "Subsection1", "subsection1", ValueType.Property));
                    map.Add(new MapObject(prismSchema, "Rights", "copyright", ValueType.Property));


                    // Открываем поток для чтения/записи значений
                    using (FileStream fs = new FileStream("metadata.xmp", FileMode.Create, FileAccess.ReadWrite)){
                        // Считываем все стрроки из .data файла
                        string[] lines = File.ReadAllLines(MetadataFile);

                        // Создаем словарь разбора строк в сопоставлении ключ:значение
                        Dictionary <string, string> info = new Dictionary <string, string>();

                        // цикл перебора строк для разбора в словарь ключ:значение
                        foreach (string line in lines)
                        {
                            string[] splitted = line.Split('=');          // делим строку попалам относительно знака =
                            string   key      = splitted[0].Trim();       // ключ(значение слева от = )
                            string   value    = splitted[1].Trim();       // значение(значение справа от =)
                            value = value.Substring(1, value.Length - 2); // убираем скобки {}
                            info.Add(key, value);
                        }

                        /**
                         * Создаём объект для корректной современной записи Xmp и в качестве значения конструктора
                         * передаём только поток
                         */
                        XmpWriter xmpWriter = new XmpWriter(fs);


                        xmpWriter.XmpMeta.SetProperty(prismSchema, "platform", "print");
                        xmpWriter.XmpMeta.SetProperty(prismSchema, "edition", "My print");
                        xmpWriter.XmpMeta.SetProperty(prismSchema, "section", "My print");
                        xmpWriter.XmpMeta.SetProperty(prismSchema, "subsection1", "My print");


                        // цикл перебора словаря для дальнейшего разбора
                        foreach (string key in info.Keys)
                        {
                            // цикл перебора карты на поиск соответствующих ключевым словам объектов
                            foreach (MapObject p in map)
                            {
                                if (p.Name == key)                 // если имя объекта равно ключевому слову из data то

                                /**
                                 * сохраняем значение в xmpWriter с помощь специального
                                 * упращенного метода сохранения(сам метод создан в конце класса)
                                 */
                                {
                                    SetValue(xmpWriter, p, info[key]);
                                }
                            }
                        }



                        // модификатор языка
                        XmpNode languageQualifier = new XmpNode("xml:lang", "x-default", new PropertyOptions {
                            Qualifier = true
                        });

                        // более низкий уровень взаимодействия с деревом xml для проставки дополнительных атрибутов
                        XmpNode groupNode = (xmpWriter.XmpMeta as XmpMetaImpl).Root.FindChildByName(XmpConst.NS_DC);

                        // находим элементы которым нужно указать языковую конструкцию
                        XmpNode titleDcNode        = groupNode.FindChildByName("dc:title");
                        XmpNode rightsDcNode       = groupNode.FindChildByName("dc:rights");
                        XmpNode descriptyopmDcNode = groupNode.FindChildByName("dc:description");

                        // проставляем модификатор
                        titleDcNode.GetChild(1).AddQualifier(languageQualifier);
                        rightsDcNode.GetChild(1).AddQualifier(languageQualifier);
                        descriptyopmDcNode.GetChild(1).AddQualifier(languageQualifier);

                        groupNode = (xmpWriter.XmpMeta as XmpMetaImpl).Root.FindChildByName(XmpConst.NS_XMP_RIGHTS);
                        XmpNode rightsXmpRightsNode = groupNode.FindChildByName("xmpRights:UsageTerms");
                        rightsXmpRightsNode.GetChild(1).AddQualifier(languageQualifier);

                        // Закрываем xmpWriter
                        xmpWriter.Close();
                    }     // после этой скобочки файл metadata.xmp сохранится и запишется автоматически

                    // Внедрение metadata.xmp в SourcePdfFile и вывод в OutputPdfFile
                    PdfReader  reader  = new PdfReader(SourcePdfFile);
                    PdfStamper stamper = new PdfStamper(reader, new FileStream(OutputPdfFile, FileMode.Create));
                    using (FileStream fs = File.OpenRead("metadata.xmp")){
                        byte[] buffer = new byte[fs.Length];
                        fs.Read(buffer, 0, buffer.Length);
                        stamper.XmpMetadata = buffer;
                    }

                    stamper.Close();
                    reader.Close();
                }
                // Catching iTextSharp.text.DocumentException if any
                catch (DocumentException de) {
                    throw de;
                }
                // Catching System.IO.IOException if any
                catch (IOException ioe) {
                    throw ioe;
                }
            }

            Console.Write("Press any key to continue . . . ");
            Console.ReadKey(true);
        }
示例#17
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();
                    }
                }
            }
        }