/// <summary> /// 插入图片(对图片尺寸没有要求) /// </summary> /// <param name="doc"></param> /// <param name="replaceFlag"></param> /// <param name="imgPath"></param> /// <param name="alignment">对齐方式</param> public Picture InsertPicture(DocX doc, string replaceFlag, string imgPath, string alignment) { Paragraph p = GetParagraphByReplaceFlag(doc, replaceFlag, alignment); if (p == null) { return(null); } p.ReplaceText(replaceFlag, ""); Novacode.Image img = null; try { img = doc.AddImage(imgPath); } catch (System.InvalidOperationException e) { classLims_NPOI.WriteLog(e, ""); return(null); } Novacode.Picture pic = img.CreatePicture(); //p.AppendPicture(pic); p.InsertPicture(pic); pic.Height = Convert.ToInt32(Convert.ToDouble(pic.Height) / Convert.ToDouble(pic.Width) * Convert.ToDouble(doc.PageWidth - doc.MarginLeft - doc.MarginRight)); pic.Width = Convert.ToInt32(Convert.ToDouble(doc.PageWidth - doc.MarginLeft - doc.MarginRight)); return(pic); }
{ /// <summary> /// create doc or docx /// using DOCX: Novacode /// </summary> public static void CreateDocStreamBySvgs(List <SvgDocument> svgDocs, Stream stream) { using (stream) { using (DocX doc = DocX.Create(stream)) { Novacode.Paragraph p = doc.InsertParagraph("", false); for (int i = 0; i < svgDocs.Count; i++) { using (MemoryStream ms = new MemoryStream()) { System.Drawing.Bitmap image = svgDocs[i].Draw(); image.Save(ms, ImageFormat.Bmp); ms.Seek(0, SeekOrigin.Begin); Novacode.Image img = doc.AddImage(ms); Novacode.Picture pic = img.CreatePicture(); p.AppendPicture(pic); } } doc.Save(); } } }
private static Paragraph AddPicture(Topic topic, string pictureName, DocX doc, Paragraph p) { if (topic.Snapshots == null) { return(p); } List <KeyValuePair <string, byte[]> > snapshots = topic.Snapshots.Where(item => item.Key.Contains(pictureName)).ToList(); if (snapshots.Count == 0) { return(p); } System.IO.MemoryStream myMemStream = Services.BCFServices.GetImageStreamFromBytes(snapshots.FirstOrDefault().Value, false); //System.Drawing.Image fullsizeImage = System.Drawing.Image.FromStream(myMemStream); // Add an Image to the docx file Novacode.Image img = doc.AddImage(myMemStream); //myMemStream.Close(); Novacode.Picture pic = img.CreatePicture(); //Create a image with more or less the width of the page int newWidth = 568; double ratio = Convert.ToDouble(pic.Height) / Convert.ToDouble(pic.Width); int newHeight = Convert.ToInt16(Math.Round(ratio * newWidth)); pic.Height = newHeight; pic.Width = newWidth; p = doc.InsertParagraph(""); p = doc.InsertParagraph(""); p.InsertPicture(pic); return(p); }
/// <summary> /// Insert a Picture into a Paragraph at the given text index. /// If not index is provided defaults to 0. /// </summary> /// <param name="p">The Picture to insert.</param> /// <param name="index">The text index to insert at.</param> /// <returns>The modified Paragraph.</returns> /// <example> /// <code> ///Load test document. ///using (DocX document = DocX.Create("Test.docx")) ///{ /// // Add Headers and Footers into this document. /// document.AddHeaders(); /// document.AddFooters(); /// document.DifferentFirstPage = true; /// document.DifferentOddAndEvenPages = true; /// /// // Add an Image to this document. /// Novacode.Image img = document.AddImage(directory_documents + "purple.png"); /// /// // Create a Picture from this Image. /// Picture pic = img.CreatePicture(); /// /// // Main document. /// Paragraph p0 = document.InsertParagraph("Hello"); /// p0.InsertPicture(pic, 3); /// /// // Header first. /// Paragraph p1 = document.Headers.first.InsertParagraph("----"); /// p1.InsertPicture(pic, 2); /// /// // Header odd. /// Paragraph p2 = document.Headers.odd.InsertParagraph("----"); /// p2.InsertPicture(pic, 2); /// /// // Header even. /// Paragraph p3 = document.Headers.even.InsertParagraph("----"); /// p3.InsertPicture(pic, 2); /// /// // Footer first. /// Paragraph p4 = document.Footers.first.InsertParagraph("----"); /// p4.InsertPicture(pic, 2); /// /// // Footer odd. /// Paragraph p5 = document.Footers.odd.InsertParagraph("----"); /// p5.InsertPicture(pic, 2); /// /// // Footer even. /// Paragraph p6 = document.Footers.even.InsertParagraph("----"); /// p6.InsertPicture(pic, 2); /// /// // Save this document. /// document.Save(); ///} /// </code> /// </example> public Paragraph InsertPicture(Picture p, int index = 0) { // Convert the path of this mainPart to its equilivant rels file path. string path = mainPart.Uri.OriginalString.Replace("/word/", ""); Uri rels_path = new Uri("/word/_rels/" + path + ".rels", UriKind.Relative); // Check to see if the rels file exists and create it if not. if (!Document.package.PartExists(rels_path)) HelperFunctions.CreateRelsPackagePart(Document, rels_path); // Check to see if a rel for this Picture exists, create it if not. var Id = GetOrGenerateRel(p); XElement p_xml; if (index == 0) { // Add this hyperlink as the last element. Xml.AddFirst(p.Xml); // Extract the picture back out of the DOM. p_xml = (XElement)Xml.FirstNode; } else { // Get the first run effected by this Insert Run run = GetFirstRunEffectedByEdit(index); if (run == null) { // Add this picture as the last element. Xml.Add(p.Xml); // Extract the picture back out of the DOM. p_xml = (XElement)Xml.LastNode; } else { // Split this run at the point you want to insert XElement[] splitRun = Run.SplitRun(run, index); // Replace the origional run. run.Xml.ReplaceWith ( splitRun[0], p.Xml, splitRun[1] ); // Get the first run effected by this Insert run = GetFirstRunEffectedByEdit(index); // The picture has to be the next element, extract it back out of the DOM. p_xml = (XElement)run.Xml.NextNode; } // Extract the attribute id from the Pictures Xml. XAttribute a_id = ( from e in p_xml.Descendants() where e.Name.LocalName.Equals("blip") select e.Attribute(XName.Get("embed", "http://schemas.openxmlformats.org/officeDocument/2006/relationships")) ).Single(); // Set its value to the Pictures relationships id. a_id.SetValue(Id); } return this; }
internal string GetOrGenerateRel(Picture p) { string image_uri_string = p.img.pr.TargetUri.OriginalString; // Search for a relationship with a TargetUri that points at this Image. var Id = ( from r in mainPart.GetRelationshipsByType("http://schemas.openxmlformats.org/officeDocument/2006/relationships/image") where r.TargetUri.OriginalString == image_uri_string select r.Id ).SingleOrDefault(); // If such a relation dosen't exist, create one. if (Id == null) { // Check to see if a relationship for this Picture exists and create it if not. PackageRelationship pr = mainPart.CreateRelationship(p.img.pr.TargetUri, TargetMode.Internal, "http://schemas.openxmlformats.org/officeDocument/2006/relationships/image"); Id = pr.Id; } return Id; }
/// <summary> /// Add an image to a document, create a custom view of that image (picture) and then insert it into a Paragraph using append. /// </summary> /// <param name="p">The Picture to append.</param> /// <returns>The Paragraph with the Picture now appended.</returns> /// <example> /// Add an image to a document, create a custom view of that image (picture) and then insert it into a Paragraph using append. /// <code> /// using (DocX document = DocX.Create("Test.docx")) /// { /// // Add an image to the document. /// Image i = document.AddImage(@"Image.jpg"); /// /// // Create a picture i.e. (A custom view of an image) /// Picture p = i.CreatePicture(); /// p.FlipHorizontal = true; /// p.Rotation = 10; /// /// // Create a new Paragraph. /// Paragraph par = document.InsertParagraph(); /// /// // Append content to the Paragraph. /// par.Append("Here is a cool picture") /// .AppendPicture(p) /// .Append(" don't you think so?"); /// /// // Save all changes made to this document. /// document.Save(); /// } /// </code> /// </example> public Paragraph AppendPicture(Picture p) { // Convert the path of this mainPart to its equilivant rels file path. string path = mainPart.Uri.OriginalString.Replace("/word/", ""); Uri rels_path = new Uri("/word/_rels/" + path + ".rels", UriKind.Relative); // Check to see if the rels file exists and create it if not. if (!Document.package.PartExists(rels_path)) HelperFunctions.CreateRelsPackagePart(Document, rels_path); // Check to see if a rel for this Picture exists, create it if not. var Id = GetOrGenerateRel(p); // Add the Picture Xml to the end of the Paragragraph Xml. Xml.Add(p.Xml); // Extract the attribute id from the Pictures Xml. XAttribute a_id = ( from e in Xml.Elements().Last().Descendants() where e.Name.LocalName.Equals("blip") select e.Attribute(XName.Get("embed", "http://schemas.openxmlformats.org/officeDocument/2006/relationships")) ).Single(); // Set its value to the Pictures relationships id. a_id.SetValue(Id); // For formatting such as .Bold() this.runs = Xml.Elements(XName.Get("r", DocX.w.NamespaceName)).Reverse().Take(p.Xml.Elements(XName.Get("r", DocX.w.NamespaceName)).Count()).ToList(); return this; }
/// <summary> /// Inserts a picture of a specific pixel width. Aspect ratio is maintained. Matched Picture is removed. /// </summary> private void InsertPicture(TemplGraphic graphic, int width) { if (RemovedPlaceholder || Expired || Removed) { return; } var newPic = graphic.Picture((uint)width); Paragraph.InsertPicture(newPic); Paragraph.Alignment = (graphic.Alignment ?? Paragraph.Alignment); RemovePlaceholder(); Picture = newPic; }
private static IEnumerable<TemplMatchPicture> Find(TemplRegex rxp, Paragraph p, Picture pic) { return Find<TemplMatchPicture>(rxp, pic.Description).Select(m => { m.Picture = pic; m.Width = pic.Width; m.Paragraph = p; return m; }); }
public static DocX CreateDocA(DocX template, ECEViewModel model, string source, bool cprvalue) { bool addcor = false; string Fadcorr = ""; bool special = false; string Fsnum = "[NUMBER]"; string sym = getSym(model); if (!String.IsNullOrEmpty(model.Prep)) { sym = sym.Replace("#", model.Prep.ToString()); } if (cprvalue == true) { sym = sym + "/CRP." + model.cprnum.ToString(); } if (!String.IsNullOrEmpty(model.Add) && model.cAdd == true && model.cCor == false) { sym = sym + "/Add." + model.Add.ToString(); Fadcorr = "Addendum"; addcor = true; } if (!String.IsNullOrEmpty(model.Cor) && model.cCor == true && model.cAdd == false) { sym = sym + "/Corr." + model.Cor.ToString(); Fadcorr = "Corrigendum"; addcor = true; } if (!String.IsNullOrEmpty(model.Cor) && !String.IsNullOrEmpty(model.Add) && model.cCor == true && model.cAdd == true) { sym = sym + "/Add." + model.Add.ToString() + "/Corr." + model.Cor.ToString(); Fadcorr = "Addendum Corrigendum"; addcor = true; } if (String.IsNullOrEmpty(model.Cor) && String.IsNullOrEmpty(model.Add)) { addcor = false; } if (String.IsNullOrEmpty(model.CaseYear)) { sym = sym.Replace("&", DateTime.Now.Year.ToString()); } if (!String.IsNullOrEmpty(model.CaseYear)) { sym = sym.Replace("&", model.CaseYear.ToString()); } model.tsym = sym; string[] SymStr = sym.Split('/'); string[] sym1 = SymStr.Skip(1).ToArray(); string Fsym = String.Join("/", sym1); if (Fsym.Contains("/S/")) { special = true; Fsnum = "special"; } //Create Date for Header string Fdate = model.date.ToString(); string[] d = Fdate.Split(' '); Fdate = d[0]; Fdate = formatdate(Fdate, model); //Create Distribution for Header string Fdist = getDist(model); //Create Virsions for Header string Fvirs = ""; //if (model.version1 != null) //{ // int deleteStart = 0; // int deleteEnd = 0; // //Get the array of the paragraphs containing the start and end catches // for (int i = 0; i < template.Paragraphs.Count; i++) // { // if (template.Paragraphs[i].Text.Contains("Original")) // deleteStart = i; // if (template.Paragraphs[i].Text.Contains("olang")) // deleteEnd = i; // } // if (deleteStart > 0 && deleteEnd > 0) // { // //delete from the paraIndex as the arrays will shift when a paragraph is deleted // int paraIndex = deleteStart; // for (int i = deleteStart; i <= deleteEnd; i++) // { // template.RemoveParagraphAt(paraIndex); // } // } //} //Fvirs = getVerisons(model); string Folang = ""; Folang = Olanguage(model.lang_ID); string Fatitle = "[Title]"; if (!String.IsNullOrEmpty(model.AgendaItem)) { Fatitle = model.AgendaItem.ToString(); } string Fsdate = "[Start-End Dates ]"; if (model.Sdate != null & model.Edate != null) { string sdate = model.Sdate.ToString(); string[] sd = sdate.Split(' '); sdate = sd[0]; sdate = formatdate(sdate, model); string edate = model.Edate.ToString(); string[] ed = edate.Split(' '); edate = ed[0]; edate = formatdate(edate, model); Fsdate = SessionDate(sdate, edate, model); } string Fldate = "[Start Date]"; if (model.Sdate != null & model.Edate != null) { string ldate = model.Sdate.ToString(); string[] ld = ldate.Split(' '); ldate = ld[0]; string dldate = System.Threading.Thread.CurrentThread.CurrentUICulture.DateTimeFormat.GetDayName(DateTime.Parse(ldate).DayOfWeek); ldate = formatdate(ldate, model); //Regex rx = new Regex(@"^\d+\p{Zs}", RegexOptions.Compiled); //ldate = rx.Replace(ldate, dldate+" "); ldate = dldate + " " + ldate; Fldate = ldate; } string Fanum = "[NUMBER]"; if (!String.IsNullOrEmpty(model.AgendaNum)) { Fanum = model.AgendaNum.ToString(); } if (special == false) { if (!String.IsNullOrEmpty(model.SNum)) { Fsnum = Sessionnum(model); } } if (model.qrcode == true) { string lang = language(model.lang_ID); lang = lang.Substring(0, 1); string url = "http://undocs.org/m2/QRCode.ashx?DS=" + Fsym + "&Size=2&Lang=" + lang; using (var client = new WebClient()) { //var content = client.DownloadData("https://api.qrserver.com/v1/create-qr-code/?size=66x66&data=http://undocs.org/fr/A/HRC/70"); //var content = client.DownloadData("http://undocs.org/m2/QRCode.ashx?DS=A/HRC/70&Size=2&Lang=F"); var content = client.DownloadData(url); using (var str = new MemoryStream(content)) { if (lang == "A") { Image image = template.AddImage(str); NVPicture p = image.CreatePicture(); NVFooter f = template.Footers.first; NVTable t = f.Tables[0]; //t.Rows[0].Cells[1].Paragraphs.First().AppendPicture(pR); t.Rows[0].Cells[0].Paragraphs.First().AppendPicture(p); } else { NVImage image = template.AddImage(str); NVPicture p = image.CreatePicture(); NVFooter f = template.Footers.first; NVTable t = f.Tables[0]; //t.Rows[0].Cells[1].Paragraphs.First().AppendPicture(pR); t.Rows[0].Cells[1].Paragraphs.First().AppendPicture(p); } } } } string Fcategory = ""; Fcategory = getCat(model.Cat); string FSubcategory = ""; if (model.SCat != "Not Applicable" || model.SCat != "Special Session") { FSubcategory = model.SCat.ToString(); } if (model.SCat == "Not Applicable" || model.SCat == "Special Session") { int deleteStart = 0; int deleteEnd = 0; //Get the array of the paragraphs containing the start and end catches for (int i = 0; i < template.Paragraphs.Count; i++) { if (template.Paragraphs[i].Text.Contains("subcategory")) { deleteStart = i; } if (template.Paragraphs[i].Text.Contains("subcategory")) { deleteEnd = i; } } if (deleteStart > 0 && deleteEnd > 0) { //delete from the paraIndex as the arrays will shift when a paragraph is deleted int paraIndex = deleteStart; for (int i = deleteStart; i <= deleteEnd; i++) { template.RemoveParagraphAt(paraIndex); } } } if (addcor == false) { int deleteStart = 0; int deleteEnd = 0; //Get the array of the paragraphs containing the start and end catches for (int i = 0; i < template.Paragraphs.Count; i++) { if (template.Paragraphs[i].Text.Contains("adcorr")) { deleteStart = i; } if (template.Paragraphs[i].Text.Contains("adcorr")) { deleteEnd = i; } } if (deleteStart > 0 && deleteEnd > 0) { //delete from the paraIndex as the arrays will shift when a paragraph is deleted int paraIndex = deleteStart; for (int i = deleteStart; i <= deleteEnd; i++) { template.RemoveParagraphAt(paraIndex); } } } string Fsplace = "[Session City]"; if (!String.IsNullOrEmpty(model.splace)) { Fsplace = model.splace.ToString(); } string Floca = "[Session Location]"; if (!String.IsNullOrEmpty(model.loca)) { Floca = model.loca.ToString() + ", " + Fsplace; } DateTime x = DateTime.Now; string[] info1 = info(model); template.AddCustomProperty(new CustomProperty("sym1", Fsym)); template.AddCustomProperty(new CustomProperty("symh", sym)); template.AddCustomProperty(new CustomProperty("dist", Fdist)); template.AddCustomProperty(new CustomProperty("date", Fdate)); template.AddCustomProperty(new CustomProperty("sdate", Fsdate)); template.AddCustomProperty(new CustomProperty("virs", Fvirs)); template.AddCustomProperty(new CustomProperty("snum", Fsnum)); template.AddCustomProperty(new CustomProperty("anum", Fanum)); template.AddCustomProperty(new CustomProperty("adcorr", Fadcorr)); template.AddCustomProperty(new CustomProperty("gdoc", "")); template.AddCustomProperty(new CustomProperty("gdocf", "")); template.AddCustomProperty(new CustomProperty("tlang", "")); template.AddCustomProperty(new CustomProperty("atitle", Fatitle)); template.AddCustomProperty(new CustomProperty("ldate", Fldate)); template.AddCustomProperty(new CustomProperty("loca", Floca)); template.AddCustomProperty(new CustomProperty("categ", Fcategory)); template.AddCustomProperty(new CustomProperty("subcategory", FSubcategory)); template.AddCustomProperty(new CustomProperty("splace", Fsplace)); template.AddCustomProperty(new CustomProperty("olang", Folang)); template.AddCustomProperty(new CustomProperty("Date-Generated", x)); template.AddCustomProperty(new CustomProperty("Org", "ECE")); template.AddCustomProperty(new CustomProperty("Entity", info1[0])); template.AddCustomProperty(new CustomProperty("doctype", info1[1])); template.AddCustomProperty(new CustomProperty("category", info1[2])); template.AddCustomProperty(new CustomProperty("bar", "")); for (int i = 0; i < template.Paragraphs.Count; i++) { if (template.Paragraphs[i].Text.Contains(Fsnum)) { string Fsnum1 = char.ToUpper(Fsnum[0]) + Fsnum.Substring(1); template.Paragraphs[i].ReplaceText(Fsnum, Fsnum1); break; } } if (addcor == true && cprvalue == false) { int deleteStart = 0; int deleteEnd = 0; //Get the array of the paragraphs containing the start and end catches for (int i = 0; i < template.Paragraphs.Count; i++) { if (template.Paragraphs[i].Text.Contains("*")) { deleteStart = i; } if (template.Paragraphs[i].Text.Contains(Fadcorr)) { deleteEnd = i; } } if (deleteStart > 0 && deleteEnd > 0) { //delete from the paraIndex as the arrays will shift when a paragraph is deleted int paraIndex = deleteEnd - deleteStart; paraIndex = deleteStart + paraIndex - 1; template.RemoveParagraphAt(paraIndex); } //List <string> replace = template.FindUniqueByPattern("*", RegexOptions.None); //foreach (string s in replace) //{ // if (!s.Equals("")) template.ReplaceText((s, ""); //} template.ReplaceText("*", ""); List <string> repl = template.FindUniqueByPattern(",\\s", RegexOptions.None); foreach (string rep in repl) { if (!String.IsNullOrEmpty(rep)) { template.ReplaceText(rep, ""); } } //bool flag = false; //List<List<string>> list1 = new List<List<string>>(); //List<string> list2 = new List<string>(); //foreach (Novacode.Paragraph item in template.Paragraphs) //{ // //use this if you need whole text of a paragraph // string paraText = item.Text; // var result = paraText.Split(' '); // int count = 0; // list2 = new List<string>(); // //use this if you need word by word // foreach (var data in result) // { // string word = data.ToString(); // if (word.Contains(Fsnum)) flag = true; // if (word.Contains("session")) // { // flag = false; // // list2.Add(word); // } // if (flag) // list2.Add(word); // count++; // } // // list2.RemoveAt(0); // list1.Add(list2); //} //// list1[0].Replace(list1[0], "*"); //for (int i = 0; i < list1.Count(); i++) //{ // string temp = ""; // for (int y = 0; y < list1[i].Count(); y++) // { // if (y == 0) // { // temp = list1[i][y]; // continue; // } // temp += " " + list1[i][y]; // // temp = temp.Remove(temp.IndexOf(',')-1, temp.Length); // } // int ind = temp.IndexOf("*"); // // temp = temp.Substring(ind, temp.Length - ind); // if (!temp.Equals("")) template.ReplaceText("Done", ""); //} } //using (WordprocessingDocument // document = WordprocessingDocument.Open(source, true)) //{ // var bookMarks = FindBookmarks(document.MainDocumentPart.Document); //} // Return the template now that it has been modified to hold all of our custom data. return(template); }